standard_id 0.61.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +145 -0
  3. data/README.md +236 -32
  4. data/app/channels/concerns/standard_id/cable_authentication.rb +1 -0
  5. data/app/controllers/concerns/standard_id/api_authentication.rb +30 -0
  6. data/app/controllers/concerns/standard_id/audience_verification.rb +6 -5
  7. data/app/controllers/concerns/standard_id/web_authentication.rb +29 -7
  8. data/app/controllers/standard_id/api/base_controller.rb +10 -5
  9. data/app/controllers/standard_id/api/oauth/base_controller.rb +1 -0
  10. data/app/controllers/standard_id/api/step_up_controller.rb +92 -0
  11. data/app/controllers/standard_id/web/step_up_controller.rb +83 -0
  12. data/app/mailers/standard_id/passwordless_mailer.rb +20 -2
  13. data/app/models/standard_id/client_application.rb +30 -1
  14. data/app/models/standard_id/password_credential.rb +76 -8
  15. data/app/models/standard_id/session.rb +45 -1
  16. data/app/views/standard_id/passwordless_mailer/step_up_email.html.erb +24 -0
  17. data/app/views/standard_id/passwordless_mailer/step_up_email.text.erb +12 -0
  18. data/app/views/standard_id/web/step_up/show.html.erb +65 -0
  19. data/config/brakeman.ignore +4 -0
  20. data/config/locales/en.yml +9 -0
  21. data/config/routes/api.rb +7 -0
  22. data/config/routes/web.rb +6 -0
  23. data/db/migrate/20261123000000_add_authenticated_at_to_standard_id_sessions.rb +15 -0
  24. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +49 -6
  25. data/lib/standard_id/api/token_manager.rb +7 -4
  26. data/lib/standard_id/auth_lineage.rb +39 -8
  27. data/lib/standard_id/config/schema.rb +105 -7
  28. data/lib/standard_id/email_password/authentication.rb +1 -1
  29. data/lib/standard_id/email_password.rb +4 -5
  30. data/lib/standard_id/engine.rb +10 -8
  31. data/lib/standard_id/errors.rb +58 -0
  32. data/lib/standard_id/events/definitions.rb +14 -3
  33. data/lib/standard_id/events/subscribers/passwordless_delivery_subscriber.rb +12 -5
  34. data/lib/standard_id/http_client.rb +6 -13
  35. data/lib/standard_id/jwt_service.rb +31 -2
  36. data/lib/standard_id/keyed_digest.rb +43 -5
  37. data/lib/standard_id/network_wrapper.rb +78 -0
  38. data/lib/standard_id/oauth/audiences.rb +42 -0
  39. data/lib/standard_id/oauth/authorization_code_authorization_flow.rb +1 -1
  40. data/lib/standard_id/oauth/direct_mint_flow.rb +9 -3
  41. data/lib/standard_id/oauth/oauth_session_persistence.rb +24 -9
  42. data/lib/standard_id/oauth/password_flow.rb +4 -10
  43. data/lib/standard_id/oauth/token_grant_flow.rb +31 -4
  44. data/lib/standard_id/password_pepper.rb +88 -0
  45. data/lib/standard_id/passwordless/base_strategy.rb +5 -1
  46. data/lib/standard_id/passwordless/code_handoff.rb +72 -0
  47. data/lib/standard_id/passwordless.rb +25 -0
  48. data/lib/standard_id/step_up.rb +236 -0
  49. data/lib/standard_id/testing/otp_helpers.rb +5 -5
  50. data/lib/standard_id/testing/request_helpers.rb +8 -3
  51. data/lib/standard_id/token_minter.rb +9 -4
  52. data/lib/standard_id/version.rb +1 -1
  53. data/lib/standard_id/web/session_manager.rb +9 -2
  54. data/lib/standard_id.rb +4 -0
  55. metadata +12 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c5b800c9bdd221e81804f561bee356990391ca705f62412542deb424d00fd0e9
4
- data.tar.gz: deff24e781f7147bca4d0096309f1bcbc37aa6d46295e6bdeff0d47d40805dca
3
+ metadata.gz: f4338b3e28da791aae773a472cbc7eda8a0fcc4d94ee2513f733e84f9b4185a5
4
+ data.tar.gz: 23c17a0ea7040d29787ebd23671047eb239f8cf73567c11414f0097f53f02ded
5
5
  SHA512:
6
- metadata.gz: c4fb45b06cfb55d73e765443943a18a8237f71fdb1093e152870f041c922d4e994bd9d3ff5c4015ada599a3552da9aca829bd7c5ca0fb5bc608e710a92615d7b
7
- data.tar.gz: 779383c04ce9b1d3548399fae80c08f77ed3f470d4bd9efe2b248cff0455aeb9812353b46a74f859e5e674d7e7264bd36f40b86f340696226b0979f0f1194f98
6
+ metadata.gz: e4c3dbe4a53c0a84cdc99d73fd5e46e5a820c1ad60f3fd23e5a71bd280aae8c184fcf42e814c9ef6d6e754bd519c839d4a682996a3092730eec49fd012aa646c
7
+ data.tar.gz: 43fb59a7c70eef841e53b986420a3fcbe99463de22f4d4b9cc981891be80e311aed0baf720c6df8ef149f23eb35138e552fb435280f2f7460ff8de203c87b38e
data/CHANGELOG.md CHANGED
@@ -7,6 +7,151 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.63.0] - 2026-11-24
11
+
12
+ ### Added
13
+
14
+ - **Built-in step-up e-mail.** Under built-in delivery (`c.step_up.delivery = :built_in` and
15
+ `c.passwordless.delivery = :built_in`), a step-up code (realm `c.step_up.realm`) now goes out as
16
+ `PasswordlessMailer#step_up_email` ("Confirm it's you"). It tells the user they are confirming a
17
+ sensitive action in a session that is already signed in, gives the code and its expiry, and says
18
+ what to do if it wasn't them. Copy is under `standard_id.passwordless_mailer.step_up_email.*`.
19
+ It replaces the generic `verification_email` that step-up codes used in 0.62; sign-in and
20
+ verification e-mails are unchanged, and `c.step_up.delivery = :custom` still sends nothing
21
+ built-in. See the Migration Guide, "Built-in step-up e-mail".
22
+ - **Minted vs accepted audiences (opt-in).** `c.oauth.mintable_audiences` lists the audiences
23
+ this app may issue tokens for (every `/oauth/token` grant, including the authorization-code
24
+ exchange and `client_credentials`, plus `TokenMinter` and the API step-up re-mint);
25
+ `c.oauth.accepted_audiences` lists the audiences `Api::TokenManager` accepts at decode time.
26
+ Each defaults to `c.oauth.allowed_audiences` when unset, so hosts that set neither see no
27
+ change. An identity provider can now mint per-service tokens (e.g. `aud=harness`) without
28
+ also accepting them on its own API. The production boot warning now checks the effective
29
+ accepted list. `StandardId::Oauth::Audiences.mintable` / `.accepted` return the effective
30
+ lists. See the README, "Token Audiences: Minted vs Accepted", and the Migration Guide.
31
+ (rarebit-one/rarebit-ops#494)
32
+ - **`StandardId::ProviderUnavailableError`** (an `OAuthError`: `temporarily_unavailable`, HTTP
33
+ 503) and **`StandardId::NetworkWrapper.run(provider:) { ... }`**. When the host's
34
+ `config.network_wrapper` refuses a request itself, such as an open circuit that never ran it,
35
+ or a breaker that turns the request's failure into its own error, StandardId now raises
36
+ `ProviderUnavailableError` with the wrapper's error as `cause`. Plugins can then map an outage
37
+ without knowing the host's circuit-breaker library.
38
+ - Google and Apple sign-in already turned any error into an `OAuthError` (`rescue_to_oauth_error`),
39
+ so they failed, but with the wrapper's message (circuit names, host internals) in the flash
40
+ and the API's `error_description`, and the API answered 400 `invalid_request`. They now show
41
+ "Google is temporarily unavailable", and the API answers 503 `temporarily_unavailable`.
42
+ - The paths that really returned a 500 are for the plugins that own them to fix with this
43
+ error (Apple's `revoke` / `exchange_authorization_code`, Void-Which-Binds sign-in); the
44
+ companion plugin changes detect it, so they keep working on older standard_id.
45
+ - Some errors still reach the caller unchanged:
46
+ - an error the request raises (a timeout, a refused connection) that the wrapper re-raises
47
+ - a `StandardId::OAuthError` the wrapper raises on purpose
48
+ - an error the wrapper raises after the request went through (a failing tracer: the request
49
+ may have spent a single-use code, so "try again" would be wrong)
50
+ - a programming error in the wrapper (`NetworkWrapper::PROGRAMMING_ERRORS`: `NameError`,
51
+ including `NoMethodError`, `TypeError`, `ArgumentError`), so the error tracker sees it
52
+ - `HttpClient` runs every request through `NetworkWrapper`; a plugin with its own HTTP code can
53
+ call it to get the same wrapper and error. A host that rescued its breaker's error (e.g.
54
+ `Stoplight::Error::RedLight`) around a StandardId provider call now finds it as
55
+ `error.cause`. Nothing changes without a `network_wrapper`, or for a wrapper that calls the
56
+ block. See the Migration Guide, "Provider calls refused by `network_wrapper`".
57
+
58
+ ### Fixed
59
+
60
+ - **OAuth protocol routes now send `Retry-After`.** `Api::Oauth::BaseController` renders OAuth
61
+ errors with its own handler and, unlike `Api::BaseController`, dropped the `Retry-After` header
62
+ for an error carrying a positive `retry_after`. Every `/api/oauth/*` route (`token`, `revoke`,
63
+ `introspect`, `register`, `callback/:provider`) now sends it under the same condition, through
64
+ one shared helper; body, status and error codes are unchanged. No error the gem raises on those
65
+ routes carries `retry_after` today, so the gem's own responses are unchanged. A response does
66
+ change where an error with a positive `retry_after` reaches an OAuth route from host code, for
67
+ example a `StandardId::RateLimitExceededError` (from `StandardId::RateLimiter.hit!`) or a
68
+ `StandardId::RetryDelayError` raised in `c.social.before_account` / `before_mint`, a
69
+ social-auth subscriber, or a provider plugin: it now gets the header.
70
+
71
+ ### Documentation
72
+
73
+ - README and Migration Guide now say plainly that implicit-flow tokens (`response_type=token`)
74
+ carry no `auth_time` and so always step up (use the authorization code flow with PKCE), and
75
+ that refreshed tokens keep the original sign-in's `auth_time`, so an API step-up stays recent
76
+ for `within:` but never past that one access token's lifetime: a refresh brings back the old
77
+ sign-in time.
78
+
79
+ ## [0.62.0] - 2026-11-23
80
+
81
+ ### Added
82
+
83
+ - **Step-up authentication (opt-in).** `require_recent_authentication!(within:)` in
84
+ `WebAuthentication` and `ApiAuthentication` lets an action run only when the session (or the
85
+ bearer token's new OIDC `auth_time` claim) proved the account's identity recently. Otherwise
86
+ the web guard redirects to `/step_up`, and the API guard answers RFC 9470's
87
+ `insufficient_user_authentication` 401 with `max_age`. The step-up re-proves identity with a
88
+ fresh `StandardId::Otp` code in its own realm (`c.step_up.realm`, default `"step_up"`), sent to
89
+ the account's verified e-mail or phone, plus the password where the account has one. It stamps
90
+ the session, or (API, `POST /step_up` then `/step_up/verify`) returns a fresh access token.
91
+ Publishes `authentication.step_up.started`, `.succeeded` and `.failed`. Sign-ins stamp the new
92
+ `Session#authenticated_at`, never remember-me. `auth_time` is carried through `/authorize`, the
93
+ authorization-code grant and every refresh (`RefreshToken#authenticated_at`).
94
+ `TokenMinter.mint(authenticated_at:)` sets it for a direct mint; while step-up is on, no custom
95
+ claim can. `c.step_up.token_profile_resolver` names the profile the API step-up re-mints for when
96
+ an account may hold several of the audience's bound type. Needs migration
97
+ `20261123000000_add_authenticated_at_to_standard_id_sessions` and `c.step_up.enabled = true`;
98
+ until then no routes are drawn, no claim is minted, and the guard raises a
99
+ `ConfigurationError`. See README, "Step-up authentication".
100
+ - **Password pepper (opt-in).** `c.password.pepper` hashes new passwords as
101
+ bcrypt(HMAC-SHA256(pepper, password)), so the digests cannot be cracked from
102
+ a database dump alone. Verification tries the current pepper, then
103
+ `c.password.previous_peppers`, then no pepper (`c.password.accept_unpeppered_passwords`,
104
+ default `true`), so turning it on or rotating it locks nobody out. A login
105
+ that matched anything but the current pepper re-hashes through
106
+ `PasswordCredential#rehash_password`: it publishes `credential.password.rehashed`
107
+ (new payload key `pepper_changed`), not `credential.password.changed`, and
108
+ voids that user's remember-me cookies and reset links, as a cost change does.
109
+ Logins for unknown addresses pay one dummy bcrypt comparison per candidate
110
+ pepper, matching a wrong password. With no pepper set (the default) nothing
111
+ changes. **Losing the pepper forces every password hashed under it to be
112
+ reset.** See README, "Password pepper".
113
+ - **`StandardId::Passwordless.issued_code(event)`** hands a `PASSWORDLESS_CODE_GENERATED`
114
+ subscriber the raw one-time code without putting it in the event payload, so delivery works
115
+ with `c.events.publish_records = false`. It returns the published record's code when there is
116
+ one; otherwise the code of the challenge being published right now, only for that event and a
117
+ matching `code_challenge_id`, and only while the publish runs (thread- or fiber-local through
118
+ `ActiveSupport::IsolatedExecutionState`). It returns `nil` after the publish, in another
119
+ thread, or in a job that received the payload, so a subscriber that defers delivery must read
120
+ the code first and pass the string on. The payload still never holds the code, so audit,
121
+ logging and breadcrumb subscribers cannot serialise it. `event[:code_challenge].code` keeps
122
+ working while records are published (the default). See `docs/MIGRATION_GUIDE.md`.
123
+
124
+ ### Changed
125
+
126
+ - **HMAC-signed JWTs verify under `config.previous_secret_key_bases`.** For HS256/384/512,
127
+ `JwtService.decode` tries the current `secret_key_base`, then each previous secret in order,
128
+ and moves on only when the signature doesn't match: an expired token, or one with the wrong
129
+ issuer or audience, is refused at once, as before. New tokens are still signed under the current
130
+ secret only, so refreshing an old-secret refresh token returns tokens under the new one. New
131
+ public `JwtService.symmetric_verification_keys` (current secret first, then previous ones; `[]`
132
+ for an asymmetric algorithm) lets a `JwtService.verify` caller pass
133
+ `key: JwtService.symmetric_verification_keys` for the same window. RS*/ES* keys keep rotating
134
+ through `oauth.previous_signing_keys`, and HS tokens are still refused when the configured
135
+ algorithm is asymmetric. Nothing changes unless previous secrets are listed.
136
+ - **Session tokens and RFC 7592 registration access tokens used under a previous
137
+ `secret_key_base` are re-keyed to the current one.** After a successful
138
+ `Session.authenticate_by_token`, web session-cookie load or Action Cable authentication, a
139
+ session whose `lookup_hash` (or HMAC `token_digest`) is still under a previous secret is
140
+ rewritten in one conditional `UPDATE` (new `StandardId::KeyedDigest.rekey`), so the old secret
141
+ stays needed only for credentials not used since the rotation, rather than for the longest
142
+ session lifetime (or forever, for registration access tokens). The `UPDATE` only applies while
143
+ the row still holds the values just read, skips callbacks, `updated_at` and events, runs in a
144
+ savepoint inside an open transaction, and never fails authentication: an error is logged (model,
145
+ id and error class only) and the token still authenticates. With no previous secrets listed,
146
+ nothing is hashed or written. One-time codes, authorization codes and JWTs are not re-keyed.
147
+
148
+ ### Fixed
149
+
150
+ - **The built-in passwordless mailer delivers with `c.events.publish_records = false`.** With
151
+ records off it found no code, sent nothing and reported `"failed"`; it now reads the code
152
+ through `issued_code` and reports `"sent"`. `StandardId::Testing::OtpHelpers`
153
+ (`capture_otp_code`, `capture_otp_codes`) also work with records off.
154
+
10
155
  ## [0.61.0] - 2026-11-23
11
156
 
12
157
  ### Added
data/README.md CHANGED
@@ -177,6 +177,111 @@ 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 # the engine's step-up e-mail under passwordless.delivery = :built_in;
232
+ # # or :custom: your PASSWORDLESS_CODE_GENERATED subscriber, realm "step_up"
233
+ # c.step_up.url = "/step_up" # where the web guard redirects
234
+ end
235
+ ```
236
+
237
+ **2. Guard the action.**
238
+
239
+ ```ruby
240
+ class AccountSettingsController < ApplicationController
241
+ include StandardId::WebAuthentication
242
+ before_action :authenticate_account!
243
+ before_action -> { require_recent_authentication!(within: 5.minutes) }, only: %i[edit update]
244
+ end
245
+
246
+ class Api::RecoveryCodesController < ActionController::API
247
+ include StandardId::ApiAuthentication
248
+ before_action -> { require_recent_authentication!(within: 5.minutes) }
249
+ end
250
+ ```
251
+
252
+ The guard raises `StandardId::ConfigurationError` while `c.step_up.enabled` is off or the migration has not run. It never passes or refuses silently.
253
+
254
+ **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:
255
+
256
+ | Token | `auth_time` |
257
+ | --- | --- |
258
+ | password, passwordless OTP, social, email + password grants | the grant itself |
259
+ | `authorization_code` | the browser session's `authenticated_at` at `/authorize` |
260
+ | `refresh_token` | the original grant's, carried on each refresh token (never refreshed into a newer time) |
261
+ | `TokenMinter.mint` | `authenticated_at:` when you pass it, else none |
262
+ | `client_credentials`, implicit (`response_type=token`) | none |
263
+
264
+ 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.
265
+
266
+ **Implicit-flow tokens always step up.** A token from the implicit flow (`response_type=token`) carries no `auth_time`, so every guarded action answers it with the step-up challenge, however recently the user signed in. This is deliberate. Use the authorization code flow with PKCE instead: its tokens carry the browser session's sign-in time, and it is the flow OAuth 2.1 recommends for single-page and native apps anyway.
267
+
268
+ **Refreshed tokens keep the original sign-in time.** A refresh never makes a token more recent: each refreshed access token carries the `auth_time` the grant started with (the sign-in, or for `authorization_code` the browser session's time at `/authorize`). A step-up through the API returns one access token with `auth_time` set to now, and no refresh token. So the fresh time lives on that one token only. It counts as recent for `within:` after the step-up (the guard checks on every request), and never past that token's expiry, about one access-token lifetime (`oauth.token_lifetimes[:step_up]`, else the default); whichever ends first. Once the token expires and the client refreshes, it holds the old sign-in time again, so a guarded action outside `within:` of that sign-in asks for another step-up.
269
+
270
+ **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.
271
+
272
+ **API flow.** A stale or `auth_time`-less token gets RFC 9470's challenge:
273
+
274
+ ```http
275
+ HTTP/1.1 401 Unauthorized
276
+ WWW-Authenticate: Bearer realm="StandardId", error="insufficient_user_authentication", error_description="A more recent authentication is required", max_age=300
277
+
278
+ {"error":"insufficient_user_authentication","error_description":"A more recent authentication is required","max_age":300}
279
+ ```
280
+
281
+ 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.
282
+
283
+ **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. Under built-in delivery (`c.step_up.delivery = :built_in` and `c.passwordless.delivery = :built_in`) it goes out as `PasswordlessMailer#step_up_email` ("Confirm it's you"), which tells the user they are confirming a sensitive action in a session that is already signed in, when the code expires, and what to do if it wasn't them. Its copy is under `standard_id.passwordless_mailer.step_up_email.*`. With `c.step_up.delivery = :custom` the engine sends nothing, and your `PASSWORDLESS_CODE_GENERATED` subscriber sees `realm: "step_up"` in the payload. There is no built-in SMS. 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).
284
+
180
285
  ### OAuth Hardening Options
181
286
 
182
287
  Two spec-conformance settings default to the historical (looser) behaviour so
@@ -324,6 +429,41 @@ token needs `client_id:` (the refresh grant matches on it) and, under a
324
429
  judged as `:unspecified`. `expires_in:` must be positive. The grant is not
325
430
  reachable from `/oauth/token`.
326
431
 
432
+ ### Token Audiences: Minted vs Accepted
433
+
434
+ `config.oauth.allowed_audiences` does two jobs: it lists the audiences this app
435
+ may issue tokens for, and the audiences its API accepts in a bearer's `aud`. An
436
+ identity provider that mints tokens for *other* services needs those jobs apart,
437
+ or every audience it mints is also accepted on its own API. Two settings split
438
+ them:
439
+
440
+ ```ruby
441
+ StandardId.configure do |config|
442
+ # What this app mints: every /oauth/token grant (the authorization-code
443
+ # exchange, client_credentials, password, refresh, …), TokenMinter and the
444
+ # API step-up re-mint refuse any other audience (400 invalid_request).
445
+ config.oauth.mintable_audiences = %w[sidekick harness inference]
446
+
447
+ # What its API accepts: Api::TokenManager decodes bearers against this, so a
448
+ # token for any other audience is an invalid token (401).
449
+ config.oauth.accepted_audiences = %w[sidekick]
450
+ end
451
+ ```
452
+
453
+ Each defaults to `allowed_audiences` when unset (`nil`), so a host that sets
454
+ neither keeps one list doing both jobs, exactly as before. When a host sets one,
455
+ it wins for that side; `allowed_audiences` still supplies the other. An empty
456
+ effective list means no check on that side, as an empty `allowed_audiences`
457
+ always has, and an empty effective accepted list in production logs the boot
458
+ warning (setting only `mintable_audiences` does not silence it). The audience is
459
+ checked when the token is minted, so for the authorization-code flow that is the
460
+ code exchange at `/oauth/token`; `/authorize` itself, including the implicit
461
+ flow, does not check either list. The Web (cookie) token manager reads no JWT,
462
+ so neither list applies to browser sessions. `JwtService.decode` and
463
+ `JwtService.verify` check only the `allowed_audiences:` you pass them.
464
+ `StandardId::Oauth::Audiences.mintable` / `.accepted` return the effective
465
+ lists.
466
+
327
467
  ### Custom Token Claims
328
468
 
329
469
  You can add additional JWT claims for any token issued through the OAuth token endpoint by mapping scopes to claim names and providing callbacks to resolve each claim. Scopes listed in `oauth.scope_claims` are evaluated against the requested token scopes; when a scope matches, every claim listed for that scope is resolved via the callable defined in `oauth.claim_resolvers`.
@@ -420,9 +560,10 @@ stay in the host controller.
420
560
  Two things to know. The document's `resource` and the challenge URL are built from
421
561
  the request origin, as RFC 9728 §3.3 requires, so pin `Host` (`config.hosts`, or at
422
562
  the proxy): the document is served with `Cache-Control: public`. And a token minted
423
- for an audience outside `config.oauth.allowed_audiences` is refused at decode time
424
- as `401 invalid_token`, before the concern sees it; the `403 insufficient_scope` is
425
- for a token minted for another *allowed* audience.
563
+ for an audience outside the accepted audiences (`config.oauth.accepted_audiences`,
564
+ else `allowed_audiences`) is refused at decode time as `401 invalid_token`, before
565
+ the concern sees it; the `403 insufficient_scope` is for a token minted for another
566
+ *accepted* audience.
426
567
 
427
568
  ### Dynamic Client Registration (RFC 7591 / RFC 7592)
428
569
 
@@ -638,8 +779,23 @@ c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}"
638
779
  ```
639
780
 
640
781
  It must call the block and return its result. A timeout or refused connection
641
- raises inside the wrapper, and whatever the wrapper raises (an open circuit,
642
- say) reaches the provider's caller as is. `provider` is the plugin's name
782
+ raises inside the wrapper and, re-raised, reaches the provider as is. When the
783
+ wrapper refuses the request itself (an open circuit that never ran it, or a
784
+ breaker that turns the request's failure into its own error), StandardId raises
785
+ `StandardId::ProviderUnavailableError` instead, with the wrapper's error as its
786
+ `cause`. That is an `OAuthError`, so the web callback sends the user back to the
787
+ login page with "Google is temporarily unavailable" and the API answers 503
788
+ `temporarily_unavailable`. The circuit's own message never reaches the user.
789
+
790
+ Some errors from the wrapper are passed through unchanged:
791
+ - a `StandardId::OAuthError` it raises on purpose
792
+ - an error it raises after the block returned (the request went through, so
793
+ "try again" would be wrong)
794
+ - a programming error (`NameError`/`NoMethodError`, `TypeError`,
795
+ `ArgumentError`; see `StandardId::NetworkWrapper::PROGRAMMING_ERRORS`), so
796
+ your error tracker sees the bug
797
+
798
+ `provider` is the plugin's name
643
799
  (`:google`, `:apple`, ...), or `:standard_id` for a plugin release that does not
644
800
  pass one yet. A lambda must take the block as `&block`; the boot check rejects
645
801
  one that doesn't, since it would silently skip the request.
@@ -827,23 +983,33 @@ Subscribe to the `PASSWORDLESS_CODE_GENERATED` event to deliver OTP codes:
827
983
  # config/initializers/standard_id_events.rb
828
984
  StandardId::Events.subscribe(StandardId::Events::PASSWORDLESS_CODE_GENERATED) do |event|
829
985
  next if event[:skip_sender] # Otp.issue(delivery: :manual) — the caller delivers
986
+ code = StandardId::Passwordless.issued_code(event)
830
987
  case event[:channel]
831
988
  when "email"
832
- UserMailer.send_code(event[:identifier], event[:code_challenge].code).deliver_now
989
+ UserMailer.send_code(event[:identifier], code).deliver_now
833
990
  when "sms"
834
- SmsService.send_code(event[:identifier], event[:code_challenge].code)
991
+ SmsService.send_code(event[:identifier], code)
835
992
  end
836
993
  end
837
994
  ```
838
995
 
996
+ `StandardId::Passwordless.issued_code(event)` returns the raw code while the event is being
997
+ published, and `nil` afterwards or on another thread, so read it in the subscriber and pass the
998
+ string on. The code is never part of the payload: audit and event-logging subscribers serialise
999
+ payloads, and the code would end up in their rows. It works with `c.events.publish_records = false`,
1000
+ where the payload carries `code_challenge_id` instead of the record. `event[:code_challenge].code`
1001
+ still works while records are published.
1002
+
839
1003
  Set `c.passwordless.delivery = :custom` (the default) so the engine's built-in
840
1004
  `PasswordlessMailer` stays out of the way; with `:built_in` the engine emails
841
1005
  the code itself — `otp_email` ("Your sign-in code") for the `"authentication"`
842
- realm and `verification_email` ("Your verification code") for every other realm
843
- (WebEngine `verify_email`, `Otp.issue` contact verification / step-up). There is
844
- no built-in SMS delivery. The copy is in `config/locales/en.yml` under
845
- `standard_id.passwordless_mailer.{otp_email,verification_email}.*` (`subject`,
846
- `greeting`, `intro`, `expiry`, `ignore`, `footer`); override any key in your own
1006
+ realm, `step_up_email` ("Confirm it's you") for the step-up realm
1007
+ (`c.step_up.realm`), and `verification_email` ("Your verification code") for
1008
+ every other realm (WebEngine `verify_email`, `Otp.issue` contact verification).
1009
+ There is no built-in SMS delivery. The copy is in `config/locales/en.yml` under
1010
+ `standard_id.passwordless_mailer.{otp_email,step_up_email,verification_email}.*`
1011
+ (`subject`, `greeting`, `intro`, `expiry`, `ignore`, `footer`; `step_up_email`
1012
+ has `warning` in place of `ignore`); override any key in your own
847
1013
  locale files, or the templates in `app/views/standard_id/passwordless_mailer/`.
848
1014
  An assigned `c.passwordless.mailer_subject` still sets the sign-in subject. The subscriber runs synchronously inside the request, so
849
1015
  `I18n.locale`, `Current.*` and the like are still available.
@@ -859,10 +1025,12 @@ parent's `default from:` does not apply to them.
859
1025
  Event payload includes:
860
1026
  - `channel` - `"email"` or `"sms"`
861
1027
  - `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`
1028
+ - `code_challenge` - The code challenge record (left out under `c.events.publish_records = false`).
1029
+ The raw code exists only on this in-memory record: the database stores an HMAC of it
1030
+ (`code_digest`), and the record does not serialise it. Read the code with
1031
+ `StandardId::Passwordless.issued_code(event)` (or `.code` on the record) in the subscriber and
1032
+ pass the string on; a challenge reloaded later (e.g. in a job that received the record) returns
1033
+ `nil`
866
1034
  - `expires_at` - When the code expires
867
1035
  - `realm` - The OTP realm (`"authentication"` for sign-in)
868
1036
  - `skip_sender` - `true` for `Otp.issue(delivery: :manual)`; don't deliver
@@ -1010,6 +1178,9 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1010
1178
  | | `authentication.password.failed` | `account_lookup`, `error_code`, `error_message` | After password verification fails |
1011
1179
  | | `authentication.otp.failed` | `identifier`, `channel`, `error_code`, `error_message` | After OTP verification fails |
1012
1180
  | | `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+) |
1181
+ | | `authentication.step_up.started` | `account`, `channel` | A step-up code was issued to a signed-in account (`c.step_up`) |
1182
+ | | `authentication.step_up.succeeded` | `account`, `channel`, `methods` | The account re-proved its identity (`methods`: `["otp"]` or `["otp", "password"]`) |
1183
+ | | `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
1184
  | Session | `session.creating` | `account`, `session_type`, `ip_address`, `user_agent` | Before a session record is created |
1014
1185
  | | `session.created` | `session`, `account`, `session_type`, `token_issued`, `ip_address`, `user_agent` | After session persistence completes |
1015
1186
  | | `session.validating` | `session` | Before validating an existing session |
@@ -1055,7 +1226,7 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1055
1226
  | | `credential.password.reset_initiated` | `credential`, `account`, `reset_token_expires_at` | After a password reset is initiated |
1056
1227
  | | `credential.password.reset_completed` | `credential`, `account` | After a password reset is confirmed |
1057
1228
  | | `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 |
1229
+ | | `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
1230
  | | `credential.client_secret.created` | `credential`, `client_id` | After a client secret is created |
1060
1231
  | | `credential.client_secret.rotated` | `credential`, `client_id`, `old_secret_revoked_at` | After a client secret rotation |
1061
1232
 
@@ -1526,8 +1697,9 @@ in front of the endpoint. The `resource` parameter is ignored until
1526
1697
  (RFC 8707 §2).
1527
1698
 
1528
1699
  For a client with no registered default, a client-supplied `audience` is taken as
1529
- is, so `audience_scopes` enforcement for such clients is only as strong as
1530
- `config.oauth.allowed_audiences` at the token endpoint.
1700
+ is, so `audience_scopes` enforcement for such clients is only as strong as the
1701
+ mintable audiences (`config.oauth.mintable_audiences`, else `allowed_audiences`) at
1702
+ the token endpoint.
1531
1703
 
1532
1704
  **Which scope?** `config.oauth.authorize_scope_resolver` normalises the requested
1533
1705
  scope once the client and audience are known and before `audience_scopes` is
@@ -2043,7 +2215,9 @@ module StandardId
2043
2215
  end
2044
2216
  ```
2045
2217
 
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.
2218
+ 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.
2219
+
2220
+ When the host's wrapper refuses a request itself (an open circuit), `HttpClient` raises `StandardId::ProviderUnavailableError`, an `OAuthError`, so `rescue_to_oauth_error` passes it through and the sign-in fails as "temporarily unavailable" rather than with the circuit's message. A plugin with its own error for an unreachable provider rescues it next to its transport errors (guard with `defined?(StandardId::ProviderUnavailableError)` to support older releases). A plugin that makes requests without `HttpClient` runs them through `StandardId::NetworkWrapper.run(provider: :github) { ... }` to get the same wrapper and the same error.
2047
2221
 
2048
2222
  **Required interface:** `provider_name`, `authorization_url`, `get_user_info`.
2049
2223
 
@@ -2222,8 +2396,9 @@ patch "/login_verify", params: { code: code }
2222
2396
  codes = capture_otp_codes { ... } # every code issued in the block: identifier, channel, realm, code
2223
2397
  ```
2224
2398
 
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
2399
+ They read `PASSWORDLESS_CODE_GENERATED` with `StandardId::Passwordless.issued_code`, as a delivery
2400
+ subscriber does, so they work whether or not `c.events.publish_records` is on. A challenge you
2401
+ create yourself
2227
2402
  (`CodeChallenge.create!(code: "123456", ...)` or the `:standard_id_code_challenge` factory) still
2228
2403
  verifies with the code you gave it.
2229
2404
 
@@ -2259,8 +2434,10 @@ bundle exec rspec spec/controllers/
2259
2434
  ### Rotating `secret_key_base`
2260
2435
 
2261
2436
  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:
2437
+ stored as digests keyed on `secret_key_base`, and JWTs signed with HS256/384/512 (the default
2438
+ `oauth.signing_algorithm` is `:hs256`) are signed with it, so changing it invalidates all of them:
2439
+ everyone is signed out and every access and refresh token fails. To rotate without that, list the
2440
+ old secret, newest first:
2264
2441
 
2265
2442
  ```ruby
2266
2443
  StandardId.configure do |c|
@@ -2270,11 +2447,41 @@ end
2270
2447
 
2271
2448
  Digests are then still looked up and verified under the old secret (one indexed query covers every
2272
2449
  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:
2450
+ (`StandardId::KeyedDigest`). HMAC-signed JWTs work the same way: `JwtService.decode` verifies a
2451
+ token under the current secret and then under each previous one, while `encode` always signs with
2452
+ the current secret, so access and refresh tokens issued before the rotation keep working until they
2453
+ expire and every refreshed token is signed under the new secret. Code that calls the config-free
2454
+ `JwtService.verify` itself can pass `key: StandardId::JwtService.symmetric_verification_keys` for the
2455
+ same window. Asymmetric signing keys (RS*/ES*) are unaffected: rotate those with
2456
+ `oauth.previous_signing_keys`.
2457
+
2458
+ **Credentials move to the new secret when they are used.**
2459
+ - A session token, or an RFC 7592 registration access token, that authenticates under a previous
2460
+ secret is re-keyed on the spot. Its `lookup_hash`/`token_digest`, or its digest, is rewritten
2461
+ under the current secret in a single conditional UPDATE.
2462
+ - This happens on the authenticating paths: `Session.authenticate_by_token`, the web session
2463
+ cookie, Action Cable, and the RFC 7592 endpoints.
2464
+ - A credential that already matches under the current secret causes no write. A write that fails
2465
+ (a read-only replica, a lock timeout) is logged and the request still succeeds; that credential
2466
+ is simply tried again next time.
2467
+ - A refresh grant always returns tokens signed under the current secret.
2468
+
2469
+ **How long to keep the old secret.** Only credentials that have not been used since the rotation
2470
+ still depend on it. Keep the entry for as long as you are willing to wait for idle users to come
2471
+ back: once you remove it, anything untouched since the rotation stops working. Those users sign in
2472
+ again, and a client re-registers. The longest lifetime you issue is the point after which nothing
2473
+ can depend on the old secret any more:
2474
+ - `session.*_lifetime`
2475
+ - long-lived `ServiceSession`s
2476
+ - `oauth.refresh_token_lifetime`
2477
+ - registration access tokens, which last as long as their client
2478
+
2479
+ One-time codes and authorization codes are single-use and short-lived, so they are not rewritten.
2480
+ They need the entry only for `passwordless.code_ttl` (10 minutes by default) and the authorization
2481
+ code TTL (10 minutes).
2482
+
2483
+ This covers StandardId's own digests and HMAC-signed JWTs only. The rest of the app needs Rails'
2484
+ rotations too:
2278
2485
 
2279
2486
  - **Cookies**, including the encrypted `session_token` cookie and the Rails session that carry the
2280
2487
  web session: `config.action_dispatch.cookies_rotations` (see the Rails security guide,
@@ -2282,9 +2489,6 @@ This covers StandardId's own digests only. The rest of the app needs Rails' rota
2282
2489
  - **Message verifiers** (`generates_token_for`, so remember-me and password-reset tokens, and the
2283
2490
  signed passwordless OTP payload): `Rails.application.message_verifiers.rotate(secret_key_base:
2284
2491
  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
2492
 
2289
2493
  ## OTP Start Limits
2290
2494
 
@@ -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
@@ -6,26 +6,27 @@ module StandardId
6
6
  # StandardId enforces audience in three layers:
7
7
  #
8
8
  # 1. At encode time (`Oauth::TokenGrantFlow#validate_audience!`):
9
- # rejects issuance of tokens with an audience outside the global
10
- # `StandardId.config.oauth.allowed_audiences` list.
9
+ # rejects issuance of tokens with an audience outside the mintable
10
+ # list (`config.oauth.mintable_audiences`, else `allowed_audiences`).
11
11
  # 2. At decode time (`JwtService.decode(..., allowed_audiences:)`):
12
12
  # rejects tokens whose `aud` claim does not match the caller-supplied
13
13
  # list, raising `StandardId::InvalidAudienceError`. The engine's
14
14
  # `Api::TokenManager#verify_jwt_token` wires this automatically when
15
- # `StandardId.config.oauth.allowed_audiences` is non-empty — a
15
+ # the accepted list (`config.oauth.accepted_audiences`, else
16
+ # `allowed_audiences`) is non-empty — a
16
17
  # mismatch there is normalised to the same 401 "invalid token"
17
18
  # response as a bad signature. Call sites that pass no arguments
18
19
  # to `decode` directly still skip aud checks by design.
19
20
  # 3. At the controller, via this concern: layers on top as
20
21
  # per-endpoint defense-in-depth. Required when a controller serves
21
- # a strict subset of the global allowed audiences (e.g., the global
22
+ # a strict subset of the global accepted audiences (e.g., the global
22
23
  # list is `%w[web api admin]` but `AdminController` must only
23
24
  # accept `admin`).
24
25
  #
25
26
  # With the global decode-time check now automatic, this concern is
26
27
  # primarily useful for tightening the allowed audience per controller,
27
28
  # not for plugging the "controller forgot to verify aud" gap (which
28
- # is closed globally when `config.oauth.allowed_audiences` is set).
29
+ # is closed globally when the accepted audiences are set).
29
30
  #
30
31
  # In addition, when `StandardId.config.oauth.audience_profile_types` is set,
31
32
  # this concern enforces the audience → profile-type binding: after the