standard_id 0.64.1 → 0.66.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 (39) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -0
  3. data/README.md +46 -15
  4. data/app/controllers/concerns/standard_id/social_authentication.rb +13 -0
  5. data/app/controllers/concerns/standard_id/web_authentication.rb +9 -0
  6. data/app/controllers/standard_id/api/authorization_controller.rb +22 -0
  7. data/app/controllers/standard_id/api/base_controller.rb +40 -0
  8. data/app/controllers/standard_id/api/oauth/callback/providers_controller.rb +1 -0
  9. data/app/controllers/standard_id/api/sessions_controller.rb +1 -0
  10. data/app/controllers/standard_id/api/step_up_controller.rb +3 -1
  11. data/app/controllers/standard_id/api/userinfo_controller.rb +2 -1
  12. data/app/controllers/standard_id/web/auth/callback/providers_controller.rb +2 -0
  13. data/app/controllers/standard_id/web/consent_controller.rb +10 -1
  14. data/app/controllers/standard_id/web/login_controller.rb +8 -0
  15. data/app/controllers/standard_id/web/verify_email/confirm_controller.rb +4 -1
  16. data/app/controllers/standard_id/web/verify_email/start_controller.rb +2 -0
  17. data/app/controllers/standard_id/web/verify_phone/confirm_controller.rb +4 -1
  18. data/app/controllers/standard_id/web/verify_phone/start_controller.rb +2 -0
  19. data/app/models/standard_id/client_application.rb +27 -2
  20. data/app/models/standard_id/client_secret_credential.rb +18 -0
  21. data/app/models/standard_id/identifier.rb +28 -0
  22. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +10 -0
  23. data/lib/standard_id/account_status.rb +6 -0
  24. data/lib/standard_id/config/schema.rb +19 -0
  25. data/lib/standard_id/email_password/authentication.rb +15 -2
  26. data/lib/standard_id/email_password/verification.rb +7 -3
  27. data/lib/standard_id/engine.rb +24 -0
  28. data/lib/standard_id/events/definitions.rb +17 -3
  29. data/lib/standard_id/events/subscribers/logging_subscriber.rb +0 -1
  30. data/lib/standard_id/events.rb +17 -5
  31. data/lib/standard_id/oauth/audiences.rb +39 -0
  32. data/lib/standard_id/oauth/authorization_code_authorization_flow.rb +6 -0
  33. data/lib/standard_id/oauth/authorization_flow.rb +21 -1
  34. data/lib/standard_id/oauth/oauth_session_persistence.rb +24 -3
  35. data/lib/standard_id/oauth/password_flow.rb +12 -0
  36. data/lib/standard_id/oauth/refresh_token_flow.rb +19 -0
  37. data/lib/standard_id/oauth/subflows/social_login_grant.rb +11 -2
  38. data/lib/standard_id/version.rb +1 -1
  39. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: bc6e2b7114dad7aa0475bd6fcd96f6a4c29c34eb91a2667cfaab83ee4f17089d
4
- data.tar.gz: 7bf5da56fcc0572da349de796a74442585f529a3522bdcdaf9c1421e63cc6fc4
3
+ metadata.gz: ce9554a4ecea8b55429ff64af874edbb1fd9220d0cfaf866834b4c2acda20482
4
+ data.tar.gz: cfe2fe8aee4b26f46111a27afec5b6c892cfed6602b306ff74c1ab2c1424adc7
5
5
  SHA512:
6
- metadata.gz: df80d0509429e338f1c6be7057ddf5606ef5b70555a90e1e6b8344cf05b341d2836a729590f2bd596fd2faf81b97d5e0d22eb1cab9ec5a60f2b02373f0c8fc40
7
- data.tar.gz: dc8312147249dd52500a68f113523fae4926171a7458fb27ff24b33ef21686dd646668b0cdea0cc8181d2d1dc04c20810b8bb483dee93cd8744959d4a1886104
6
+ metadata.gz: 6e70a3bf0dc94040dbe10b1cbe90480de7b90e549f5b86311fe29e9b81798193a03745c1d2789bcd923eef74a549ba483f0ecca676aebc8f070644f60008d5b6
7
+ data.tar.gz: 886cfc5f1f805f1716142eb945b0f0fcbb13c34859f9ce882076ea31c014bfeb65bcdcfb636103192f89572cf95d7ea7ec7c82bf6ab289da5b01c1d0b00dd2e4
data/CHANGELOG.md CHANGED
@@ -7,6 +7,86 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.66.0] - 2026-11-25
11
+
12
+ ### Added
13
+
14
+ - **Per-endpoint accepted audiences** (`config.oauth.endpoint_audiences`). The gem's own bearer
15
+ endpoints, `userinfo` (`GET /userinfo`), `sessions` (`GET /sessions`, `DELETE /sessions/:id`)
16
+ and `step_up` (`POST /step_up`, `POST /step_up/verify`), can each be limited to a subset of
17
+ the accepted audiences, e.g. `{ userinfo: %w[companion_kit admin_kit], ... }`, so a
18
+ per-service or MCP token the API accepts elsewhere cannot read the account, list or revoke its
19
+ sessions, or step up. A token with none of the endpoint's audiences gets the
20
+ `StandardId::AudienceVerification` response, `403 insufficient_scope`, and the refusal publishes
21
+ `oauth.audience.mismatch` (already auditable) with `token_audiences`, `required_audiences` and
22
+ `endpoint`. An array `aud` passes when any entry matches, and the matched audience's
23
+ `audience_profile_types` binding applies.
24
+ Opt-in: an endpoint left out (or given `[]`) accepts any accepted audience, as before. An
25
+ unknown key raises `StandardId::ConfigurationError` at boot. In production with more than one
26
+ accepted audience, boot logs a warning naming the endpoints left open.
27
+ `StandardId::Oauth::Audiences.endpoint(name)` returns an endpoint's list.
28
+
29
+ ### Changed
30
+
31
+ - `GET /userinfo` verifies the access token in a `before_action` rather than inside the action.
32
+ Responses are unchanged.
33
+
34
+ ## [0.65.0] - 2026-11-25
35
+
36
+ ### Added
37
+
38
+ - **Declared events are now published.** These names were in the event catalogue (several in
39
+ `SECURITY_EVENTS`) but nothing published them (rarebit-one/rarebit-sre#596). Payloads carry ids,
40
+ provider names and reasons, never a password, code, token or secret. The README event table
41
+ lists each payload.
42
+ - `authentication.password.failed`: a password checked against an existing password credential
43
+ did not match, at the web login, the OAuth password grant and the `c.email_password` login,
44
+ before `authentication.attempt.failed`. Not for a login that names no credential.
45
+ - `account.status_changed`: any committed change to `AccountStatus`'s status, after
46
+ `account.activated` / `account.deactivated`.
47
+ - `session.refreshed`: an OAuth token grant reused the device's active `DeviceSession`
48
+ (`session.session_type_resolver` returning `:device`) and moved its expiry forward. Published
49
+ after the grant commits; a raising subscriber is reported, not raised.
50
+ - `oauth.token.refreshed`: a `refresh_token` grant rotated its token. Published inside the
51
+ rotation transaction after `oauth.token.issued`, so a raising subscriber rolls it back as
52
+ one on `oauth.token.issued` does.
53
+ - `oauth.authorization.requested` (`/authorize` received a request for an active client),
54
+ `oauth.authorization.granted` (a code or implicit token was issued; for a consent-gated
55
+ client, after approval; not for a social `connection`) and `oauth.authorization.denied` (Deny
56
+ on the consent screen).
57
+ - `social.auth.started` (the browser is sent to the provider, from `POST /login` with a
58
+ `connection` or `/authorize?connection=`) and `social.auth.callback_received` (the provider's answer reached
59
+ the web or API callback, with the provider's `error` when it sent one).
60
+ - `identifier.verification.started` / `identifier.verification.failed`: a code to prove an
61
+ address was issued, or a wrong code was sent for a live one, in `/verify_email`,
62
+ `/verify_phone` and the `c.email_password` sign-up code.
63
+ - `credential.client_secret.created` (any committed client secret: `create_client_secret!`,
64
+ rotation, dynamic registration) and `credential.client_secret.rotated`
65
+ (`rotate_client_secret!`, after its `created`). Ids only: the record is left out because
66
+ it still holds the plaintext secret just after create.
67
+ - **`Events.auditable` gains `oauth.authorization.granted` and `oauth.authorization.denied`.**
68
+
69
+ ### Changed
70
+
71
+ - **More audit rows for apps that subscribe through `Events.auditable`.** Its Regexps already
72
+ matched four of the newly published events, so they are audited from this release:
73
+ `authentication.password.failed` (one more row per wrong password for an existing account, next
74
+ to `authentication.attempt.failed`), `account.status_changed` (one more row per activation or
75
+ deactivation), and `social.auth.started` / `social.auth.callback_received` (two more rows per
76
+ social sign-in; `started` also for abandoned ones, and starting one needs no authentication:
77
+ `POST /login` with a `connection` is rate-limited per IP, `/authorize?connection=` is not). Add to that one row per
78
+ authorization grant or consent denial. `session.refreshed`, `oauth.token.refreshed` (one per
79
+ refresh), `oauth.authorization.requested` and `identifier.verification.*` are published but
80
+ not auditable.
81
+
82
+ ### Removed
83
+
84
+ - **`identifier.linked` (`StandardId::Events::IDENTIFIER_LINKED`).** Core never attaches an
85
+ existing identifier to an account: an identifier is created with its account
86
+ (`identifier.created`), and a social sign-in that links one publishes `social.account.linked`.
87
+ The constant was never published, so a subscriber to it received nothing; referencing the
88
+ constant now raises `NameError`.
89
+
10
90
  ## [0.64.1] - 2026-11-25
11
91
 
12
92
  ### Fixed
data/README.md CHANGED
@@ -464,6 +464,38 @@ so neither list applies to browser sessions. `JwtService.decode` and
464
464
  `StandardId::Oauth::Audiences.mintable` / `.accepted` return the effective
465
465
  lists.
466
466
 
467
+ #### Per-endpoint audiences
468
+
469
+ The accepted list is the whole API's. The gem's own bearer endpoints, which
470
+ return or change the account's data, can be narrowed further with
471
+ `config.oauth.endpoint_audiences`, so a per-service or MCP token your API must
472
+ accept elsewhere cannot read the account or end its sessions:
473
+
474
+ ```ruby
475
+ StandardId.configure do |config|
476
+ config.oauth.accepted_audiences = %w[companion_kit admin_kit mcp]
477
+
478
+ config.oauth.endpoint_audiences = {
479
+ userinfo: %w[companion_kit admin_kit], # GET /userinfo
480
+ sessions: %w[companion_kit admin_kit], # GET /sessions, DELETE /sessions/:id
481
+ step_up: %w[companion_kit admin_kit] # POST /step_up, POST /step_up/verify
482
+ }
483
+ end
484
+ ```
485
+
486
+ A token whose `aud` holds none of the endpoint's audiences gets
487
+ `403 insufficient_scope`, the response `StandardId::AudienceVerification`
488
+ gives everywhere, and publishes `oauth.audience.mismatch` (auditable) with
489
+ `token_audiences`, `required_audiences` and `endpoint`; an array `aud` passes
490
+ when any entry matches. A token outside
491
+ the accepted list is still a `401 invalid_token` at decode time. The matched
492
+ audience's `audience_profile_types` binding is enforced as well, as on any
493
+ `AudienceVerification` controller. An endpoint left out (or given `[]`) accepts
494
+ any accepted audience, as before, so nothing changes until you set it; an
495
+ unknown key raises `StandardId::ConfigurationError` at boot. In production, with
496
+ more than one accepted audience, boot logs a warning naming the endpoints left
497
+ open (`step_up` only while step-up is enabled).
498
+
467
499
  ### Custom Token Claims
468
500
 
469
501
  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`.
@@ -1202,7 +1234,7 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1202
1234
  | Authentication | `authentication.attempt.started` | `account_lookup`, `auth_method` | Before credential validation begins |
1203
1235
  | | `authentication.attempt.succeeded` | `account`, `auth_method`, `session_type` | After authentication succeeds |
1204
1236
  | | `authentication.attempt.failed` | `account_lookup`, `auth_method`, `error_code`, `error_message` | After authentication fails |
1205
- | | `authentication.password.failed` | `account_lookup`, `error_code`, `error_message` | After password verification fails |
1237
+ | | `authentication.password.failed` | `account_lookup`, `account`, `credential_id`, `error_code` (`invalid_password`) | A password was checked against an existing password credential and did not match (web login, OAuth password grant, `c.email_password` login), before `authentication.attempt.failed`. Not published for a login that names no credential (0.65+) |
1206
1238
  | | `authentication.otp.failed` | `identifier`, `channel`, `error_code`, `error_message` | After OTP verification fails |
1207
1239
  | | `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+) |
1208
1240
  | | `authentication.step_up.started` | `account`, `channel` | A step-up code was issued to a signed-in account (`c.step_up`) |
@@ -1214,24 +1246,23 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1214
1246
  | | `session.validated` | `session`, `account` | After a session passes validation |
1215
1247
  | | `session.expired` | `session`, `account`, `expired_at` | When validation fails because the session expired |
1216
1248
  | | `session.revoked` | `session`, `account`, `reason` | After a session is explicitly revoked |
1217
- | | `session.refreshed` | `session`, `account`, `old_expires_at`, `new_expires_at` | After a refresh operation extends a session |
1249
+ | | `session.refreshed` | `session`, `account`, `previous_expires_at`, `expires_at`, `grant_type` | An OAuth token grant reused the device's active `DeviceSession` (`session.session_type_resolver` → `:device`) and moved its expiry forward. After the grant commits; a raising subscriber is reported, not raised. Fires on every such grant, refreshes included, so it is not in `Events.auditable` (0.65+) |
1218
1250
  | Account | `account.creating` | `account_params`, `auth_method` | Before an account record is created |
1219
1251
  | | `account.created` | `account`, `auth_method`, `source` (signup/passwordless/social) | After an account record is created |
1220
1252
  | | `account.verified` | `account`, `verified_via` (email/phone) | When an account is marked verified |
1221
- | | `account.status_changed` | `account`, `old_status`, `new_status`, `changed_by` | When account status transitions (Issue #16) |
1253
+ | | `account.status_changed` | `account`, `previous_status`, `status` | Any committed change to `AccountStatus`'s status, after `account.activated` / `account.deactivated` (0.65+) |
1222
1254
  | | `account.locked` | `account`, `lock_reason`, `locked_by` | When an account is administratively locked (Issue #17) |
1223
1255
  | | `account.unlocked` | `account`, `unlocked_by` | When an account lock is lifted (Issue #17) |
1224
1256
  | Identifier | `identifier.created` | `identifier`, `account` | After an identifier record is created |
1225
- | | `identifier.verification.started` | `identifier`, `channel` (email/sms), `code_sent` | After a verification code is issued |
1257
+ | | `identifier.verification.started` | `identifier` (the address), `channel` (email/sms), `realm` | A code to prove an address was issued: `/verify_email`, `/verify_phone` and the `c.email_password` sign-up code (0.65+) |
1226
1258
  | | `identifier.verification.succeeded` | `identifier`, `account`, `verified_at` | After identifier verification succeeds |
1227
- | | `identifier.verification.failed` | `identifier`, `error_code`, `attempts` | After identifier verification fails |
1228
- | | `identifier.linked` | `identifier`, `account`, `source` (social/manual) | When an identifier is associated to an account |
1229
- | OAuth | `oauth.authorization.requested` | `client_id`, `account`, `scope`, `redirect_uri` | Before issuing an authorization code |
1230
- | | `oauth.authorization.granted` | `authorization_code`, `client_id`, `account`, `scope` | After an authorization code is created |
1231
- | | `oauth.authorization.denied` | `client_id`, `account`, `reason` | When a user denies authorization |
1259
+ | | `identifier.verification.failed` | `identifier` (the address), `channel`, `realm`, `error_code`, `attempts` | A wrong code was sent for a live verification code. Not published for an address that was never sent one (0.65+) |
1260
+ | OAuth | `oauth.authorization.requested` | `client_id`, `account` (nil for a social `connection`), `response_type`, `scope`, `audience`, `redirect_uri`, `connection` | `/authorize` received a request for an active client, before consent and before anything is issued (0.65+) |
1261
+ | | `oauth.authorization.granted` | `client_id`, `account`, `response_type`, `scope`, `audience`, `redirect_uri` | An authorization code or implicit token was issued to the client (for a consent-gated client, after approval). Never the code. Not for a social `connection`, which only redirects to the provider (0.65+) |
1262
+ | | `oauth.authorization.denied` | `client_id`, `account`, `scope`, `redirect_uri`, `reason` (`access_denied`) | The account chose Deny on the consent screen (0.65+) |
1232
1263
  | | `oauth.token.issuing` | `grant_type`, `client_id`, `account`, `scope` | Before generating access/refresh tokens |
1233
1264
  | | `oauth.token.issued` | `access_token_id`, `grant_type`, `client_id`, `account`, `expires_in` | After tokens are generated. For a `TokenMinter` mint, `requested_scopes` may be caller-supplied (`requested_scopes:`) rather than the token's `scope` |
1234
- | | `oauth.token.refreshed` | `old_token_id`, `new_token_id`, `client_id`, `account` | After a refresh token is redeemed |
1265
+ | | `oauth.token.refreshed` | `client_id`, `account`, `account_id`, `session_id`, `previous_refresh_token_id`, `refresh_token_id`, `scope`, `graced` | A `refresh_token` grant rotated its token, after `oauth.token.issued` and inside the rotation transaction (a raising subscriber rolls it back). Ids only, never a token (0.65+) |
1235
1266
  | | `oauth.code.consumed` | `authorization_code`, `client_id`, `account` | After an authorization code is exchanged |
1236
1267
  | | `oauth.client.registered` | `client_application`, `client_id`, `client_name`, `client_type`, `redirect_uris`, `scope`, `owner_type`, `owner_id`, `client_metadata` | After a dynamic registration (RFC 7591) commits. Never fails the registration: a raising subscriber is logged |
1237
1268
  | | `oauth.client.updated` | same as `registered` | After an RFC 7592 update commits |
@@ -1242,8 +1273,8 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1242
1273
  | | `passwordless.code.verified` | `code_challenge`, `account`, `channel` | After OTP verification succeeds |
1243
1274
  | | `passwordless.code.failed` | `identifier`, `channel`, `attempts` | After OTP verification fails |
1244
1275
  | | `passwordless.account.created` | `account`, `channel`, `identifier` | When an account is created via passwordless flow |
1245
- | Social | `social.auth.started` | `provider`, `redirect_uri`, `state` | Before redirecting to a social provider |
1246
- | | `social.auth.callback_received` | `provider`, `code`, `state` | After the provider redirects back |
1276
+ | Social | `social.auth.started` | `provider`, `flow` (`web` / `oauth_authorize`), `redirect_uri` (the callback URL), `client_id` (`oauth_authorize` only) | The browser is being sent to the provider: `POST /login` with a `connection`, or `/authorize?connection=…`. Never the state, nonce or PKCE verifier (0.65+) |
1277
+ | | `social.auth.callback_received` | `provider`, `flow` (`web` / `api`), `error` (the provider's, e.g. `access_denied`) | The provider's answer reached the web or API callback. Never the code, state or tokens (0.65+) |
1247
1278
  | | `social.user_info.fetched` | `provider`, `social_info`, `email` | After fetching user info from the provider |
1248
1279
  | | `social.account.created` | `account`, `provider`, `social_info` | When a social login creates a new account |
1249
1280
  | | `social.account.linked` | `account`, `provider`, `identifier` | When a social login links to an existing account by email (published once the link is written, never for a refused login), or matches an existing link by `sub` |
@@ -1254,8 +1285,8 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1254
1285
  | | `credential.password.reset_completed` | `credential`, `account` | After a password reset is confirmed |
1255
1286
  | | `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` |
1256
1287
  | | `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 |
1257
- | | `credential.client_secret.created` | `credential`, `client_id` | After a client secret is created |
1258
- | | `credential.client_secret.rotated` | `credential`, `client_id`, `old_secret_revoked_at` | After a client secret rotation |
1288
+ | | `credential.client_secret.created` | `credential_id`, `client_application_id`, `client_id`, `name` | After a client secret is committed (`create_client_secret!`, rotation, dynamic registration). Ids only: never the record, which still holds the plaintext secret (0.65+) |
1289
+ | | `credential.client_secret.rotated` | `credential_id` (the new secret), `client_application_id`, `client_id`, `revoked_credential_ids`, `old_secret_revoked_at` | After `rotate_client_secret!` commits, following `credential.client_secret.created` (0.65+) |
1259
1290
 
1260
1291
  ### Subscribing to Events
1261
1292
 
@@ -1350,7 +1381,7 @@ end
1350
1381
 
1351
1382
  That's it. Every security-relevant StandardId event will now be persisted as an audit log entry. No changes are needed inside StandardId itself.
1352
1383
 
1353
- `StandardId::Events.auditable` is a frozen list of Regexps and full event names: authentication, account, social and passwordless events; session created, revoked and expired; password and client-secret lifecycle; refresh-token reuse, token revocation, audience mismatches and OAuth client registration changes. It leaves out per-request noise (`session.validating`/`validated`) and high-volume token minting (`oauth.token.issued`/`refreshed`). New releases may add to it, so an app that iterates it picks those up. To audit everything instead, subscribe to `/\Astandard_id\./`.
1384
+ `StandardId::Events.auditable` is a frozen list of Regexps and full event names: authentication, account, social and passwordless events; session created, revoked and expired; password and client-secret lifecycle; refresh-token reuse, token revocation, audience mismatches and OAuth client registration changes. It also has OAuth authorization grants and consent denials (`oauth.authorization.granted`/`denied`). It leaves out per-request noise (`session.validating`/`validated`), events that fire on every token grant or refresh (`oauth.token.issued`/`refreshed`, `session.refreshed`), the `/authorize` request itself (`oauth.authorization.requested`) and identifier verification codes (`identifier.verification.*`), which `passwordless.*` and `authentication.otp.*` already record. Its Regexps cover whole families, so new events in them are audited too. New releases may add to it, so an app that iterates it picks those up. To audit everything instead, subscribe to `/\Astandard_id\./`.
1354
1385
 
1355
1386
  #### Querying audit logs
1356
1387
 
@@ -501,6 +501,19 @@ module StandardId
501
501
  emit_social_auth_completed(provider, social_info, provider_tokens, account, original_request_params)
502
502
  end
503
503
 
504
+ # The provider's answer reached a callback. Only the provider and the
505
+ # error it reported (`access_denied` and the like): never the code, state,
506
+ # id_token or access_token it carries.
507
+ def emit_social_callback_received(flow:)
508
+ error = params[:error]
509
+ StandardId::Events.publish(
510
+ StandardId::Events::SOCIAL_CALLBACK_RECEIVED,
511
+ provider: provider.provider_name,
512
+ flow: flow,
513
+ error: error.is_a?(String) ? error.presence : nil
514
+ )
515
+ end
516
+
504
517
  def emit_social_user_info_fetched(provider, social_info, email)
505
518
  StandardId::Events.publish(
506
519
  StandardId::Events::SOCIAL_USER_INFO_FETCHED,
@@ -160,6 +160,15 @@ module StandardId
160
160
  StandardId::PasswordPepper.dummy_authenticate(password) unless password_credential
161
161
 
162
162
  unless authenticated
163
+ if password_credential
164
+ StandardId::Events.publish(
165
+ StandardId::Events::PASSWORD_VALIDATION_FAILED,
166
+ account_lookup: login,
167
+ account: password_credential.credential&.account,
168
+ credential_id: password_credential.id,
169
+ error_code: "invalid_password"
170
+ )
171
+ end
163
172
  StandardId::Events.publish(
164
173
  StandardId::Events::AUTHENTICATION_FAILED,
165
174
  account_lookup: login,
@@ -17,6 +17,7 @@ module StandardId
17
17
 
18
18
  def show
19
19
  reject_invalid_redirect_uri!
20
+ emit_authorization_requested
20
21
  return redirect_to_consent if consent_required?
21
22
 
22
23
  response_data = flow_strategy_class.new(
@@ -52,6 +53,27 @@ module StandardId
52
53
  raise StandardId::InvalidRequestError, "Invalid redirect_uri"
53
54
  end
54
55
 
56
+ # Once per /authorize request for an active client, before consent and
57
+ # before anything is issued. The consent screen's approval resumes the
58
+ # flow without coming back here, so it is not published twice. An unknown
59
+ # client publishes nothing: the flow refuses it. A social connection
60
+ # names no account (it is resolved at the provider's callback), and its
61
+ # browser session is not read here, as it never was.
62
+ def emit_authorization_requested
63
+ return if consent_client.nil?
64
+
65
+ StandardId::Events.publish(
66
+ StandardId::Events::OAUTH_AUTHORIZATION_REQUESTED,
67
+ client_id: consent_client.client_id,
68
+ account: social_login? ? nil : current_account,
69
+ response_type: response_type,
70
+ scope: params[:scope].presence,
71
+ audience: params[:audience].presence,
72
+ redirect_uri: params[:redirect_uri].presence,
73
+ connection: params[:connection].presence
74
+ )
75
+ end
76
+
55
77
  # An interactive authorization-code request needs a consent screen when:
56
78
  # * the user is authenticated,
57
79
  # * the request is an interactive (HTML) request — not JSON, not a
@@ -34,6 +34,20 @@ module StandardId
34
34
  # A host hook refused the request with its own response.
35
35
  rescue_from StandardId::RequestRefused, with: :handle_request_refused
36
36
 
37
+ # Narrows the bearer audiences this endpoint accepts to
38
+ # `c.oauth.endpoint_audiences[endpoint]` when the host set it
39
+ # (StandardId::Oauth::Audiences.endpoint): a token with none of them is
40
+ # refused by StandardId::AudienceVerification, 403 insufficient_scope.
41
+ # Unset, any accepted audience passes, as before. Declare it after
42
+ # `before_action :verify_access_token!`, which the check runs behind.
43
+ def self.endpoint_audiences(endpoint)
44
+ include StandardId::AudienceVerification
45
+
46
+ verify_audience -> { StandardId::Oauth::Audiences.endpoint(endpoint) }
47
+ skip_before_action :verify_audience!, if: -> { StandardId::Oauth::Audiences.endpoint(endpoint).empty? }
48
+ rescue_from StandardId::InvalidAudienceError, with: ->(error) { reject_endpoint_audience(error, endpoint) }
49
+ end
50
+
37
51
  protected
38
52
 
39
53
  def validate_content_type!
@@ -93,6 +107,32 @@ module StandardId
93
107
  }, status: error.http_status
94
108
  end
95
109
 
110
+ # AudienceVerification publishes oauth.audience.mismatch only when a
111
+ # profile binding fails; a token refused here for its audience alone is
112
+ # recorded too, then answered as AudienceVerification answers it. A
113
+ # failing subscriber is logged, as there, and does not change the 403.
114
+ def reject_endpoint_audience(error, endpoint)
115
+ publish_endpoint_audience_mismatch(error, endpoint)
116
+ handle_invalid_audience(error)
117
+ end
118
+
119
+ def publish_endpoint_audience_mismatch(error, endpoint)
120
+ StandardId::Events.publish(
121
+ StandardId::Events::OAUTH_AUDIENCE_MISMATCH,
122
+ audience: nil,
123
+ token_audiences: error.actual,
124
+ required_audiences: error.required,
125
+ expected_profile_types: [],
126
+ actual_profile_type: nil,
127
+ endpoint: endpoint.to_s,
128
+ account: current_account
129
+ )
130
+ rescue StandardError => e
131
+ StandardId.config.logger&.warn(
132
+ "[StandardId] failed to emit oauth.audience.mismatch event: #{e.class}: #{e.message}"
133
+ )
134
+ end
135
+
96
136
  def handle_request_refused(error)
97
137
  error.headers.each { |name, value| response.set_header(name.to_s, value.to_s) }
98
138
  render json: error.body, status: error.status
@@ -19,6 +19,7 @@ module StandardId
19
19
  ].freeze
20
20
 
21
21
  def callback
22
+ emit_social_callback_received(flow: "api")
22
23
  provider_response = fetch_provider_user_info
23
24
  social_info = provider_response[:user_info]
24
25
  provider_tokens = provider_response[:tokens]
@@ -5,6 +5,7 @@ module StandardId
5
5
 
6
6
  skip_before_action :validate_content_type!
7
7
  before_action :verify_access_token!
8
+ endpoint_audiences :sessions
8
9
 
9
10
  def index
10
11
  sessions = current_account.sessions.active.order(created_at: :desc)
@@ -16,7 +16,8 @@ module StandardId
16
16
  # token is issued: the client keeps its own, and tokens refreshed from it
17
17
  # carry the original sign-in's auth_time. For an audience bound to a
18
18
  # profile type, set c.step_up.token_profile_resolver when an account may
19
- # hold several such profiles. Routed only while c.step_up.enabled is true.
19
+ # hold several such profiles. c.oauth.endpoint_audiences[:step_up] narrows
20
+ # which tokens may step up. Routed only while c.step_up.enabled is true.
20
21
  class StepUpController < BaseController
21
22
  authenticated_controller
22
23
 
@@ -27,6 +28,7 @@ module StandardId
27
28
  store: StandardId::RateLimitHandling::RATE_LIMIT_STORE
28
29
 
29
30
  before_action :verify_access_token!
31
+ endpoint_audiences :step_up
30
32
  # A token whose account config.account_scope no longer finds is no
31
33
  # longer anyone's to step up.
32
34
  before_action -> { render_bearer_unauthorized! if current_account.nil? }
@@ -4,9 +4,10 @@ module StandardId
4
4
  authenticated_controller
5
5
 
6
6
  skip_before_action :validate_content_type!
7
+ before_action :verify_access_token!
8
+ endpoint_audiences :userinfo
7
9
 
8
10
  def show
9
- verify_access_token!
10
11
  account = current_account
11
12
  raise StandardId::NotAuthenticatedError unless account
12
13
 
@@ -17,6 +17,8 @@ module StandardId
17
17
  skip_before_action :verify_authenticity_token, only: [:callback, :mobile_callback], if: :skip_csrf_verification?
18
18
 
19
19
  def callback
20
+ emit_social_callback_received(flow: "web")
21
+
20
22
  if params[:error].present?
21
23
  handle_callback_error
22
24
  return
@@ -92,7 +92,16 @@ module StandardId
92
92
  end
93
93
 
94
94
  def deny!
95
- redirect_out(denied_redirect_uri, status: :found)
95
+ url = denied_redirect_uri
96
+ StandardId::Events.publish(
97
+ StandardId::Events::OAUTH_AUTHORIZATION_DENIED,
98
+ client_id: @client.client_id,
99
+ account: current_account,
100
+ scope: @consent_request[:scope],
101
+ redirect_uri: @consent_request[:redirect_uri],
102
+ reason: "access_denied"
103
+ )
104
+ redirect_out(url, status: :found)
96
105
  end
97
106
 
98
107
  # Redirect to the OAuth client's (external) redirect_uri in a way that
@@ -151,6 +151,14 @@ module StandardId
151
151
  **extra_params.compact
152
152
  )
153
153
 
154
+ # Never the state, nonce or PKCE verifier: they guard the callback.
155
+ StandardId::Events.publish(
156
+ StandardId::Events::SOCIAL_AUTH_STARTED,
157
+ provider: provider.provider_name,
158
+ flow: "web",
159
+ redirect_uri: callback_url
160
+ )
161
+
154
162
  redirect_with_inertia url, allow_other_host: true
155
163
  rescue StandardId::ProviderRegistry::ProviderNotFoundError => e
156
164
  raise StandardId::InvalidRequestError, e.message
@@ -24,7 +24,10 @@ module StandardId
24
24
  return redirect_to(standard_id_web.login_path, alert: "Invalid or expired verification code") if code.blank?
25
25
 
26
26
  result = StandardId::Otp.verify(realm: "verification", target: target, code: code, channel: :email, request: request)
27
- return redirect_to(standard_id_web.login_path, alert: result.error) unless result.success?
27
+ unless result.success?
28
+ StandardId::Identifier.publish_verification_failed(value: target, channel: :email, realm: "verification", result: result)
29
+ return redirect_to(standard_id_web.login_path, alert: result.error)
30
+ end
28
31
 
29
32
  StandardId::EmailIdentifier.find_by(value: target)&.verify!
30
33
 
@@ -54,6 +54,8 @@ module StandardId
54
54
  render plain: result.error_message, status: :unprocessable_content and return
55
55
  end
56
56
 
57
+ StandardId::Identifier.publish_verification_started(value: email, channel: :email, realm: "verification")
58
+
57
59
  redirect_to standard_id_web.login_path, notice: "Verification code sent to your email", status: :see_other
58
60
  end
59
61
  end
@@ -24,7 +24,10 @@ module StandardId
24
24
  return redirect_to(standard_id_web.login_path, alert: "Invalid or expired verification code") if code.blank?
25
25
 
26
26
  result = StandardId::Otp.verify(realm: "verification", target: target, code: code, channel: :sms, request: request)
27
- return redirect_to(standard_id_web.login_path, alert: result.error) unless result.success?
27
+ unless result.success?
28
+ StandardId::Identifier.publish_verification_failed(value: target, channel: :sms, realm: "verification", result: result)
29
+ return redirect_to(standard_id_web.login_path, alert: result.error)
30
+ end
28
31
 
29
32
  StandardId::PhoneNumberIdentifier.find_by(value: target)&.verify!
30
33
 
@@ -54,6 +54,8 @@ module StandardId
54
54
  render plain: result.error_message, status: :unprocessable_content and return
55
55
  end
56
56
 
57
+ StandardId::Identifier.publish_verification_started(value: phone, channel: :sms, realm: "verification")
58
+
57
59
  redirect_to standard_id_web.login_path, notice: "Verification code sent via SMS", status: :see_other
58
60
  end
59
61
  end
@@ -281,18 +281,26 @@ module StandardId
281
281
  client_secret_credentials.active.first
282
282
  end
283
283
 
284
- # Client secret rotation support
284
+ # Client secret rotation support. Publishes CREDENTIAL_CLIENT_SECRET_CREATED
285
+ # for the new secret and then CREDENTIAL_CLIENT_SECRET_ROTATED, both once
286
+ # the rotation commits.
285
287
  def rotate_client_secret!(new_secret_name: "Rotated Secret #{Time.current.strftime('%Y%m%d')}", client_secret: SecureRandom.hex(32))
286
288
  transaction do
287
289
  # Create new secret
288
290
  new_secret = create_client_secret!(name: new_secret_name, client_secret: client_secret)
289
291
 
290
292
  # Deactivate old secrets (but don't delete for audit trail)
293
+ revoked_at = Time.current
294
+ superseded = client_secret_credentials.where.not(id: new_secret.id).where(revoked_at: nil)
295
+ revoked_ids = superseded.pluck(:id)
291
296
  client_secret_credentials.where.not(id: new_secret.id).update_all(
292
297
  active: false,
293
- revoked_at: Time.current
298
+ revoked_at: revoked_at
294
299
  )
295
300
 
301
+ ActiveRecord.after_all_transactions_commit do
302
+ publish_client_secret_rotated(new_secret, revoked_ids: revoked_ids, revoked_at: revoked_at)
303
+ end
296
304
  new_secret
297
305
  end
298
306
  end
@@ -304,6 +312,23 @@ module StandardId
304
312
 
305
313
  private
306
314
 
315
+ # Ids only, never the secret records (see ClientSecretCredential's
316
+ # CREATED event). The rotation has committed, so a failing subscriber is
317
+ # reported rather than raised.
318
+ def publish_client_secret_rotated(new_secret, revoked_ids:, revoked_at:)
319
+ StandardId::Events.publish(
320
+ StandardId::Events::CREDENTIAL_CLIENT_SECRET_ROTATED,
321
+ credential_id: new_secret.id,
322
+ client_application_id: id,
323
+ client_id: client_id,
324
+ revoked_credential_ids: revoked_ids,
325
+ old_secret_revoked_at: revoked_at
326
+ )
327
+ rescue StandardError => e
328
+ StandardId::ErrorReporting.report(e, event: StandardId::Events.namespaced_event_name(StandardId::Events::CREDENTIAL_CLIENT_SECRET_ROTATED))
329
+ StandardId.logger&.error("[StandardId::ClientApplication] Failed to publish CREDENTIAL_CLIENT_SECRET_ROTATED for #{client_id}: #{e.class}: #{e.message}")
330
+ end
331
+
307
332
  # Registered redirect URIs must be absolute (include scheme + host) and
308
333
  # must NOT carry a query string or fragment. Allowing either would turn
309
334
  # the whitelist into a prefix match and enable "query-param piggyback"
@@ -9,6 +9,7 @@ module StandardId
9
9
 
10
10
  before_validation :set_client_id_from_client, on: :create
11
11
  before_validation :ensure_client_secret, on: :create
12
+ after_commit :emit_created_event, on: :create
12
13
 
13
14
  validates :name, presence: true
14
15
  validates :client_id, presence: true
@@ -58,6 +59,23 @@ module StandardId
58
59
  self.client_secret ||= SecureRandom.hex(32)
59
60
  end
60
61
 
62
+ # Ids and the secret's name only, never the record: just after create it
63
+ # still holds the plaintext secret (`client_secret`), and its digest is
64
+ # no business of a subscriber's. The row has committed, so a failing
65
+ # subscriber is reported rather than raised.
66
+ def emit_created_event
67
+ StandardId::Events.publish(
68
+ StandardId::Events::CREDENTIAL_CLIENT_SECRET_CREATED,
69
+ credential_id: id,
70
+ client_application_id: client_application_id,
71
+ client_id: client_id,
72
+ name: name
73
+ )
74
+ rescue StandardError => e
75
+ StandardId::ErrorReporting.report(e, event: StandardId::Events.namespaced_event_name(StandardId::Events::CREDENTIAL_CLIENT_SECRET_CREATED))
76
+ StandardId.logger&.error("[StandardId::ClientSecretCredential] Failed to publish CREDENTIAL_CLIENT_SECRET_CREATED for #{id}: #{e.class}: #{e.message}")
77
+ end
78
+
61
79
  def emit_revoked_event
62
80
  StandardId::Events.publish(
63
81
  StandardId::Events::CREDENTIAL_CLIENT_SECRET_REVOKED,
@@ -37,6 +37,34 @@ module StandardId
37
37
  update!(verified_at: nil)
38
38
  end
39
39
 
40
+ # IDENTIFIER_VERIFICATION_STARTED: a code to prove +value+ (an address,
41
+ # whether or not an identifier row exists for it yet) was issued.
42
+ def self.publish_verification_started(value:, channel:, realm:)
43
+ StandardId::Events.publish(
44
+ StandardId::Events::IDENTIFIER_VERIFICATION_STARTED,
45
+ identifier: value,
46
+ channel: channel.to_s,
47
+ realm: realm
48
+ )
49
+ end
50
+
51
+ # IDENTIFIER_VERIFICATION_FAILED for a failed Otp.verify +result+, only
52
+ # when a live code was guessed wrong (result.attempts > 0), as
53
+ # OTP_VALIDATION_FAILED: a target that was never sent a code is a probe,
54
+ # not a failed verification.
55
+ def self.publish_verification_failed(value:, channel:, realm:, result:)
56
+ return unless result.attempts.to_i.positive?
57
+
58
+ StandardId::Events.publish(
59
+ StandardId::Events::IDENTIFIER_VERIFICATION_FAILED,
60
+ identifier: value,
61
+ channel: channel.to_s,
62
+ realm: realm,
63
+ error_code: result.error_code&.to_s,
64
+ attempts: result.attempts
65
+ )
66
+ end
67
+
40
68
  private
41
69
 
42
70
  def just_verified?
@@ -367,6 +367,16 @@ StandardId.configure do |c|
367
367
  # for other services lists them as mintable but not accepted:
368
368
  # c.oauth.mintable_audiences = %w[web harness inference]
369
369
  # c.oauth.accepted_audiences = %w[web]
370
+ #
371
+ # Narrow the gem's own bearer endpoints (userinfo, sessions, step_up) to the
372
+ # end-user clients' audiences; a token for any other accepted audience gets
373
+ # 403. An endpoint left out accepts any accepted audience.
374
+ # Default: {}
375
+ # c.oauth.endpoint_audiences = {
376
+ # userinfo: %w[web mobile],
377
+ # sessions: %w[web mobile],
378
+ # step_up: %w[web mobile]
379
+ # }
370
380
 
371
381
  # Scope-to-claims mapping — when a scope is granted, every listed claim is
372
382
  # resolved via claim_resolvers below and embedded in the access token.
@@ -95,6 +95,12 @@ module StandardId
95
95
  account: self,
96
96
  previous_status: status_previously_was
97
97
  )
98
+ StandardId::Events.publish(
99
+ StandardId::Events::ACCOUNT_STATUS_CHANGED,
100
+ account: self,
101
+ previous_status: status_previously_was,
102
+ status: status
103
+ )
98
104
  end
99
105
  end
100
106
  end
@@ -660,6 +660,25 @@ StandardId::ConfigSchema.define do
660
660
  # neither list applies to it.
661
661
  field :accepted_audiences, type: :array, default: nil
662
662
 
663
+ # Audiences each of the gem's own bearer endpoints accepts, on top of the
664
+ # accepted list: a token with none of them gets 403 insufficient_scope
665
+ # (StandardId::AudienceVerification). Keys are the endpoints
666
+ # (StandardId::Oauth::Audiences::ENDPOINTS):
667
+ #
668
+ # :userinfo GET /userinfo
669
+ # :sessions GET /sessions, DELETE /sessions/:id
670
+ # :step_up POST /step_up, POST /step_up/verify
671
+ #
672
+ # c.oauth.endpoint_audiences = {
673
+ # userinfo: %w[companion_kit admin_kit],
674
+ # sessions: %w[companion_kit admin_kit],
675
+ # step_up: %w[companion_kit admin_kit]
676
+ # }
677
+ #
678
+ # An endpoint left out (or given an empty list) accepts any accepted
679
+ # audience, as before. An unknown key raises ConfigurationError at boot.
680
+ field :endpoint_audiences, type: :hash, default: -> { {} }
681
+
663
682
  # Audience → profile type binding (first-class audience modeling).
664
683
  #
665
684
  # Maps each configured audience string to the profile type (or types)
@@ -37,7 +37,8 @@ module StandardId
37
37
 
38
38
  identifier = password_credential.credential&.identifier
39
39
  verified_digest = password_credential.password_digest
40
- failed!(email) unless identifier && password_credential.authenticate(password)
40
+ failed!(email) unless identifier
41
+ failed!(email, password_credential) unless password_credential.authenticate(password)
41
42
 
42
43
  account = identifier.account
43
44
  StandardId::Events.publish(
@@ -61,7 +62,19 @@ module StandardId
61
62
 
62
63
  private
63
64
 
64
- def failed!(email)
65
+ # +password_credential+ is given when the address has one and the
66
+ # password did not match it: only then is PASSWORD_VALIDATION_FAILED
67
+ # published as well.
68
+ def failed!(email, password_credential = nil)
69
+ if password_credential
70
+ StandardId::Events.publish(
71
+ StandardId::Events::PASSWORD_VALIDATION_FAILED,
72
+ account_lookup: email,
73
+ account: password_credential.account,
74
+ credential_id: password_credential.id,
75
+ error_code: "invalid_password"
76
+ )
77
+ end
65
78
  StandardId::Events.publish(
66
79
  StandardId::Events::AUTHENTICATION_FAILED,
67
80
  account_lookup: email,
@@ -52,7 +52,7 @@ module StandardId
52
52
  code: code.to_s.strip,
53
53
  request: request
54
54
  )
55
- failed!(email, otp.error_code) unless otp.success?
55
+ failed!(email, otp) unless otp.success?
56
56
 
57
57
  # The hook runs in the same transaction as the verification: if it
58
58
  # raises, the address stays unverified, so the registrant can ask for
@@ -120,6 +120,7 @@ module StandardId
120
120
  return false unless result.success?
121
121
 
122
122
  DailyLimit.record!(:code_issued, email)
123
+ StandardId::Identifier.publish_verification_started(value: email, channel: :email, realm: config.verification_realm)
123
124
  if built_in
124
125
  StandardId::PasswordlessMailer
125
126
  .with(email: email, otp_code: result.code, realm: config.verification_realm)
@@ -138,11 +139,14 @@ module StandardId
138
139
  raise invalid_code(INVALID_CODE_MESSAGE) unless password_credential.password_digest == verified_digest
139
140
  end
140
141
 
141
- def failed!(email, error_code)
142
+ def failed!(email, otp)
143
+ StandardId::Identifier.publish_verification_failed(
144
+ value: email, channel: :email, realm: EmailPassword.config.verification_realm, result: otp
145
+ )
142
146
  count = DailyLimit.record!(:failed_verification, email)
143
147
  message = if count >= DailyLimit.limit(:failed_verification)
144
148
  LOCKED_OUT_MESSAGE
145
- elsif error_code == :max_attempts
149
+ elsif otp.error_code == :max_attempts
146
150
  TOO_MANY_ATTEMPTS_MESSAGE
147
151
  else
148
152
  INVALID_CODE_MESSAGE
@@ -96,10 +96,12 @@ module StandardId
96
96
  StandardId::Config::CallableValidator.validate!
97
97
  StandardId::Config::ScopeClaimsValidator.validate!
98
98
  StandardId::ScopeConfig.validate_all!
99
+ StandardId::Oauth::Audiences.validate_endpoint_audiences!
99
100
 
100
101
  StandardId::Engine.verify_host_cookie_encryption!(app)
101
102
  StandardId::MigrationCheck.verify_at_boot!
102
103
  StandardId::Engine.warn_if_allowed_audiences_empty_in_production!
104
+ StandardId::Engine.warn_if_endpoint_audiences_unset_in_production!
103
105
  end
104
106
 
105
107
  # Defensive check: StandardId's Web::SessionManager stores session tokens
@@ -176,6 +178,28 @@ module StandardId
176
178
  )
177
179
  end
178
180
 
181
+ # Logs a production-only warning naming the gem's bearer endpoints
182
+ # (`userinfo`, `sessions`, `step_up`) that `oauth.endpoint_audiences` leaves
183
+ # open while the API accepts more than one audience: a token for any of
184
+ # them (an MCP or per-service token, say) can then read the account and
185
+ # its sessions. Silent with one accepted audience, where there is nothing
186
+ # to narrow, and with none, which the accepted-audiences warning covers.
187
+ # `step_up` counts only while step-up is enabled (its routes exist).
188
+ def self.warn_if_endpoint_audiences_unset_in_production!
189
+ return unless StandardId::AppEnvironment.production?
190
+ return unless StandardId::Oauth::Audiences.accepted.size > 1
191
+
192
+ open = StandardId::Oauth::Audiences.unrestricted_endpoints
193
+ open -= [:step_up] unless StandardId::StepUp.enabled?
194
+ return if open.empty?
195
+
196
+ Rails.logger.warn(
197
+ "StandardId: config.oauth.endpoint_audiences does not restrict #{open.join(', ')} in production — " \
198
+ "they accept a bearer for any accepted audience (#{StandardId::Oauth::Audiences.accepted.join(', ')}). " \
199
+ "List the audiences of the end-user clients that call them."
200
+ )
201
+ end
202
+
179
203
  # Warn when the issuer configuration is missing or when `verify_issuer`
180
204
  # is explicitly `false` with an issuer set (migration flag left behind).
181
205
  # Extracted to a module method so specs can exercise it without booting
@@ -5,6 +5,9 @@ module StandardId
5
5
  AUTHENTICATION_SUCCEEDED = "authentication.attempt.succeeded"
6
6
  AUTHENTICATION_FAILED = "authentication.attempt.failed"
7
7
  PASSWORD_VALIDATED = "authentication.password.validated"
8
+ # A password was checked against an existing password credential and did
9
+ # not match. A login that names no credential at all publishes only
10
+ # AUTHENTICATION_FAILED, as an OTP for a target with no challenge does.
8
11
  PASSWORD_VALIDATION_FAILED = "authentication.password.failed"
9
12
  OTP_VALIDATED = "authentication.otp.validated"
10
13
  OTP_VALIDATION_FAILED = "authentication.otp.failed"
@@ -23,11 +26,15 @@ module StandardId
23
26
  SESSION_VALIDATED = "session.validated"
24
27
  SESSION_EXPIRED = "session.expired"
25
28
  SESSION_REVOKED = "session.revoked"
29
+ # An OAuth token grant reused the device's active DeviceSession and moved
30
+ # its expires_at forward (session.session_type_resolver -> :device).
26
31
  SESSION_REFRESHED = "session.refreshed"
27
32
 
28
33
  ACCOUNT_CREATING = "account.creating"
29
34
  ACCOUNT_CREATED = "account.created"
30
35
  ACCOUNT_VERIFIED = "account.verified"
36
+ # Any committed change to AccountStatus's status column, published after
37
+ # ACCOUNT_ACTIVATED / ACCOUNT_DEACTIVATED.
31
38
  ACCOUNT_STATUS_CHANGED = "account.status_changed"
32
39
  ACCOUNT_ACTIVATED = "account.activated"
33
40
  ACCOUNT_DEACTIVATED = "account.deactivated"
@@ -35,16 +42,22 @@ module StandardId
35
42
  ACCOUNT_UNLOCKED = "account.unlocked"
36
43
 
37
44
  IDENTIFIER_CREATED = "identifier.created"
45
+ # Proving an address (the "verification" realm of /verify-email and
46
+ # /verify-phone, and c.email_password's sign-up code): a code was issued,
47
+ # the address was verified, or a wrong code was sent for a live code.
38
48
  IDENTIFIER_VERIFICATION_STARTED = "identifier.verification.started"
39
49
  IDENTIFIER_VERIFICATION_SUCCEEDED = "identifier.verification.succeeded"
40
50
  IDENTIFIER_VERIFICATION_FAILED = "identifier.verification.failed"
41
- IDENTIFIER_LINKED = "identifier.linked"
42
51
 
52
+ # /authorize: a request for an active client arrived, an authorization
53
+ # response (code or implicit token) was issued, or the account refused
54
+ # the client on the consent screen.
43
55
  OAUTH_AUTHORIZATION_REQUESTED = "oauth.authorization.requested"
44
56
  OAUTH_AUTHORIZATION_GRANTED = "oauth.authorization.granted"
45
57
  OAUTH_AUTHORIZATION_DENIED = "oauth.authorization.denied"
46
58
  OAUTH_TOKEN_ISSUING = "oauth.token.issuing"
47
59
  OAUTH_TOKEN_ISSUED = "oauth.token.issued"
60
+ # A refresh_token grant rotated its token (after OAUTH_TOKEN_ISSUED).
48
61
  OAUTH_TOKEN_REFRESHED = "oauth.token.refreshed"
49
62
  OAUTH_CODE_CONSUMED = "oauth.code.consumed"
50
63
  OAUTH_TOKEN_REVOKED = "oauth.token.revoked"
@@ -62,6 +75,8 @@ module StandardId
62
75
  PASSWORDLESS_CODE_FAILED = "passwordless.code.failed"
63
76
  PASSWORDLESS_ACCOUNT_CREATED = "passwordless.account.created"
64
77
 
78
+ # The browser was sent to a social provider, and the provider's answer
79
+ # reached a callback.
65
80
  SOCIAL_AUTH_STARTED = "social.auth.started"
66
81
  SOCIAL_CALLBACK_RECEIVED = "social.auth.callback_received"
67
82
  SOCIAL_USER_INFO_FETCHED = "social.user_info.fetched"
@@ -122,8 +137,7 @@ module StandardId
122
137
  IDENTIFIER_CREATED,
123
138
  IDENTIFIER_VERIFICATION_STARTED,
124
139
  IDENTIFIER_VERIFICATION_SUCCEEDED,
125
- IDENTIFIER_VERIFICATION_FAILED,
126
- IDENTIFIER_LINKED
140
+ IDENTIFIER_VERIFICATION_FAILED
127
141
  ].freeze
128
142
 
129
143
  OAUTH_EVENTS = [
@@ -32,7 +32,6 @@ module StandardId
32
32
  "identifier.verification.started" => :debug,
33
33
  "identifier.verification.succeeded" => :info,
34
34
  "identifier.verification.failed" => :warn,
35
- "identifier.linked" => :info,
36
35
  "oauth.authorization.requested" => :debug,
37
36
  "oauth.authorization.granted" => :info,
38
37
  "oauth.authorization.denied" => :info,
@@ -27,8 +27,11 @@ module StandardId
27
27
  "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_CREATED}",
28
28
  "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_ROTATED}",
29
29
  "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_REVOKED}",
30
- # OAuth: token theft and revocation, a token sent to the wrong resource,
31
- # and changes to who may request tokens at all.
30
+ # OAuth: an account handing a client access, or refusing it on the
31
+ # consent screen; token theft and revocation, a token sent to the wrong
32
+ # resource, and changes to who may request tokens at all.
33
+ "#{NAMESPACE}.#{OAUTH_AUTHORIZATION_GRANTED}",
34
+ "#{NAMESPACE}.#{OAUTH_AUTHORIZATION_DENIED}",
32
35
  "#{NAMESPACE}.#{OAUTH_REFRESH_TOKEN_REUSE_DETECTED}",
33
36
  "#{NAMESPACE}.#{OAUTH_TOKEN_REVOKED}",
34
37
  "#{NAMESPACE}.#{OAUTH_AUDIENCE_MISMATCH}",
@@ -45,9 +48,18 @@ module StandardId
45
48
  # end
46
49
  #
47
50
  # Deliberately left out: per-request noise (session.validating /
48
- # validated), high-volume token minting (oauth.token.issued,
49
- # oauth.token.refreshed), and the benign refresh race
50
- # (oauth.refresh_token.reuse_graced).
51
+ # validated), events that fire on every token grant or refresh
52
+ # (oauth.token.issued, oauth.token.refreshed, session.refreshed), the
53
+ # benign refresh race (oauth.refresh_token.reuse_graced), an /authorize
54
+ # request before anything is decided (oauth.authorization.requested;
55
+ # .granted and .denied are the outcome), and identifier verification
56
+ # codes, whose issue and failure the passwordless.* and
57
+ # authentication.otp.* events already record.
58
+ #
59
+ # The Regexps match every event in their family, so a family's new
60
+ # events are audited too: authentication.password.failed,
61
+ # account.status_changed, social.auth.started and
62
+ # social.auth.callback_received (all published from 0.65.0).
51
63
  #
52
64
  # @return [Array<Regexp, String>] frozen
53
65
  def auditable
@@ -19,7 +19,14 @@ module StandardId
19
19
  #
20
20
  # An empty effective list means no restriction on that side, as an empty
21
21
  # allowed_audiences always has.
22
+ #
23
+ # On top of the accepted list, `oauth.endpoint_audiences` narrows what each
24
+ # of the gem's own bearer endpoints accepts (see .endpoint).
22
25
  module Audiences
26
+ # The gem's bearer endpoints that return or change the account's data,
27
+ # by their `oauth.endpoint_audiences` key.
28
+ ENDPOINTS = %i[userinfo sessions step_up].freeze
29
+
23
30
  module_function
24
31
 
25
32
  # @return [Array<String>]
@@ -32,6 +39,38 @@ module StandardId
32
39
  resolve(StandardId.config.oauth.accepted_audiences)
33
40
  end
34
41
 
42
+ # The audiences `oauth.endpoint_audiences` lets +endpoint+ accept. Empty
43
+ # when the host set none, which means any accepted audience.
44
+ #
45
+ # @param endpoint [Symbol] one of ENDPOINTS
46
+ # @return [Array<String>]
47
+ def endpoint(endpoint)
48
+ map = StandardId.config.oauth.endpoint_audiences || {}
49
+ list = map.key?(endpoint.to_sym) ? map[endpoint.to_sym] : map[endpoint.to_s]
50
+ Array(list).map(&:to_s).reject(&:blank?)
51
+ end
52
+
53
+ # ENDPOINTS that `oauth.endpoint_audiences` leaves open.
54
+ #
55
+ # @return [Array<Symbol>]
56
+ def unrestricted_endpoints
57
+ ENDPOINTS.select { |name| endpoint(name).empty? }
58
+ end
59
+
60
+ # A mistyped key would leave its endpoint open without a word, so refuse
61
+ # it at boot.
62
+ #
63
+ # @raise [StandardId::ConfigurationError]
64
+ def validate_endpoint_audiences!
65
+ map = StandardId.config.oauth.endpoint_audiences || {}
66
+ unknown = map.keys.map(&:to_s) - ENDPOINTS.map(&:to_s)
67
+ return if unknown.empty?
68
+
69
+ raise StandardId::ConfigurationError,
70
+ "config.oauth.endpoint_audiences has unknown endpoint(s) #{unknown.join(', ')}; " \
71
+ "expected any of #{ENDPOINTS.join(', ')}"
72
+ end
73
+
35
74
  def resolve(override)
36
75
  list = override.nil? ? StandardId.config.oauth.allowed_audiences : override
37
76
  Array(list).map(&:to_s)
@@ -25,6 +25,12 @@ module StandardId
25
25
  subflow_for(params).call
26
26
  end
27
27
 
28
+ # A social connection only redirects to the provider; nothing is issued
29
+ # to the client until its callback.
30
+ def grants_authorization?
31
+ params[:connection].blank?
32
+ end
33
+
28
34
  def subflow_for(flow_params)
29
35
  builders = {
30
36
  social: -> do
@@ -23,11 +23,31 @@ module StandardId
23
23
  validate_params!
24
24
  authenticate_client!
25
25
  enforce_audience_scopes!
26
- generate_authorization_response
26
+ response = generate_authorization_response
27
+ emit_authorization_granted if grants_authorization?
28
+ response
27
29
  end
28
30
 
29
31
  private
30
32
 
33
+ # Whether #generate_authorization_response hands the client something
34
+ # for the account (a code, a token). False for a hand-off elsewhere.
35
+ def grants_authorization?
36
+ true
37
+ end
38
+
39
+ def emit_authorization_granted
40
+ StandardId::Events.publish(
41
+ StandardId::Events::OAUTH_AUTHORIZATION_GRANTED,
42
+ client_id: @client.client_id,
43
+ account: current_account,
44
+ response_type: params[:response_type],
45
+ scope: scope,
46
+ audience: audience,
47
+ redirect_uri: redirect_uri
48
+ )
49
+ end
50
+
31
51
  def validate_params!
32
52
  if params[:response_type].blank?
33
53
  raise StandardId::InvalidRequestError, "The response_type parameter is required"
@@ -74,7 +74,7 @@ module StandardId
74
74
  account.class.where(id: account.id).lock.first
75
75
 
76
76
  existing = active_device_session(account: account, device_id: device_id)
77
- return refresh_device_session!(existing, ip_address: ip_address, user_agent: user_agent, authenticated_at: authenticated_at) if existing
77
+ return refresh_device_session!(existing, account: account, ip_address: ip_address, user_agent: user_agent, authenticated_at: authenticated_at, grant_type: grant_type) if existing
78
78
 
79
79
  begin
80
80
  # Savepoint, so a unique violation does not abort the enclosing token
@@ -96,7 +96,7 @@ module StandardId
96
96
  winner = active_device_session(account: account, device_id: device_id)
97
97
  raise unless winner
98
98
 
99
- refresh_device_session!(winner, ip_address: ip_address, user_agent: user_agent, authenticated_at: authenticated_at)
99
+ refresh_device_session!(winner, account: account, ip_address: ip_address, user_agent: user_agent, authenticated_at: authenticated_at, grant_type: grant_type)
100
100
  end
101
101
  end
102
102
 
@@ -111,17 +111,38 @@ module StandardId
111
111
  .first
112
112
  end
113
113
 
114
- def refresh_device_session!(session, ip_address:, user_agent:, authenticated_at: nil)
114
+ # SESSION_REFRESHED waits for the token transaction to commit (a grant
115
+ # that rolls back extended nothing), so a failing subscriber is reported
116
+ # rather than raised: the tokens have been issued by then.
117
+ def refresh_device_session!(session, account:, ip_address:, user_agent:, authenticated_at: nil, grant_type: nil)
115
118
  latest = [session.try(:authenticated_at), authenticated_at].compact.max
119
+ previous_expires_at = session.expires_at
116
120
  session.update!(
117
121
  expires_at: StandardId::DeviceSession.expiry,
118
122
  ip_address: ip_address || session.ip_address,
119
123
  device_agent: user_agent || session.device_agent,
120
124
  **authenticated_at_attributes(latest)
121
125
  )
126
+ ActiveRecord.after_all_transactions_commit do
127
+ publish_session_refreshed(session, account: account, previous_expires_at: previous_expires_at, grant_type: grant_type)
128
+ end
122
129
  session
123
130
  end
124
131
 
132
+ def publish_session_refreshed(session, account:, previous_expires_at:, grant_type:)
133
+ StandardId::Events.publish(
134
+ StandardId::Events::SESSION_REFRESHED,
135
+ session: session,
136
+ account: account,
137
+ previous_expires_at: previous_expires_at,
138
+ expires_at: session.expires_at,
139
+ grant_type: grant_type
140
+ )
141
+ rescue StandardError => e
142
+ StandardId::ErrorReporting.report(e, event: StandardId::Events.namespaced_event_name(StandardId::Events::SESSION_REFRESHED))
143
+ StandardId.logger&.error("[StandardId] SESSION_REFRESHED subscriber raised after the session was extended: #{e.class}: #{e.message}")
144
+ end
145
+
125
146
  # Nothing is written before migration 20261123000000 has run.
126
147
  def authenticated_at_attributes(authenticated_at)
127
148
  return {} if authenticated_at.nil? || !StandardId::StepUp.session_column?
@@ -13,6 +13,7 @@ module StandardId
13
13
  @account = authenticate_account(params[:username], params[:password])
14
14
 
15
15
  if @account.blank?
16
+ emit_password_validation_failed if @credential
16
17
  emit_authentication_failed
17
18
  raise StandardId::InvalidGrantError, "Invalid username or password"
18
19
  end
@@ -49,6 +50,17 @@ module StandardId
49
50
  )
50
51
  end
51
52
 
53
+ # A credential exists for the username and the password did not match it.
54
+ def emit_password_validation_failed
55
+ StandardId::Events.publish(
56
+ StandardId::Events::PASSWORD_VALIDATION_FAILED,
57
+ account_lookup: params[:username],
58
+ account: @credential.credential&.account,
59
+ credential_id: @credential.id,
60
+ error_code: "invalid_password"
61
+ )
62
+ end
63
+
52
64
  def unverified_identifier_refused?
53
65
  return false unless StandardId.config.oauth.password_grant_requires_verified_identifier
54
66
 
@@ -20,6 +20,10 @@ module StandardId
20
20
  StandardId::RefreshToken.transaction do
21
21
  rotate_current_refresh_token!
22
22
  response = generate_token_response
23
+ # Inside the rotation transaction, as OAUTH_TOKEN_ISSUED is: a
24
+ # subscriber that raises rolls the rotation back and the presented
25
+ # token stays usable.
26
+ emit_token_refreshed
23
27
  end
24
28
 
25
29
  # If rotate detected a concurrent reuse (rows==0), the transaction
@@ -361,6 +365,21 @@ module StandardId
361
365
  )
362
366
  end
363
367
 
368
+ # Ids only: never the refresh token, its jti or the access token.
369
+ def emit_token_refreshed
370
+ StandardId::Events.publish(
371
+ StandardId::Events::OAUTH_TOKEN_REFRESHED,
372
+ client_id: client_id,
373
+ account: token_account,
374
+ account_id: subject_id,
375
+ session_id: refresh_token_session_id,
376
+ previous_refresh_token_id: @current_refresh_token_record&.id,
377
+ refresh_token_id: @issued_refresh_token&.id,
378
+ scope: token_scope,
379
+ graced: @served_from_graced_successor == true
380
+ )
381
+ end
382
+
364
383
  def emit_reuse_detected_event
365
384
  StandardId::Events.publish(
366
385
  StandardId::Events::OAUTH_REFRESH_TOKEN_REUSE_DETECTED,
@@ -19,11 +19,20 @@ module StandardId
19
19
  raise StandardId::InvalidRequestError, "#{connection} sign-in requires the web login flow (PKCE)"
20
20
  end
21
21
 
22
- provider.authorization_url(
22
+ callback_url = "#{params[:base_url]}/api/oauth/callback/#{connection}"
23
+ url = provider.authorization_url(
23
24
  state: encode_state_with_original_params,
24
- redirect_uri: "#{params[:base_url]}/api/oauth/callback/#{connection}",
25
+ redirect_uri: callback_url,
25
26
  scope: provider.default_scope
26
27
  )
28
+ StandardId::Events.publish(
29
+ StandardId::Events::SOCIAL_AUTH_STARTED,
30
+ provider: provider.provider_name,
31
+ flow: "oauth_authorize",
32
+ client_id: params[:client_id],
33
+ redirect_uri: callback_url
34
+ )
35
+ url
27
36
  rescue StandardId::ProviderRegistry::ProviderNotFoundError => e
28
37
  raise StandardId::InvalidRequestError, e.message
29
38
  end
@@ -1,3 +1,3 @@
1
1
  module StandardId
2
- VERSION = "0.64.1"
2
+ VERSION = "0.66.0"
3
3
  end
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.64.1
4
+ version: 0.66.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rarebit One