standard_id 0.62.0 → 0.64.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 2362d21d45d2771288474468d9f32f18fd4be058329aafeae789e05a4ad6339f
4
- data.tar.gz: 9b3780603bc7a3a76d936a2d780bc95522bd55034960098c1bef9c476b154211
3
+ metadata.gz: 299bfc41d084764b04761feb2ad82437e7ac0cd3ea4dd47667c4e021519211ad
4
+ data.tar.gz: 17c66fdb33e21a1f9b2d694d9e310193133557617b000962089a39db1eb4288e
5
5
  SHA512:
6
- metadata.gz: f0eaa52443d01056cc784627aceed9bef678249069ab66150091871b4aa985f70ebae651e6271219623a5045a0da0b6c61342e996e7660d946c8e9af3842314b
7
- data.tar.gz: 67737af10630f42f4625d309dbf872e9a97c6d0fc1d25165000af58e5a34cecb95e87996e2b874d579c750add493d74f9fd3bb712e9c7c9b2db56e751344067a
6
+ metadata.gz: '08cd8132db371312d928220af8f3a520bd9cc5610c02e255a17e298d5516001a82caabf9c22b16d48898d2f47834742cce8e87f0c4c75389448b3aa82a6aedfc'
7
+ data.tar.gz: '0867392da53c2a1750bec89e41339e2166a63477c8ed88b1553f33a90ecad045b1026ff9c4fda74184017585ce5388533b6aa0d37858ced36586e994bb2eb469'
data/CHANGELOG.md CHANGED
@@ -7,6 +7,95 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.64.0] - 2026-11-25
11
+
12
+ ### Added
13
+
14
+ - **`config.network_wrapper_passthrough_errors`.** Errors the host's `network_wrapper` raises
15
+ that mean its own setup is wrong, not that the provider is down, reach the caller unchanged
16
+ instead of becoming `ProviderUnavailableError`. An example is `StandardCircuit::UnknownCircuit`
17
+ for a circuit that was never registered. Without the setting, such a misconfiguration shows
18
+ users "temporarily unavailable" and never reaches the error tracker. Entries are classes or
19
+ class-name Strings; a String is resolved when a wrapper error is handled, so it may name a
20
+ class from a gem that isn't loaded, and a name that resolves to nothing is ignored. Defaults
21
+ to `[]`, so nothing changes unless you set it.
22
+ - **`Retry-After` for a refused provider call.** `ProviderUnavailableError` now has
23
+ `retry_after` (Integer seconds, or nil). `NetworkWrapper` fills it in from the wrapper's
24
+ error: a `retry_after` that is a `Time` (seconds until then) or a number of seconds, or else
25
+ `cool_off_time` in seconds, as Stoplight's `RedLight` provides. It is duck-typed and assumes
26
+ no breaker library. The API's 503 `temporarily_unavailable` responses, such as
27
+ `/api/oauth/callback/:provider`, then send a `Retry-After` header. Errors that say nothing
28
+ get no header, as before.
29
+
30
+ ## [0.63.0] - 2026-11-24
31
+
32
+ ### Added
33
+
34
+ - **Built-in step-up e-mail.** Under built-in delivery (`c.step_up.delivery = :built_in` and
35
+ `c.passwordless.delivery = :built_in`), a step-up code (realm `c.step_up.realm`) now goes out as
36
+ `PasswordlessMailer#step_up_email` ("Confirm it's you"). It tells the user they are confirming a
37
+ sensitive action in a session that is already signed in, gives the code and its expiry, and says
38
+ what to do if it wasn't them. Copy is under `standard_id.passwordless_mailer.step_up_email.*`.
39
+ It replaces the generic `verification_email` that step-up codes used in 0.62; sign-in and
40
+ verification e-mails are unchanged, and `c.step_up.delivery = :custom` still sends nothing
41
+ built-in. See the Migration Guide, "Built-in step-up e-mail".
42
+ - **Minted vs accepted audiences (opt-in).** `c.oauth.mintable_audiences` lists the audiences
43
+ this app may issue tokens for (every `/oauth/token` grant, including the authorization-code
44
+ exchange and `client_credentials`, plus `TokenMinter` and the API step-up re-mint);
45
+ `c.oauth.accepted_audiences` lists the audiences `Api::TokenManager` accepts at decode time.
46
+ Each defaults to `c.oauth.allowed_audiences` when unset, so hosts that set neither see no
47
+ change. An identity provider can now mint per-service tokens (e.g. `aud=harness`) without
48
+ also accepting them on its own API. The production boot warning now checks the effective
49
+ accepted list. `StandardId::Oauth::Audiences.mintable` / `.accepted` return the effective
50
+ lists. See the README, "Token Audiences: Minted vs Accepted", and the Migration Guide.
51
+ (rarebit-one/rarebit-ops#494)
52
+ - **`StandardId::ProviderUnavailableError`** (an `OAuthError`: `temporarily_unavailable`, HTTP
53
+ 503) and **`StandardId::NetworkWrapper.run(provider:) { ... }`**. When the host's
54
+ `config.network_wrapper` refuses a request itself, such as an open circuit that never ran it,
55
+ or a breaker that turns the request's failure into its own error, StandardId now raises
56
+ `ProviderUnavailableError` with the wrapper's error as `cause`. Plugins can then map an outage
57
+ without knowing the host's circuit-breaker library.
58
+ - Google and Apple sign-in already turned any error into an `OAuthError` (`rescue_to_oauth_error`),
59
+ so they failed, but with the wrapper's message (circuit names, host internals) in the flash
60
+ and the API's `error_description`, and the API answered 400 `invalid_request`. They now show
61
+ "Google is temporarily unavailable", and the API answers 503 `temporarily_unavailable`.
62
+ - The paths that really returned a 500 are for the plugins that own them to fix with this
63
+ error (Apple's `revoke` / `exchange_authorization_code`, Void-Which-Binds sign-in); the
64
+ companion plugin changes detect it, so they keep working on older standard_id.
65
+ - Some errors still reach the caller unchanged:
66
+ - an error the request raises (a timeout, a refused connection) that the wrapper re-raises
67
+ - a `StandardId::OAuthError` the wrapper raises on purpose
68
+ - an error the wrapper raises after the request went through (a failing tracer: the request
69
+ may have spent a single-use code, so "try again" would be wrong)
70
+ - a programming error in the wrapper (`NetworkWrapper::PROGRAMMING_ERRORS`: `NameError`,
71
+ including `NoMethodError`, `TypeError`, `ArgumentError`), so the error tracker sees it
72
+ - `HttpClient` runs every request through `NetworkWrapper`; a plugin with its own HTTP code can
73
+ call it to get the same wrapper and error. A host that rescued its breaker's error (e.g.
74
+ `Stoplight::Error::RedLight`) around a StandardId provider call now finds it as
75
+ `error.cause`. Nothing changes without a `network_wrapper`, or for a wrapper that calls the
76
+ block. See the Migration Guide, "Provider calls refused by `network_wrapper`".
77
+
78
+ ### Fixed
79
+
80
+ - **OAuth protocol routes now send `Retry-After`.** `Api::Oauth::BaseController` renders OAuth
81
+ errors with its own handler and, unlike `Api::BaseController`, dropped the `Retry-After` header
82
+ for an error carrying a positive `retry_after`. Every `/api/oauth/*` route (`token`, `revoke`,
83
+ `introspect`, `register`, `callback/:provider`) now sends it under the same condition, through
84
+ one shared helper; body, status and error codes are unchanged. No error the gem raises on those
85
+ routes carries `retry_after` today, so the gem's own responses are unchanged. A response does
86
+ change where an error with a positive `retry_after` reaches an OAuth route from host code, for
87
+ example a `StandardId::RateLimitExceededError` (from `StandardId::RateLimiter.hit!`) or a
88
+ `StandardId::RetryDelayError` raised in `c.social.before_account` / `before_mint`, a
89
+ social-auth subscriber, or a provider plugin: it now gets the header.
90
+
91
+ ### Documentation
92
+
93
+ - README and Migration Guide now say plainly that implicit-flow tokens (`response_type=token`)
94
+ carry no `auth_time` and so always step up (use the authorization code flow with PKCE), and
95
+ that refreshed tokens keep the original sign-in's `auth_time`, so an API step-up stays recent
96
+ for `within:` but never past that one access token's lifetime: a refresh brings back the old
97
+ sign-in time.
98
+
10
99
  ## [0.62.0] - 2026-11-23
11
100
 
12
101
  ### Added
data/README.md CHANGED
@@ -228,7 +228,8 @@ StandardId.configure do |c|
228
228
  c.step_up.enabled = true
229
229
  # c.step_up.max_age = 300 # default `within:`, in seconds
230
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"
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"
232
233
  # c.step_up.url = "/step_up" # where the web guard redirects
233
234
  end
234
235
  ```
@@ -258,10 +259,14 @@ The guard raises `StandardId::ConfigurationError` while `c.step_up.enabled` is o
258
259
  | `authorization_code` | the browser session's `authenticated_at` at `/authorize` |
259
260
  | `refresh_token` | the original grant's, carried on each refresh token (never refreshed into a newer time) |
260
261
  | `TokenMinter.mint` | `authenticated_at:` when you pass it, else none |
261
- | `client_credentials`, implicit | none |
262
+ | `client_credentials`, implicit (`response_type=token`) | none |
262
263
 
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.
264
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
+
265
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.
266
271
 
267
272
  **API flow.** A stale or `auth_time`-less token gets RFC 9470's challenge:
@@ -275,7 +280,7 @@ WWW-Authenticate: Bearer realm="StandardId", error="insufficient_user_authentica
275
280
 
276
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.
277
282
 
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).
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).
279
284
 
280
285
  ### OAuth Hardening Options
281
286
 
@@ -424,6 +429,41 @@ token needs `client_id:` (the refresh grant matches on it) and, under a
424
429
  judged as `:unspecified`. `expires_in:` must be positive. The grant is not
425
430
  reachable from `/oauth/token`.
426
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
+
427
467
  ### Custom Token Claims
428
468
 
429
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`.
@@ -520,9 +560,10 @@ stay in the host controller.
520
560
  Two things to know. The document's `resource` and the challenge URL are built from
521
561
  the request origin, as RFC 9728 §3.3 requires, so pin `Host` (`config.hosts`, or at
522
562
  the proxy): the document is served with `Cache-Control: public`. And a token minted
523
- for an audience outside `config.oauth.allowed_audiences` is refused at decode time
524
- as `401 invalid_token`, before the concern sees it; the `403 insufficient_scope` is
525
- 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.
526
567
 
527
568
  ### Dynamic Client Registration (RFC 7591 / RFC 7592)
528
569
 
@@ -738,8 +779,43 @@ c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}"
738
779
  ```
739
780
 
740
781
  It must call the block and return its result. A timeout or refused connection
741
- raises inside the wrapper, and whatever the wrapper raises (an open circuit,
742
- 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
+ When the wrapper's error says how long to wait, the 503 carries a `Retry-After`
790
+ header: StandardId reads `retry_after` (a `Time` or a number of seconds) or,
791
+ failing that, `cool_off_time` (seconds) from it, as Stoplight's `RedLight`
792
+ provides. It knows no breaker library, so any error with those methods works.
793
+
794
+ Some errors from the wrapper are passed through unchanged:
795
+ - a `StandardId::OAuthError` it raises on purpose
796
+ - an error it raises after the block returned (the request went through, so
797
+ "try again" would be wrong)
798
+ - a programming error (`NameError`/`NoMethodError`, `TypeError`,
799
+ `ArgumentError`; see `StandardId::NetworkWrapper::PROGRAMMING_ERRORS`), so
800
+ your error tracker sees the bug
801
+ - an error you list in `config.network_wrapper_passthrough_errors`
802
+
803
+ That last setting is for errors that mean your own setup is wrong rather than
804
+ the provider being down. `StandardCircuit.run` raises
805
+ `StandardCircuit::UnknownCircuit` (not a programming error) when no circuit is
806
+ registered under the name, and without the setting that misconfiguration would
807
+ look like an outage to users and never reach your error tracker:
808
+
809
+ ```ruby
810
+ c.network_wrapper_passthrough_errors = ["StandardCircuit::UnknownCircuit"]
811
+ ```
812
+
813
+ Entries are classes or class names. A name is resolved when a wrapper error is
814
+ handled, so it may name a class from a gem that isn't loaded; a name that
815
+ resolves to nothing is ignored. An error passes through when it `is_a?` any
816
+ entry. Errors the request itself raised are passed through regardless.
817
+
818
+ `provider` is the plugin's name
743
819
  (`:google`, `:apple`, ...), or `:standard_id` for a plugin release that does not
744
820
  pass one yet. A lambda must take the block as `&block`; the boot check rejects
745
821
  one that doesn't, since it would silently skip the request.
@@ -947,11 +1023,13 @@ still works while records are published.
947
1023
  Set `c.passwordless.delivery = :custom` (the default) so the engine's built-in
948
1024
  `PasswordlessMailer` stays out of the way; with `:built_in` the engine emails
949
1025
  the code itself — `otp_email` ("Your sign-in code") for the `"authentication"`
950
- realm and `verification_email` ("Your verification code") for every other realm
951
- (WebEngine `verify_email`, `Otp.issue` contact verification / step-up). There is
952
- no built-in SMS delivery. The copy is in `config/locales/en.yml` under
953
- `standard_id.passwordless_mailer.{otp_email,verification_email}.*` (`subject`,
954
- `greeting`, `intro`, `expiry`, `ignore`, `footer`); override any key in your own
1026
+ realm, `step_up_email` ("Confirm it's you") for the step-up realm
1027
+ (`c.step_up.realm`), and `verification_email` ("Your verification code") for
1028
+ every other realm (WebEngine `verify_email`, `Otp.issue` contact verification).
1029
+ There is no built-in SMS delivery. The copy is in `config/locales/en.yml` under
1030
+ `standard_id.passwordless_mailer.{otp_email,step_up_email,verification_email}.*`
1031
+ (`subject`, `greeting`, `intro`, `expiry`, `ignore`, `footer`; `step_up_email`
1032
+ has `warning` in place of `ignore`); override any key in your own
955
1033
  locale files, or the templates in `app/views/standard_id/passwordless_mailer/`.
956
1034
  An assigned `c.passwordless.mailer_subject` still sets the sign-in subject. The subscriber runs synchronously inside the request, so
957
1035
  `I18n.locale`, `Current.*` and the like are still available.
@@ -1639,8 +1717,9 @@ in front of the endpoint. The `resource` parameter is ignored until
1639
1717
  (RFC 8707 §2).
1640
1718
 
1641
1719
  For a client with no registered default, a client-supplied `audience` is taken as
1642
- is, so `audience_scopes` enforcement for such clients is only as strong as
1643
- `config.oauth.allowed_audiences` at the token endpoint.
1720
+ is, so `audience_scopes` enforcement for such clients is only as strong as the
1721
+ mintable audiences (`config.oauth.mintable_audiences`, else `allowed_audiences`) at
1722
+ the token endpoint.
1644
1723
 
1645
1724
  **Which scope?** `config.oauth.authorize_scope_resolver` normalises the requested
1646
1725
  scope once the client and audience are known and before `audience_scopes` is
@@ -2158,6 +2237,8 @@ end
2158
2237
 
2159
2238
  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.
2160
2239
 
2240
+ 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.
2241
+
2161
2242
  **Required interface:** `provider_name`, `authorization_url`, `get_user_info`.
2162
2243
 
2163
2244
  **Optional hooks** (all class methods, with safe defaults):
@@ -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
@@ -99,17 +99,22 @@ module StandardId
99
99
  end
100
100
 
101
101
  def handle_oauth_error(error)
102
- # A lib-level rate limit (StandardId::RateLimiter) knows its window;
103
- # say so, as the controller-level limits do.
104
- if error.respond_to?(:retry_after) && error.retry_after.to_i.positive?
105
- response.set_header("Retry-After", error.retry_after.to_i.to_s)
106
- end
102
+ set_retry_after_header(error)
107
103
  render json: {
108
104
  error: error.oauth_error_code,
109
105
  error_description: error.message
110
106
  }, status: error.http_status
111
107
  end
112
108
 
109
+ # A lib-level rate limit (StandardId::RateLimiter) knows its window;
110
+ # say so, as the controller-level limits do. Shared with
111
+ # Api::Oauth::BaseController's own OAuth error handler.
112
+ def set_retry_after_header(error)
113
+ return unless error.respond_to?(:retry_after) && error.retry_after.to_i.positive?
114
+
115
+ response.set_header("Retry-After", error.retry_after.to_i.to_s)
116
+ end
117
+
113
118
  def render_bearer_unauthorized!(error_description: default_invalid_token_message, error_code: "invalid_token")
114
119
  response.set_header(
115
120
  "WWW-Authenticate",
@@ -29,6 +29,7 @@ module StandardId
29
29
  status = exception.respond_to?(:http_status) ? exception.http_status : :bad_request
30
30
  description = exception.message.presence || "An error occurred processing the request"
31
31
 
32
+ set_retry_after_header(exception)
32
33
  render json: {
33
34
  error: error_code.to_s,
34
35
  error_description: description
@@ -3,10 +3,13 @@ module StandardId
3
3
  # when `c.passwordless.delivery = :built_in`.
4
4
  #
5
5
  # * #otp_email — the sign-in code (realm "authentication").
6
+ # * #step_up_email — the step-up code (realm `c.step_up.realm`, default
7
+ # "step_up"): an account that is already signed in confirming a sensitive
8
+ # action. It tells the recipient what to do if that wasn't them.
6
9
  # * #verification_email — every other realm: WebEngine verify_email/start
7
10
  # (realm "verification") and `Otp.issue(realm: ...)` for contact
8
- # verification, step-up and the like. It must not tell the recipient the
9
- # code is for signing in.
11
+ # verification and the like. It must not tell the recipient the code is
12
+ # for signing in.
10
13
  #
11
14
  # Copy lives under `standard_id.passwordless_mailer.<action>.*` in
12
15
  # config/locales/en.yml; override any key in the host's locale files, or
@@ -47,6 +50,21 @@ module StandardId
47
50
  )
48
51
  end
49
52
 
53
+ # @param email [String]
54
+ # @param otp_code [String]
55
+ # @param realm [String, nil] the OTP realm, available to overriding templates
56
+ # @param expires_in_minutes [Integer, nil] defaults to passwordless.code_ttl
57
+ def step_up_email
58
+ assign_otp_params
59
+ @realm = params[:realm]
60
+
61
+ mail(
62
+ to: @email,
63
+ from: StandardId.config.passwordless.mailer_from,
64
+ subject: otp_copy(:subject)
65
+ )
66
+ end
67
+
50
68
  # Copy for the current action from
51
69
  # standard_id.passwordless_mailer.<action>.<key>, in I18n.locale. Falls
52
70
  # back to the gem's English copy when the host has no translation for
@@ -0,0 +1,24 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <style>
6
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 0; }
7
+ .container { max-width: 480px; margin: 40px auto; background-color: #ffffff; border-radius: 8px; padding: 40px; }
8
+ .code { font-size: 32px; font-weight: bold; letter-spacing: 8px; text-align: center; padding: 20px; background-color: #f0f0f0; border-radius: 6px; margin: 24px 0; font-family: monospace; }
9
+ .footer { margin-top: 32px; font-size: 13px; color: #888888; text-align: center; }
10
+ </style>
11
+ </head>
12
+ <body>
13
+ <div class="container">
14
+ <p><%= otp_copy(:greeting) %></p>
15
+ <p><%= otp_copy(:intro) %></p>
16
+ <div class="code"><%= @otp_code %></div>
17
+ <p><%= otp_copy(:expiry, count: @expires_in_minutes) %></p>
18
+ <p><%= otp_copy(:warning) %></p>
19
+ <div class="footer">
20
+ <p><%= otp_copy(:footer) %></p>
21
+ </div>
22
+ </div>
23
+ </body>
24
+ </html>
@@ -0,0 +1,12 @@
1
+ <%= otp_copy(:greeting) %>
2
+
3
+ <%= otp_copy(:intro) %>
4
+
5
+ <%= @otp_code %>
6
+
7
+ <%= otp_copy(:expiry, count: @expires_in_minutes) %>
8
+
9
+ <%= otp_copy(:warning) %>
10
+
11
+ --
12
+ <%= otp_copy(:footer) %>
@@ -20,6 +20,15 @@ en:
20
20
  other: "This code will expire in %{count} minutes."
21
21
  ignore: "If you did not request this code, you can safely ignore this email."
22
22
  footer: "This is an automated message. Please do not reply."
23
+ step_up_email:
24
+ subject: "Confirm it's you"
25
+ greeting: "Hi,"
26
+ intro: "You're already signed in, and you've asked to do something sensitive on your account. To confirm it's you, enter this code:"
27
+ expiry:
28
+ one: "This code will expire in %{count} minute."
29
+ other: "This code will expire in %{count} minutes."
30
+ warning: "If you didn't ask for this, don't share the code with anyone. Someone else may be signed in to your account: change your password, if you have one, and check your account for anything you don't recognise."
31
+ footer: "This is an automated message. Please do not reply."
23
32
  account_notice_mailer:
24
33
  existing_account:
25
34
  subject: "Someone tried to sign up with your email"
@@ -361,6 +361,12 @@ StandardId.configure do |c|
361
361
  # validation entirely — set this in production.
362
362
  # Default: []
363
363
  # c.oauth.allowed_audiences = %w[web mobile admin]
364
+ #
365
+ # Split what this app mints from what its API accepts. Each defaults to
366
+ # allowed_audiences when unset (nil). An identity provider minting tokens
367
+ # for other services lists them as mintable but not accepted:
368
+ # c.oauth.mintable_audiences = %w[web harness inference]
369
+ # c.oauth.accepted_audiences = %w[web]
364
370
 
365
371
  # Scope-to-claims mapping — when a scope is granted, every listed claim is
366
372
  # resolved via claim_resolvers below and embedded in the access token.
@@ -634,10 +640,22 @@ StandardId.configure do |c|
634
640
 
635
641
  # Wraps every outbound provider request (token exchange, userinfo, JWKS),
636
642
  # e.g. in a circuit breaker. Receives provider: (:google, :apple, ...) and
637
- # the request as a block; must call the block and return its result.
643
+ # the request as a block; must call the block and return its result. A
644
+ # refusal by the wrapper itself (an open circuit) becomes
645
+ # StandardId::ProviderUnavailableError, so sign-in fails as "temporarily
646
+ # unavailable" (API: 503, with Retry-After when the refusal says how long
647
+ # to wait) without the circuit's message.
638
648
  # Default: nil (the request runs directly)
639
649
  # c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }
640
650
 
651
+ # Errors network_wrapper raises that mean your setup is wrong, not that the
652
+ # provider is down (a circuit that was never registered, say). They reach
653
+ # the caller and your error tracker unchanged instead of becoming
654
+ # ProviderUnavailableError. Classes or class names; a name that resolves to
655
+ # nothing (its gem isn't loaded) is ignored.
656
+ # Default: []
657
+ # c.network_wrapper_passthrough_errors = ["StandardCircuit::UnknownCircuit"]
658
+
641
659
  # Receives errors StandardId handles and carries on from (a subscriber that
642
660
  # raised after its change committed). Receives (error, context).
643
661
  # Default: nil (Rails.error.report(error, handled: true, source: "standard_id"))
@@ -71,8 +71,9 @@ module StandardId
71
71
 
72
72
  # Verifies the bearer JWT and returns a decoded session.
73
73
  #
74
- # When `StandardId.config.oauth.allowed_audiences` is non-empty,
75
- # the token's `aud` claim is enforced against that list at decode
74
+ # When the accepted audiences (`config.oauth.accepted_audiences`,
75
+ # else `config.oauth.allowed_audiences`) are non-empty, the token's
76
+ # `aud` claim is enforced against that list at decode
76
77
  # time. A mismatch raises `StandardId::InvalidAudienceError`, which
77
78
  # is caught and treated as an invalid token (returns nil) so the
78
79
  # downstream 401 path in `Api::BaseController` handles it
@@ -125,8 +126,7 @@ module StandardId
125
126
  end
126
127
 
127
128
  def configured_allowed_audiences
128
- audiences = StandardId.config.oauth.allowed_audiences
129
- audiences.presence
129
+ StandardId::Oauth::Audiences.accepted.presence
130
130
  end
131
131
  end
132
132
  end
@@ -176,13 +176,33 @@ StandardId::ConfigSchema.define do
176
176
  # Receives: provider: (Symbol — :google, :apple, ...; :standard_id when the
177
177
  # caller names none) and a block that performs the request.
178
178
  # Must call the block and return its result. Whatever the block raises
179
- # (timeouts, refused connections) raises inside the wrapper; whatever the
180
- # wrapper raises reaches the caller unchanged.
179
+ # (timeouts, refused connections) raises inside the wrapper and, re-raised,
180
+ # reaches the caller unchanged. A refusal by the wrapper itself (an open
181
+ # circuit) becomes StandardId::ProviderUnavailableError, `cause` set to it,
182
+ # so a sign-in fails as "temporarily unavailable" (API: 503, with
183
+ # Retry-After when the refusal says how long to wait) without the
184
+ # circuit's message. Programming errors in the wrapper, errors listed in
185
+ # network_wrapper_passthrough_errors, and errors it raises after the
186
+ # block returned pass through unchanged (see StandardId::NetworkWrapper).
181
187
  # nil (the default) runs the block directly.
182
188
  #
183
189
  # c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }
184
190
  field :network_wrapper, type: :any, default: nil
185
191
 
192
+ # network_wrapper_passthrough_errors: errors network_wrapper raises that
193
+ # mean the host's own setup is wrong, not that the provider is down, such
194
+ # as a circuit that was never registered. They reach the caller (and the
195
+ # error tracker) unchanged instead of becoming
196
+ # StandardId::ProviderUnavailableError. An error passes through when it
197
+ # `is_a?` any entry.
198
+ # Entries: classes, or class names as Strings. A String is resolved
199
+ # when a wrapper error is handled, so it may name a class from a gem
200
+ # that is not loaded; a name that resolves to nothing is ignored.
201
+ # [] (the default) passes none through.
202
+ #
203
+ # c.network_wrapper_passthrough_errors = ["StandardCircuit::UnknownCircuit"]
204
+ field :network_wrapper_passthrough_errors, type: :array, default: -> { [] }
205
+
186
206
  # error_reporter: receives errors StandardId handles and carries on from —
187
207
  # today, an event subscriber that raised after the change it reports had
188
208
  # already committed (a completed password reset, a password rehash, a
@@ -417,8 +437,9 @@ StandardId::ConfigSchema.define do
417
437
  field :realm, type: :string, default: "step_up"
418
438
  # How the code is delivered (StandardId::Otp delivery modes):
419
439
  # :built_in — (default) follow c.passwordless.delivery: the engine's
420
- # PasswordlessMailer when that is :built_in, else your
421
- # PASSWORDLESS_CODE_GENERATED subscriber (realm "step_up")
440
+ # PasswordlessMailer#step_up_email when that is :built_in,
441
+ # else your PASSWORDLESS_CODE_GENERATED subscriber (realm
442
+ # "step_up")
422
443
  # :custom — always your subscriber, so the message can say why
423
444
  field :delivery, type: :symbol, default: :built_in
424
445
  # Also ask for the password when the account has one. Off only for hosts
@@ -619,8 +640,26 @@ StandardId::ConfigSchema.define do
619
640
  # Empty (default) = no global audience validation; behavior matches
620
641
  # pre-threading releases. Production deployments should set this
621
642
  # explicitly (e.g., `%w[web api]`).
643
+ #
644
+ # It is the default for both of the two lists below: set either to split
645
+ # what this app mints from what it accepts (StandardId::Oauth::Audiences).
622
646
  field :allowed_audiences, type: :array, default: -> { [] }
623
647
 
648
+ # Audiences this app may issue tokens for: every /oauth/token grant
649
+ # (authorization-code exchange, client_credentials, password, refresh, …),
650
+ # StandardId::TokenMinter and the API step-up re-mint refuse any other.
651
+ # nil (default) = `allowed_audiences`. An identity provider that mints
652
+ # per-service tokens lists those services here without accepting them on
653
+ # its own API (see `accepted_audiences`).
654
+ field :mintable_audiences, type: :array, default: nil
655
+
656
+ # Audiences the API token manager accepts in a bearer's `aud` at decode
657
+ # time; any other is an invalid token (401). nil (default) =
658
+ # `allowed_audiences`. Empty = no decode-time audience check (warned about
659
+ # at boot in production). The Web (cookie) token manager reads no JWT, so
660
+ # neither list applies to it.
661
+ field :accepted_audiences, type: :array, default: nil
662
+
624
663
  # Audience → profile type binding (first-class audience modeling).
625
664
  #
626
665
  # Maps each configured audience string to the profile type (or types)
@@ -157,18 +157,20 @@ module StandardId
157
157
  end
158
158
  private_class_method :host_secret_key_base
159
159
 
160
- # Logs a production-only warning when no global audience allow-list is
161
- # configured. With `allowed_audiences` empty, the API token manager
162
- # skips decode-time aud enforcement, leaving cross-audience JWT replay
163
- # mitigation dependent on per-controller `AudienceVerification`
164
- # inclusion. Extracted to a module method so specs can exercise it
165
- # directly without booting a second Rails app.
160
+ # Logs a production-only warning when the effective accepted audiences
161
+ # (`accepted_audiences`, else `allowed_audiences`) are empty. Then the API
162
+ # token manager skips decode-time aud enforcement, leaving cross-audience
163
+ # JWT replay mitigation dependent on per-controller
164
+ # `AudienceVerification` inclusion. Setting only `mintable_audiences`
165
+ # does not silence it. Extracted to a module method so specs can exercise
166
+ # it directly without booting a second Rails app.
166
167
  def self.warn_if_allowed_audiences_empty_in_production!
167
168
  return unless StandardId::AppEnvironment.production?
168
- return if StandardId.config.oauth.allowed_audiences.present?
169
+ return if StandardId::Oauth::Audiences.accepted.present?
169
170
 
171
+ setting = StandardId.config.oauth.accepted_audiences.nil? ? "allowed_audiences" : "accepted_audiences"
170
172
  Rails.logger.warn(
171
- "StandardId: config.oauth.allowed_audiences is empty in production — " \
173
+ "StandardId: config.oauth.#{setting} is empty in production — " \
172
174
  "JWT audience is not enforced globally. Set this to your expected " \
173
175
  "audiences (e.g., ['web', 'api']) to close cross-audience replay vectors."
174
176
  )
@@ -204,6 +204,54 @@ module StandardId
204
204
  def oauth_error_code = :invalid_client_metadata
205
205
  end
206
206
 
207
+ # The host's `config.network_wrapper` refused a provider request itself (an
208
+ # open circuit breaker, say), as opposed to the request failing in transit:
209
+ # StandardId::NetworkWrapper raises it in place of the wrapper's own error,
210
+ # which stays reachable as `cause` (see NetworkWrapper for the rules). An
211
+ # error the request raises and the wrapper re-raises unchanged (a timeout,
212
+ # a refused connection) is never turned into it; it reaches the provider as
213
+ # it always has. Nor are programming errors in the wrapper, or an error the
214
+ # wrapper raises after the request went through.
215
+ #
216
+ # An OAuthError, so a sign-in that hits it takes the ordinary failure path:
217
+ # the web callback redirects to the login page with the message, and the
218
+ # API renders `temporarily_unavailable` with HTTP 503 (RFC 6749 §4.1.2.1).
219
+ # The message names only the provider, never the wrapper's error, which may
220
+ # carry circuit names or host internals. Plugins map it to their own
221
+ # unavailable error where they have one.
222
+ class ProviderUnavailableError < OAuthError
223
+ # Providers no user would recognise, so the message names none:
224
+ # HttpClient::DEFAULT_PROVIDER, which HttpClient passes when its caller
225
+ # names no provider. Kept here rather than read from HttpClient so the
226
+ # error has no load-order or stubbing dependency on it.
227
+ UNNAMED_PROVIDERS = [:standard_id].freeze
228
+
229
+ # @return [Symbol, nil] the provider the request was for (`:google`, ...)
230
+ attr_reader :provider
231
+
232
+ # @return [Integer, nil] seconds the wrapper's error says to wait before
233
+ # retrying (StandardId::NetworkWrapper reads it from the error), sent
234
+ # by the API as a Retry-After header; nil when it doesn't say
235
+ attr_reader :retry_after
236
+
237
+ def initialize(message = nil, provider: nil, retry_after: nil)
238
+ @provider = provider
239
+ @retry_after = retry_after
240
+ super(message || "#{provider_label(provider)} is temporarily unavailable")
241
+ end
242
+
243
+ def oauth_error_code = :temporarily_unavailable
244
+ def http_status = :service_unavailable
245
+
246
+ private
247
+
248
+ def provider_label(provider)
249
+ return "The provider" if provider.nil? || UNNAMED_PROVIDERS.include?(provider.to_sym)
250
+
251
+ provider.to_s.humanize
252
+ end
253
+ end
254
+
207
255
  # Lifecycle hook errors
208
256
  class AuthenticationDenied < StandardError; end
209
257
 
@@ -4,9 +4,10 @@ module StandardId
4
4
  # Built-in OTP email delivery (`c.passwordless.delivery = :built_in`).
5
5
  #
6
6
  # Sign-in codes (realm "authentication") get PasswordlessMailer#otp_email;
7
- # every other realm — WebEngine email verification, Otp.issue step-up /
8
- # contact verification — gets #verification_email, so a verification code
9
- # never arrives as "your sign-in code". There is no built-in SMS delivery.
7
+ # step-up codes (realm `c.step_up.realm`) get #step_up_email; every other
8
+ # realm — WebEngine email verification, Otp.issue contact verification —
9
+ # gets #verification_email, so neither arrives as "your sign-in code".
10
+ # There is no built-in SMS delivery.
10
11
  #
11
12
  # On a successful enqueue it marks the code challenge
12
13
  # (CodeChallenge#built_in_delivered), which is how the strategy knows to
@@ -65,7 +66,11 @@ module StandardId
65
66
  private
66
67
 
67
68
  def mailer_action(realm)
68
- realm.blank? || realm.to_s == StandardId::Passwordless::DEFAULT_REALM ? :otp_email : :verification_email
69
+ case realm.to_s
70
+ when "", StandardId::Passwordless::DEFAULT_REALM then :otp_email
71
+ when StandardId::StepUp.realm then :step_up_email
72
+ else :verification_email
73
+ end
69
74
  end
70
75
 
71
76
  def expires_in_minutes(expires_at)
@@ -76,20 +76,13 @@ module StandardId
76
76
  # Private, but provider plugins call it through `send` to fetch a JWKS
77
77
  # with a plain GET, so its signature is part of the plugin contract:
78
78
  # `provider:` is optional and new keywords must stay optional.
79
+ #
80
+ # The host's `network_wrapper` sees the whole connection (connect,
81
+ # request, response), so a timeout or refused connection raises inside
82
+ # it and reaches the caller as is; an error the wrapper raises itself
83
+ # becomes StandardId::ProviderUnavailableError (see NetworkWrapper).
79
84
  def start_connection(uri, resolved_ip: nil, provider: DEFAULT_PROVIDER, &block)
80
- with_network_wrapper(provider) { open_connection(uri, resolved_ip:, &block) }
81
- end
82
-
83
- # Runs the block through `StandardId.config.network_wrapper`, or
84
- # directly when none is configured. The wrapper sees the whole
85
- # connection (connect, request, response), so a timeout or refused
86
- # connection raises inside it; whatever it raises or returns is the
87
- # caller's.
88
- def with_network_wrapper(provider, &block)
89
- wrapper = StandardId.config.network_wrapper
90
- return yield unless wrapper.respond_to?(:call)
91
-
92
- wrapper.call(**StandardId::Utils::CallableParameterFilter.filter(wrapper, { provider: provider&.to_sym }), &block)
85
+ NetworkWrapper.run(provider:) { open_connection(uri, resolved_ip:, &block) }
93
86
  end
94
87
 
95
88
  def open_connection(uri, resolved_ip: nil, &block)
@@ -0,0 +1,118 @@
1
+ module StandardId
2
+ # Runs an outbound provider request through the host's
3
+ # `StandardId.config.network_wrapper`, or directly when none is configured.
4
+ # StandardId::HttpClient sends every request through here; a plugin with its
5
+ # own HTTP code (one that may not use HttpClient's address guard) calls it
6
+ # the same way, so the wrapper and its error contract cover it too:
7
+ #
8
+ # StandardId::NetworkWrapper.run(provider: :example) { http.start { |h| h.request(req) } }
9
+ #
10
+ # With no wrapper, the block runs directly and nothing is rescued. With one,
11
+ # an error that leaves the wrapper is handled by the first rule that matches:
12
+ #
13
+ # 1. A StandardId::OAuthError (a ProviderUnavailableError from a nested
14
+ # call, or a refusal of the host's own) reaches the caller as is.
15
+ # 2. An error the block raised (the request: a timeout, a refused
16
+ # connection), re-raised by the wrapper as the same object, reaches the
17
+ # caller as is, exactly as with no wrapper.
18
+ # 3. If the most recent call of the block returned normally, the request
19
+ # went through (an authorization code may be spent), so the wrapper's
20
+ # error (a failing tracer, say) reaches the caller as is: telling the
21
+ # user to retry would be wrong. With a retrying wrapper, only the last
22
+ # call counts.
23
+ # 4. A programming error in the wrapper (PROGRAMMING_ERRORS: a typo, an
24
+ # unloaded constant, a wrong call) reaches the caller as is, so it is
25
+ # reported as the bug it is, not shown as an outage.
26
+ # 5. An error the host listed in `config.network_wrapper_passthrough_errors`
27
+ # (a misconfiguration of its own, such as a circuit that was never
28
+ # registered) reaches the caller as is, for the same reason.
29
+ # 6. Anything else (an open circuit that never ran the block, a breaker
30
+ # that turns the request's failure into its own error) becomes
31
+ # StandardId::ProviderUnavailableError, with the wrapper's error as
32
+ # `cause`. Callers therefore need no knowledge of the host's
33
+ # circuit-breaker library to map an outage. When the wrapper's error
34
+ # says how long to wait (see .retry_after_from), the
35
+ # ProviderUnavailableError carries it as `retry_after`, which the API
36
+ # sends as a Retry-After header.
37
+ #
38
+ # Non-StandardError exceptions (Interrupt, ...) are never touched.
39
+ module NetworkWrapper
40
+ # Errors a host wrapper raises because its own code is wrong, never
41
+ # because the provider is down. NameError covers NoMethodError.
42
+ PROGRAMMING_ERRORS = [NameError, TypeError, ArgumentError].freeze
43
+
44
+ module_function
45
+
46
+ # @param provider [Symbol, String, nil] the remote service (`:google`,
47
+ # `:apple`, ...), handed to the wrapper as `provider:`
48
+ # @return whatever the block (through the wrapper) returns
49
+ # @raise [StandardId::ProviderUnavailableError] the wrapper refused the
50
+ # request (rule 6 above)
51
+ def run(provider:, &block)
52
+ wrapper = StandardId.config.network_wrapper
53
+ return yield unless wrapper.respond_to?(:call)
54
+
55
+ provider = provider&.to_sym
56
+ arguments = StandardId::Utils::CallableParameterFilter.filter(wrapper, { provider: provider })
57
+ # Every error the block raised (rule 2), and whether its latest call
58
+ # returned normally (rule 3).
59
+ raised = []
60
+ returned = false
61
+ request = proc do |*args|
62
+ returned = false
63
+ result = block.call(*args)
64
+ returned = true
65
+ result
66
+ rescue StandardError => e
67
+ raised << e
68
+ raise
69
+ end
70
+
71
+ begin
72
+ wrapper.call(**arguments, &request)
73
+ rescue StandardId::OAuthError
74
+ raise
75
+ rescue StandardError => e
76
+ raise if raised.any? { |error| error.equal?(e) }
77
+ raise if returned
78
+ raise if PROGRAMMING_ERRORS.any? { |klass| e.is_a?(klass) }
79
+ raise if passthrough_errors.any? { |klass| e.is_a?(klass) }
80
+
81
+ raise StandardId::ProviderUnavailableError.new(provider: provider, retry_after: retry_after_from(e)), cause: e
82
+ end
83
+ end
84
+
85
+ # The classes in `config.network_wrapper_passthrough_errors`. A String
86
+ # names a class that may not be loaded (it may come from a gem the host
87
+ # has not required), so it is resolved on each call and skipped while it
88
+ # names nothing.
89
+ #
90
+ # @return [Array<Module>]
91
+ def passthrough_errors
92
+ Array(StandardId.config.network_wrapper_passthrough_errors).filter_map do |entry|
93
+ klass = entry.is_a?(Module) ? entry : entry.to_s.safe_constantize
94
+ klass if klass.is_a?(Module)
95
+ end
96
+ end
97
+
98
+ # How long, in whole seconds, the wrapper's error says to wait before
99
+ # retrying, or nil when it doesn't say. Duck-typed, so no breaker library
100
+ # is assumed: a `retry_after` that is a Time (when to retry) or a Numeric
101
+ # (seconds) decides; without one, `cool_off_time` in seconds. Stoplight's
102
+ # RedLight has both, with `retry_after` nil while a light is locked red.
103
+ #
104
+ # @param error [Exception] the wrapper's error
105
+ # @return [Integer, nil] a positive number of seconds, or nil
106
+ def retry_after_from(error)
107
+ value = error.retry_after if error.respond_to?(:retry_after)
108
+ value -= Time.now if value.is_a?(Time)
109
+ value = error.cool_off_time if !value.is_a?(Numeric) && error.respond_to?(:cool_off_time)
110
+
111
+ value.ceil if value.is_a?(Numeric) && value.positive?
112
+ rescue StandardError
113
+ # Only a hint for a header: a host error whose accessor misbehaves must
114
+ # not replace the ProviderUnavailableError being raised.
115
+ nil
116
+ end
117
+ end
118
+ end
@@ -0,0 +1,42 @@
1
+ module StandardId
2
+ module Oauth
3
+ # The two audience lists an app works with, resolved from config:
4
+ #
5
+ # * mintable — audiences this app may issue tokens for (every
6
+ # TokenGrantFlow, so /oauth/token for each grant including the
7
+ # authorization-code exchange and client_credentials, plus
8
+ # TokenMinter / DirectMintFlow and the API step-up re-mint).
9
+ # * accepted — audiences the API token manager accepts on a bearer at
10
+ # decode time.
11
+ #
12
+ # Each is `oauth.mintable_audiences` / `oauth.accepted_audiences` when the
13
+ # host set it (nil means unset), else `oauth.allowed_audiences`, so a host
14
+ # that sets neither sees one list doing both jobs, as it always did. An
15
+ # identity provider that mints tokens for other services (aud=harness,
16
+ # aud=inference) lists them in mintable_audiences and keeps
17
+ # accepted_audiences to its own API's audiences, so those service tokens
18
+ # are not also accepted on it.
19
+ #
20
+ # An empty effective list means no restriction on that side, as an empty
21
+ # allowed_audiences always has.
22
+ module Audiences
23
+ module_function
24
+
25
+ # @return [Array<String>]
26
+ def mintable
27
+ resolve(StandardId.config.oauth.mintable_audiences)
28
+ end
29
+
30
+ # @return [Array<String>]
31
+ def accepted
32
+ resolve(StandardId.config.oauth.accepted_audiences)
33
+ end
34
+
35
+ def resolve(override)
36
+ list = override.nil? ? StandardId.config.oauth.allowed_audiences : override
37
+ Array(list).map(&:to_s)
38
+ end
39
+ private_class_method :resolve
40
+ end
41
+ end
42
+ end
@@ -5,7 +5,7 @@ module StandardId
5
5
  # :audience is optional (RFC 6749 / RFC 8707 §2 treats `resource`/`audience`
6
6
  # as OPTIONAL at /authorize). Token-time validation in
7
7
  # TokenGrantFlow#validate_audience! already no-ops when audience is blank or
8
- # when no allowed_audiences are configured, so omitting it is safe and lets
8
+ # when no mintable audiences are configured, so omitting it is safe and lets
9
9
  # standards-compliant clients (e.g. MCP) authorize without it.
10
10
  permit_params :audience, :resource, :scope, :redirect_uri, :state, :connection, :prompt, :organization, :invitation, :code_challenge, :code_challenge_method, :nonce
11
11
 
@@ -350,8 +350,10 @@ module StandardId
350
350
  params[:audience]
351
351
  end
352
352
 
353
+ # Against the audiences this app may mint (oauth.mintable_audiences,
354
+ # else oauth.allowed_audiences), not the ones its API accepts.
353
355
  def validate_audience!
354
- allowed = StandardId.config.oauth.allowed_audiences
356
+ allowed = StandardId::Oauth::Audiences.mintable
355
357
  return if allowed.blank? # No restriction configured
356
358
  return if audience.blank? # Audience not provided (optional)
357
359
 
@@ -17,8 +17,9 @@ module StandardId
17
17
  # result.access_token # the JWT
18
18
  # result.jti # what OAUTH_TOKEN_ISSUED carried
19
19
  #
20
- # What runs, in order: audience validation (oauth.allowed_audiences),
21
- # audience → profile binding (oauth.audience_profile_types, fail-closed),
20
+ # What runs, in order: audience validation (oauth.mintable_audiences, else
21
+ # oauth.allowed_audiences), audience → profile binding
22
+ # (oauth.audience_profile_types, fail-closed),
22
23
  # OAUTH_TOKEN_ISSUING (AccountStatus / AccountLocking refuse here),
23
24
  # scope_claims + claim_resolvers and custom_claims, then the host's own
24
25
  # +claims+, then OAUTH_TOKEN_ISSUED. A refresh token is persisted only when
@@ -1,3 +1,3 @@
1
1
  module StandardId
2
- VERSION = "0.62.0"
2
+ VERSION = "0.64.0"
3
3
  end
data/lib/standard_id.rb CHANGED
@@ -29,6 +29,7 @@ require "standard_id/events/subscribers/password_reset_delivery_subscriber"
29
29
  require "standard_id/events/subscribers/password_changed_notice_subscriber"
30
30
  require "standard_id/account_status"
31
31
  require "standard_id/account_locking"
32
+ require "standard_id/network_wrapper"
32
33
  require "standard_id/http_client"
33
34
  require "standard_id/bearer_token_extraction"
34
35
  require "standard_id/jwt_service"
@@ -47,6 +48,7 @@ require "standard_id/account_cleanup"
47
48
  require "standard_id/oauth/audience_profile_resolver"
48
49
  require "standard_id/oauth/audience_scope_resolver"
49
50
  require "standard_id/oauth/audience_resolver"
51
+ require "standard_id/oauth/audiences"
50
52
  require "standard_id/oauth/authorize_scope_resolver"
51
53
  require "standard_id/oauth/base_request_flow"
52
54
  require "standard_id/oauth/token_lifetime_resolver"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: standard_id
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.62.0
4
+ version: 0.64.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rarebit One
@@ -233,6 +233,8 @@ files:
233
233
  - app/views/standard_id/password_reset_mailer/reset_email.text.erb
234
234
  - app/views/standard_id/passwordless_mailer/otp_email.html.erb
235
235
  - app/views/standard_id/passwordless_mailer/otp_email.text.erb
236
+ - app/views/standard_id/passwordless_mailer/step_up_email.html.erb
237
+ - app/views/standard_id/passwordless_mailer/step_up_email.text.erb
236
238
  - app/views/standard_id/passwordless_mailer/verification_email.html.erb
237
239
  - app/views/standard_id/passwordless_mailer/verification_email.text.erb
238
240
  - app/views/standard_id/web/account/edit.html.erb
@@ -332,9 +334,11 @@ files:
332
334
  - lib/standard_id/login_method_policy.rb
333
335
  - lib/standard_id/migration_check.rb
334
336
  - lib/standard_id/migration_helpers.rb
337
+ - lib/standard_id/network_wrapper.rb
335
338
  - lib/standard_id/oauth/audience_profile_resolver.rb
336
339
  - lib/standard_id/oauth/audience_resolver.rb
337
340
  - lib/standard_id/oauth/audience_scope_resolver.rb
341
+ - lib/standard_id/oauth/audiences.rb
338
342
  - lib/standard_id/oauth/authorization_code_authorization_flow.rb
339
343
  - lib/standard_id/oauth/authorization_code_flow.rb
340
344
  - lib/standard_id/oauth/authorization_flow.rb