standard_id 0.59.0 → 0.61.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 +4 -4
- data/CHANGELOG.md +110 -0
- data/README.md +121 -8
- data/app/controllers/concerns/standard_id/social_authentication.rb +5 -4
- data/app/controllers/concerns/standard_id/web_authentication.rb +2 -0
- data/app/forms/standard_id/web/reset_password_confirm_form.rb +2 -1
- data/app/mailers/standard_id/account_notice_mailer.rb +11 -0
- data/app/models/standard_id/authorization_code.rb +6 -3
- data/app/models/standard_id/client_application.rb +7 -6
- data/app/models/standard_id/code_challenge.rb +69 -1
- data/app/models/standard_id/password_credential.rb +141 -0
- data/app/models/standard_id/session.rb +22 -12
- data/app/views/standard_id/account_notice_mailer/password_changed.html.erb +22 -0
- data/app/views/standard_id/account_notice_mailer/password_changed.text.erb +10 -0
- data/config/locales/en.yml +7 -0
- data/db/migrate/20261122000000_add_code_digest_to_standard_id_code_challenges.rb +24 -0
- data/lib/generators/standard_id/install/templates/standard_id_reference.rb +20 -0
- data/lib/standard_id/config/callable_validator.rb +26 -3
- data/lib/standard_id/config/schema.rb +56 -0
- data/lib/standard_id/email_password/authentication.rb +8 -2
- data/lib/standard_id/email_password/password_reset.rb +2 -1
- data/lib/standard_id/email_password/verification.rb +5 -1
- data/lib/standard_id/engine.rb +1 -0
- data/lib/standard_id/error_reporting.rb +38 -0
- data/lib/standard_id/events/definitions.rb +5 -0
- data/lib/standard_id/events/subscribers/password_changed_notice_subscriber.rb +42 -0
- data/lib/standard_id/events.rb +47 -0
- data/lib/standard_id/health_contributions.rb +27 -0
- data/lib/standard_id/http_client.rb +39 -6
- data/lib/standard_id/keyed_digest.rb +65 -0
- data/lib/standard_id/oauth/password_flow.rb +1 -0
- data/lib/standard_id/passwordless/verification_service.rb +9 -7
- data/lib/standard_id/testing/otp_helpers.rb +58 -0
- data/lib/standard_id/testing.rb +1 -0
- data/lib/standard_id/version.rb +1 -1
- data/lib/standard_id.rb +4 -0
- metadata +11 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: c5b800c9bdd221e81804f561bee356990391ca705f62412542deb424d00fd0e9
|
|
4
|
+
data.tar.gz: deff24e781f7147bca4d0096309f1bcbc37aa6d46295e6bdeff0d47d40805dca
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: c4fb45b06cfb55d73e765443943a18a8237f71fdb1093e152870f041c922d4e994bd9d3ff5c4015ada599a3552da9aca829bd7c5ca0fb5bc608e710a92615d7b
|
|
7
|
+
data.tar.gz: 779383c04ce9b1d3548399fae80c08f77ed3f470d4bd9efe2b248cff0455aeb9812353b46a74f859e5e674d7e7264bd36f40b86f340696226b0979f0f1194f98
|
data/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,116 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.61.0] - 2026-11-23
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **standard_health contributions.** StandardId registers an `ActiveSupport.on_load(:standard_health)`
|
|
15
|
+
hook that offers `StandardId::Checks::Migrations` as the non-critical `standard_id_migrations`
|
|
16
|
+
default check and declares two env vars under `standard_id`: `APP_ENVIRONMENT` (recommended;
|
|
17
|
+
it decides StandardId's production-only guards) and `STANDARD_ID_BYPASS_CODE` (forbidden in
|
|
18
|
+
production). There is no dependency on standard_health: without a standard_health that runs the
|
|
19
|
+
hook, nothing happens. Apps that already `register_check :standard_id_migrations` by hand are
|
|
20
|
+
unaffected (`register_default_checks` skips a registered name); opt out with
|
|
21
|
+
`c.register_default_checks standard_id_migrations: false`.
|
|
22
|
+
- **`config.network_wrapper`**, a callable `->(provider:, &block)` that wraps every outbound
|
|
23
|
+
connection `StandardId::HttpClient` makes (social token, userinfo and JWKS calls), e.g. in a
|
|
24
|
+
circuit breaker: `->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }`. `nil`
|
|
25
|
+
(default) runs the request directly. `HttpClient.post_form`, `.get_with_bearer` and the private
|
|
26
|
+
`start_connection` that plugins call for a JWKS take an optional `provider:` keyword (default
|
|
27
|
+
`:standard_id`), so existing callers keep working, including those that pass
|
|
28
|
+
`post_form`'s form as bare keywords (`post_form(url, id_token: token)`). The boot-time callable check rejects a
|
|
29
|
+
wrapper with an unknown keyword, a positional argument, or (for a lambda) no `&block`.
|
|
30
|
+
- **`StandardId::Events.auditable`**, the frozen list of event patterns worth an audit row, for
|
|
31
|
+
`StandardId::Events.auditable.each { |pattern| config.subscribe_to(pattern) }` in standard_audit
|
|
32
|
+
(one pattern per call, which every standard_audit version accepts). It keeps what the apps
|
|
33
|
+
subscribe to today (authentication, account, social and passwordless events; session created,
|
|
34
|
+
revoked and expired) and adds the password and client-secret lifecycle, refresh-token reuse,
|
|
35
|
+
token revocation, audience mismatches and OAuth client registration changes.
|
|
36
|
+
- **`config.error_reporter`**, an optional callable `(error, context)` for the errors StandardId
|
|
37
|
+
handles and carries on from (an event subscriber that raised after its change committed).
|
|
38
|
+
`context` carries `source: "standard_id"`, `handled: true` and what failed (`event:` or
|
|
39
|
+
`action:`). `nil` (default) keeps `Rails.error.report(error, handled: true, source:
|
|
40
|
+
"standard_id")`. All four report sites go through the new `StandardId::ErrorReporting.report`.
|
|
41
|
+
A reporter that raises is logged and the error falls back to that default report, so the flow
|
|
42
|
+
it was reporting from still carries on.
|
|
43
|
+
|
|
44
|
+
## [0.60.0] - 2026-11-22
|
|
45
|
+
|
|
46
|
+
### Security
|
|
47
|
+
|
|
48
|
+
- **One-time codes are stored as an HMAC, not in plaintext.** `standard_id_code_challenges.code`
|
|
49
|
+
held every passwordless and `StandardId::Otp` code, so anyone who could read the table (a
|
|
50
|
+
replica, a backup, a SQL console, audit rows that serialised the record) could sign in with any
|
|
51
|
+
active code. New challenges store only `code_digest`, an HMAC-SHA256 of the code keyed on
|
|
52
|
+
`secret_key_base` (a plain SHA256 of a 6-digit code is reversed by hashing a million
|
|
53
|
+
candidates), and `VerificationService` compares it in constant time; a request with no
|
|
54
|
+
challenge runs the same comparison, so timing still doesn't reveal one. **Install and run the
|
|
55
|
+
new migration** `20261122000000_add_code_digest_to_standard_id_code_challenges`
|
|
56
|
+
(`bin/rails standard_id:install:migrations && bin/rails db:migrate`), which adds the nullable
|
|
57
|
+
`code_digest` column and drops `NOT NULL` from `code`, both metadata-only on PostgreSQL. Until
|
|
58
|
+
it has run the gem keeps writing plaintext as before, so deploying the gem first breaks nothing.
|
|
59
|
+
Codes issued before the migration keep verifying against the plaintext column until they
|
|
60
|
+
expire (`passwordless.code_ttl`). **`CodeChallenge#code` now returns the raw code only on the
|
|
61
|
+
record the engine just created** (the one in `PASSWORDLESS_CODE_GENERATED`'s `code_challenge:`
|
|
62
|
+
and behind `Otp.issue(delivery: :manual).code`), so delivery subscribers that read
|
|
63
|
+
`event[:code_challenge].code` are unaffected; a challenge loaded from the database returns
|
|
64
|
+
`nil` (or a pre-migration row's plaintext). Host specs that read `CodeChallenge.last.code` must
|
|
65
|
+
capture the code as it is issued with the new `StandardId::Testing::OtpHelpers#capture_otp_code`
|
|
66
|
+
(or `#capture_otp_codes`); challenges created with `create!(code: "123456")` still verify with
|
|
67
|
+
that code. `CodeChallenge#serializable_hash` / `#as_json` leave out `code` and `code_digest`. A
|
|
68
|
+
later release drops the plaintext `code` column and its fallback. See `docs/MIGRATION_GUIDE.md`.
|
|
69
|
+
|
|
70
|
+
### Added
|
|
71
|
+
|
|
72
|
+
- **`config.previous_secret_key_bases` (default `[]`) for rotating `secret_key_base`.** Session
|
|
73
|
+
tokens, one-time code digests, authorization codes and RFC 7592 registration access tokens are
|
|
74
|
+
all keyed on `secret_key_base`, so rotating it signed everyone out. Secrets listed here are
|
|
75
|
+
still accepted on read while everything new is written under the current one.
|
|
76
|
+
`Session.by_token` checks every candidate in one indexed query (`lookup_hash IN (...)`), and with
|
|
77
|
+
nothing listed does the same work as before. Rails' own derived secrets (encrypted cookies,
|
|
78
|
+
message verifiers) need Rails' rotations as well, and HS256-signed JWTs are not covered: see the
|
|
79
|
+
README, "Rotating `secret_key_base`". The shared helper is `StandardId::KeyedDigest`.
|
|
80
|
+
|
|
81
|
+
- **Passwords are re-hashed on login when the bcrypt cost has changed (on by default).** Stored
|
|
82
|
+
digests were never upgraded, so raising `BCrypt::Engine.cost` only reached passwords set
|
|
83
|
+
afterwards. `StandardId::PasswordCredential#rehash_password` now re-hashes the password at the
|
|
84
|
+
cost `has_secure_password` uses when the stored digest was made at another one, after every
|
|
85
|
+
successful password login: `sign_in_account` (web), the OAuth password grant, and the email +
|
|
86
|
+
password API's `Authentication.call` and `Verification.verify!`. The write is a single `UPDATE`
|
|
87
|
+
conditional on the row still holding the digest the password was checked against, so a reset
|
|
88
|
+
that lands first wins and the rehash is skipped; where the login re-checks the digest under a
|
|
89
|
+
lock (the email + password API) the rehash runs after that check, inside the lock. A failed rehash is reported (`Rails.error`, `StandardId.logger`) and never fails the
|
|
90
|
+
login. Publishes the new `credential.password.rehashed` (`credential`, `account`,
|
|
91
|
+
`previous_cost`, `cost`) after commit. All digests are at the default cost today, so this is a
|
|
92
|
+
no-op until a host raises it. When it does, each user's first login afterwards replaces their
|
|
93
|
+
digest, which is the fingerprint of the `:remember_me` and `:password_reset` tokens: their
|
|
94
|
+
remember-me cookies on other browsers stop working and unused reset links are voided (the
|
|
95
|
+
login's own remember-me cookie is minted after the rehash). Turn it off with
|
|
96
|
+
`c.password.rehash_on_login = false`.
|
|
97
|
+
|
|
98
|
+
- **Opt-in "your password was changed" email.** Set `c.password.changed_notice_delivery =
|
|
99
|
+
:built_in` (default `:custom`: the engine sends nothing) to have
|
|
100
|
+
`StandardId::AccountNoticeMailer#password_changed` email the credential's e-mail identifier
|
|
101
|
+
whenever its password is changed or reset, telling the owner what to do if it wasn't them. Copy is
|
|
102
|
+
under `standard_id.account_notice_mailer.password_changed.*`. Delivered by the new
|
|
103
|
+
`Events::Subscribers::PasswordChangedNoticeSubscriber` on `credential.password.changed`. Off by
|
|
104
|
+
default so upgrading sends no new mail. A host that already sends its own notice from a
|
|
105
|
+
`credential.password.reset_completed` subscriber should leave it off, or the owner gets two.
|
|
106
|
+
|
|
107
|
+
### Fixed
|
|
108
|
+
|
|
109
|
+
- **`credential.password.changed` is now published.** It was defined and documented but nothing
|
|
110
|
+
published it. `StandardId::PasswordCredential` now publishes it after commit whenever an update
|
|
111
|
+
assigns a new password through `password=`. That includes both reset flows, which set
|
|
112
|
+
`reason: :password_reset`, and host code (`reason: :changed`). Writing `password_digest`
|
|
113
|
+
directly, as a re-hash of the same password does, does not publish it. The check runs at
|
|
114
|
+
commit against the digest in the row, so a password change that survives a rolled-back
|
|
115
|
+
savepoint, or a rolled-back save that is retried, still publishes once it commits. The payload
|
|
116
|
+
carries `credential_id` explicitly, so the built-in notice still finds its recipient under
|
|
117
|
+
`events.publish_records = false`. The documented `changed_by` payload field, which was never
|
|
118
|
+
sent, is replaced by `reason`. A subscriber that raises is reported and does not fail the save.
|
|
119
|
+
|
|
10
120
|
## [0.59.0] - 2026-11-03
|
|
11
121
|
|
|
12
122
|
### Added
|
data/README.md
CHANGED
|
@@ -171,6 +171,12 @@ end
|
|
|
171
171
|
|
|
172
172
|
`default_token_lifetime` is applied to every OAuth grant unless you override it in `oauth.token_lifetimes`. Keys map to OAuth grant types (for example `:password`, `:client_credentials`, `:refresh_token`) and should return durations in seconds. Non-token endpoint flows such as the implicit flow can be customized with their symbol key (e.g. `:implicit`). Refresh tokens can be tuned separately through `oauth.refresh_token_lifetime`.
|
|
173
173
|
|
|
174
|
+
### Raising the bcrypt cost
|
|
175
|
+
|
|
176
|
+
Password digests are made by `has_secure_password` at `BCrypt::Engine.cost` (bcrypt-ruby's default is 12). Raising it, e.g. `BCrypt::Engine.cost = 13` in an initializer, used to apply only to passwords set afterwards. Now every password login (web, OAuth password grant, email + password API) re-hashes the password at the current cost when the stored digest was made at another one, and publishes `credential.password.rehashed`. Until the cost changes this does nothing.
|
|
177
|
+
|
|
178
|
+
The digest is also the fingerprint of the remember-me cookie and the password-reset link, so the first login after a cost change signs that user out of remember-me on their other browsers and voids any reset link they have not used yet. The login itself, and a remember-me cookie it sets, are unaffected. The rewrite happens one user at a time as each signs in, never on deploy. Turn it off with `config.password.rehash_on_login = false`.
|
|
179
|
+
|
|
174
180
|
### OAuth Hardening Options
|
|
175
181
|
|
|
176
182
|
Two spec-conformance settings default to the historical (looser) behaviour so
|
|
@@ -621,6 +627,23 @@ gets `provider_tokens:` in the `social.before_account` / `before_mint` hooks.
|
|
|
621
627
|
Setting `config.events.publish_provider_tokens = true` restores `event[:tokens]`;
|
|
622
628
|
the subscriber that reads it then has to keep them out of audit rows and logs.
|
|
623
629
|
|
|
630
|
+
**Wrapping provider calls.** Every outbound request StandardId makes for a
|
|
631
|
+
provider (token exchange, userinfo, JWKS) goes through `StandardId::HttpClient`,
|
|
632
|
+
and `config.network_wrapper` wraps each one, given the provider's name. Use it
|
|
633
|
+
for a circuit breaker, so a provider outage fails fast instead of holding
|
|
634
|
+
request threads for the full timeout, or for a tracing span:
|
|
635
|
+
|
|
636
|
+
```ruby
|
|
637
|
+
c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }
|
|
638
|
+
```
|
|
639
|
+
|
|
640
|
+
It must call the block and return its result. A timeout or refused connection
|
|
641
|
+
raises inside the wrapper, and whatever the wrapper raises (an open circuit,
|
|
642
|
+
say) reaches the provider's caller as is. `provider` is the plugin's name
|
|
643
|
+
(`:google`, `:apple`, ...), or `:standard_id` for a plugin release that does not
|
|
644
|
+
pass one yet. A lambda must take the block as `&block`; the boot check rejects
|
|
645
|
+
one that doesn't, since it would silently skip the request.
|
|
646
|
+
|
|
624
647
|
### Inertia.js Integration
|
|
625
648
|
|
|
626
649
|
StandardId supports [Inertia.js](https://inertiajs.com/) for modern React, Vue, or Svelte frontends. When enabled, web controllers render Inertia components instead of ERB views.
|
|
@@ -836,7 +859,10 @@ parent's `default from:` does not apply to them.
|
|
|
836
859
|
Event payload includes:
|
|
837
860
|
- `channel` - `"email"` or `"sms"`
|
|
838
861
|
- `identifier` - The email address or phone number
|
|
839
|
-
- `code_challenge` - The code challenge object with `.code` method
|
|
862
|
+
- `code_challenge` - The code challenge object with `.code` method. The raw code exists only on
|
|
863
|
+
this in-memory record: the database stores an HMAC of it (`code_digest`), so read `.code` in the
|
|
864
|
+
subscriber and pass the string on; a challenge reloaded later (e.g. in a job that received the
|
|
865
|
+
record) returns `nil`
|
|
840
866
|
- `expires_at` - When the code expires
|
|
841
867
|
- `realm` - The OTP realm (`"authentication"` for sign-in)
|
|
842
868
|
- `skip_sender` - `true` for `Otp.issue(delivery: :manual)`; don't deliver
|
|
@@ -844,6 +870,18 @@ Event payload includes:
|
|
|
844
870
|
|
|
845
871
|
> **Note**: `passwordless_email_sender` / `passwordless_sms_sender` were removed in 0.43; see the [Migration Guide](docs/MIGRATION_GUIDE.md).
|
|
846
872
|
|
|
873
|
+
### Password changed notice
|
|
874
|
+
|
|
875
|
+
When a password is changed, StandardId publishes `credential.password.changed`. That covers both reset flows (web and the email + password API, with `reason: :password_reset`) and any code of yours that assigns a new password to a `StandardId::PasswordCredential` (`reason: :changed`). It is not published when only the digest is rewritten, such as a re-hash of the same password. The event waits for the change to commit.
|
|
876
|
+
|
|
877
|
+
By default the engine sends no email for it. To have the engine email the account's address (its e-mail identifier) saying the password was changed, and what to do if it wasn't them, set:
|
|
878
|
+
|
|
879
|
+
```ruby
|
|
880
|
+
config.password.changed_notice_delivery = :built_in # default :custom (send nothing)
|
|
881
|
+
```
|
|
882
|
+
|
|
883
|
+
The message is `StandardId::AccountNoticeMailer#password_changed`, sent with `deliver_later` from `c.passwordless.mailer_from`. Its copy lives under `standard_id.account_notice_mailer.password_changed.*`; override those keys or the templates in `app/views/standard_id/account_notice_mailer/`. If you already send your own notice from a `credential.password.reset_completed` subscriber, leave this at `:custom`, or drop yours, so owners don't get two emails.
|
|
884
|
+
|
|
847
885
|
### Starting a passwordless login from your own controller
|
|
848
886
|
|
|
849
887
|
To send the code from your own controller (a sign-up form, an invite page) and
|
|
@@ -1016,7 +1054,8 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
|
|
|
1016
1054
|
| Credential | `credential.password.created` | `credential`, `account` | After a password credential is created |
|
|
1017
1055
|
| | `credential.password.reset_initiated` | `credential`, `account`, `reset_token_expires_at` | After a password reset is initiated |
|
|
1018
1056
|
| | `credential.password.reset_completed` | `credential`, `account` | After a password reset is confirmed |
|
|
1019
|
-
| | `credential.password.changed` | `credential`, `account`, `
|
|
1057
|
+
| | `credential.password.changed` | `credential`, `credential_id` (sent even with `events.publish_records = false`), `account`, `reason` (`:password_reset` / `:changed`) | After a new password is committed: by a reset, or by host code assigning `password` (never for a re-hash of the same password). Drives `password.changed_notice_delivery` |
|
|
1058
|
+
| | `credential.password.rehashed` | `credential`, `account`, `previous_cost`, `cost` | After a login re-hashed the password at the current bcrypt cost (`password.rehash_on_login`); the password is unchanged |
|
|
1020
1059
|
| | `credential.client_secret.created` | `credential`, `client_id` | After a client secret is created |
|
|
1021
1060
|
| | `credential.client_secret.rotated` | `credential`, `client_id`, `old_secret_revoked_at` | After a client secret rotation |
|
|
1022
1061
|
|
|
@@ -1050,6 +1089,21 @@ StandardId::Events.subscribe(/social/) do |event|
|
|
|
1050
1089
|
end
|
|
1051
1090
|
```
|
|
1052
1091
|
|
|
1092
|
+
#### When a subscriber raises after the change has committed
|
|
1093
|
+
|
|
1094
|
+
A subscriber to an event that reports something already written (a completed
|
|
1095
|
+
password reset, a password rehash, a social link) cannot undo it, so StandardId
|
|
1096
|
+
logs its error and reports it instead of failing the request. Reports go to
|
|
1097
|
+
`Rails.error.report(error, handled: true, source: "standard_id")` unless you set
|
|
1098
|
+
`config.error_reporter`, a callable taking `(error, context)`; `context` carries
|
|
1099
|
+
`source:` and `handled:` plus what failed (`event:` or `action:`). If your
|
|
1100
|
+
reporter raises, StandardId logs that and falls back to the `Rails.error.report`
|
|
1101
|
+
call above, so the request still completes:
|
|
1102
|
+
|
|
1103
|
+
```ruby
|
|
1104
|
+
c.error_reporter = ->(error, context) { Sentry.capture_exception(error, extra: context) }
|
|
1105
|
+
```
|
|
1106
|
+
|
|
1053
1107
|
### Audit Logging
|
|
1054
1108
|
|
|
1055
1109
|
For production audit trails, use the [standard_audit](https://github.com/rarebit-one/standard_audit) gem. StandardId and StandardAudit have zero direct references to each other — the host application wires them together.
|
|
@@ -1072,12 +1126,12 @@ rails db:migrate
|
|
|
1072
1126
|
|
|
1073
1127
|
#### Wiring StandardId events to StandardAudit
|
|
1074
1128
|
|
|
1075
|
-
Configure StandardAudit to subscribe to StandardId
|
|
1129
|
+
Configure StandardAudit to subscribe to the events StandardId marks as worth auditing, and map its payload conventions:
|
|
1076
1130
|
|
|
1077
1131
|
```ruby
|
|
1078
1132
|
# config/initializers/standard_audit.rb
|
|
1079
1133
|
StandardAudit.configure do |config|
|
|
1080
|
-
config.subscribe_to
|
|
1134
|
+
StandardId::Events.auditable.each { |pattern| config.subscribe_to(pattern) }
|
|
1081
1135
|
|
|
1082
1136
|
# StandardId uses :account and :current_account rather than :actor/:target.
|
|
1083
1137
|
# Map them so StandardAudit extracts the right records.
|
|
@@ -1096,7 +1150,9 @@ StandardAudit.configure do |config|
|
|
|
1096
1150
|
end
|
|
1097
1151
|
```
|
|
1098
1152
|
|
|
1099
|
-
That's it. Every StandardId
|
|
1153
|
+
That's it. Every security-relevant StandardId event will now be persisted as an audit log entry. No changes are needed inside StandardId itself.
|
|
1154
|
+
|
|
1155
|
+
`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\./`.
|
|
1100
1156
|
|
|
1101
1157
|
#### Querying audit logs
|
|
1102
1158
|
|
|
@@ -1881,7 +1937,7 @@ StandardId creates the following tables:
|
|
|
1881
1937
|
- `standard_id_clients` - OAuth clients
|
|
1882
1938
|
- `standard_id_client_secret_credentials` - Client secrets
|
|
1883
1939
|
- `standard_id_password_credentials` - Password storage
|
|
1884
|
-
- `standard_id_code_challenges` - OTP codes for authentication and verification
|
|
1940
|
+
- `standard_id_code_challenges` - OTP codes for authentication and verification (stored as an HMAC digest)
|
|
1885
1941
|
|
|
1886
1942
|
## API Endpoints
|
|
1887
1943
|
|
|
@@ -1976,7 +2032,7 @@ module StandardId
|
|
|
1976
2032
|
rescue_to_oauth_error do
|
|
1977
2033
|
raise StandardId::InvalidRequestError, "Missing authorization code" if code.blank?
|
|
1978
2034
|
|
|
1979
|
-
response = HttpClient.post_form(TOKEN_ENDPOINT, { code:, redirect_uri:, ... })
|
|
2035
|
+
response = HttpClient.post_form(TOKEN_ENDPOINT, { code:, redirect_uri:, ... }, provider: :github)
|
|
1980
2036
|
parsed = JSON.parse(response.body)
|
|
1981
2037
|
build_response(fetch_profile(parsed["access_token"]), tokens: extract_tokens(parsed))
|
|
1982
2038
|
end
|
|
@@ -1987,6 +2043,8 @@ module StandardId
|
|
|
1987
2043
|
end
|
|
1988
2044
|
```
|
|
1989
2045
|
|
|
2046
|
+
Pass `provider:` to every `HttpClient` call so the host's `config.network_wrapper` can tell providers apart (see [Social Login Setup](#social-login-setup)). The keyword is new in the release after 0.60.0; a plugin that supports older standard_id releases should check for it, e.g. `HttpClient.method(:post_form).parameters.include?([:key, :provider])`, and leave it out when absent.
|
|
2047
|
+
|
|
1990
2048
|
**Required interface:** `provider_name`, `authorization_url`, `get_user_info`.
|
|
1991
2049
|
|
|
1992
2050
|
**Optional hooks** (all class methods, with safe defaults):
|
|
@@ -2148,6 +2206,27 @@ scoped login request instead. It replaces controller stubbing
|
|
|
2148
2206
|
(`stub_web_authentication`, `allow_any_instance_of(...).to receive(:current_user)`)
|
|
2149
2207
|
and per-app `/test/set-session` routes.
|
|
2150
2208
|
|
|
2209
|
+
### Reading one-time codes in specs
|
|
2210
|
+
|
|
2211
|
+
A `CodeChallenge` stores only an HMAC of its code, so `StandardId::CodeChallenge.last.code` is
|
|
2212
|
+
`nil`. Capture the code as it is issued instead:
|
|
2213
|
+
|
|
2214
|
+
```ruby
|
|
2215
|
+
RSpec.configure do |config|
|
|
2216
|
+
config.include StandardId::Testing::OtpHelpers, type: :request
|
|
2217
|
+
end
|
|
2218
|
+
|
|
2219
|
+
code = capture_otp_code(email) { post "/login", params: { login: { email: email } } }
|
|
2220
|
+
patch "/login_verify", params: { code: code }
|
|
2221
|
+
|
|
2222
|
+
codes = capture_otp_codes { ... } # every code issued in the block: identifier, channel, realm, code
|
|
2223
|
+
```
|
|
2224
|
+
|
|
2225
|
+
They read `PASSWORDLESS_CODE_GENERATED`, as a delivery subscriber does, so they see nothing when
|
|
2226
|
+
`c.events.publish_records = false`. A challenge you create yourself
|
|
2227
|
+
(`CodeChallenge.create!(code: "123456", ...)` or the `:standard_id_code_challenge` factory) still
|
|
2228
|
+
verifies with the code you gave it.
|
|
2229
|
+
|
|
2151
2230
|
### This gem's own suite
|
|
2152
2231
|
|
|
2153
2232
|
StandardId includes comprehensive test coverage:
|
|
@@ -2174,6 +2253,38 @@ bundle exec rspec spec/controllers/
|
|
|
2174
2253
|
requests that omit `code_challenge` for a PKCE-required client are
|
|
2175
2254
|
rejected with `invalid_request`.
|
|
2176
2255
|
- Rate limiting on authentication endpoints
|
|
2256
|
+
- Passwordless / OTP codes are stored as HMAC-SHA256 digests keyed on `secret_key_base`, never in
|
|
2257
|
+
plaintext (since migration `20261122000000`; see the Migration Guide)
|
|
2258
|
+
|
|
2259
|
+
### Rotating `secret_key_base`
|
|
2260
|
+
|
|
2261
|
+
Session tokens, passwordless codes, authorization codes and RFC 7592 registration access tokens are
|
|
2262
|
+
stored as digests keyed on `secret_key_base`, so changing it invalidates all of them: everyone is
|
|
2263
|
+
signed out. To rotate without that, list the old secret, newest first:
|
|
2264
|
+
|
|
2265
|
+
```ruby
|
|
2266
|
+
StandardId.configure do |c|
|
|
2267
|
+
c.previous_secret_key_bases = [Rails.application.credentials.old_secret_key_base]
|
|
2268
|
+
end
|
|
2269
|
+
```
|
|
2270
|
+
|
|
2271
|
+
Digests are then still looked up and verified under the old secret (one indexed query covers every
|
|
2272
|
+
candidate session lookup hash), while everything new is written under the current one
|
|
2273
|
+
(`StandardId::KeyedDigest`). Nothing is re-written in place, so keep the entry until the longest
|
|
2274
|
+
session lifetime you issue (`session.*_lifetime`, and the lifetime of any long-lived
|
|
2275
|
+
`ServiceSession`) has passed, then remove it.
|
|
2276
|
+
|
|
2277
|
+
This covers StandardId's own digests only. The rest of the app needs Rails' rotations too:
|
|
2278
|
+
|
|
2279
|
+
- **Cookies**, including the encrypted `session_token` cookie and the Rails session that carry the
|
|
2280
|
+
web session: `config.action_dispatch.cookies_rotations` (see the Rails security guide,
|
|
2281
|
+
"Rotating Encrypted and Signed Cookies Configurations").
|
|
2282
|
+
- **Message verifiers** (`generates_token_for`, so remember-me and password-reset tokens, and the
|
|
2283
|
+
signed passwordless OTP payload): `Rails.application.message_verifiers.rotate(secret_key_base:
|
|
2284
|
+
old)` in a `before_initialize` block.
|
|
2285
|
+
- **JWTs signed with HS256** (the default `oauth.signing_algorithm`) use `secret_key_base` directly
|
|
2286
|
+
and are not covered: access tokens fail until re-issued and HS256 refresh tokens stop refreshing.
|
|
2287
|
+
Use an asymmetric `oauth.signing_key` if you need to rotate without that.
|
|
2177
2288
|
|
|
2178
2289
|
## OTP Start Limits
|
|
2179
2290
|
|
|
@@ -2208,12 +2319,14 @@ address with a PostgreSQL advisory lock, so two concurrent starts cannot both is
|
|
|
2208
2319
|
|
|
2209
2320
|
- **At boot** (file-system only, no database): `config.missing_migrations` — `:warn` (default in development/test: logs and prints to stderr), `:raise` (fails boot with `StandardId::ConfigurationError`), or `:ignore` (default in every other environment — it never raises in production unless you opt in).
|
|
2210
2321
|
- **`StandardId::MigrationCheck.pending(check_database: true)`** returns every gem migration that is `:not_installed` or installed but `:not_run` (one `schema_migrations` read).
|
|
2211
|
-
- **Health check** — `StandardId::Checks::Migrations` is [standard_health](https://github.com/rarebit-one/standard_health)-compatible (duck-typed, no dependency).
|
|
2322
|
+
- **Health check** — `StandardId::Checks::Migrations` is [standard_health](https://github.com/rarebit-one/standard_health)-compatible (duck-typed, no dependency). With a standard_health that supports contributions, StandardId offers it through standard_health's load hook, so `c.register_default_checks` registers it, non-critical: a missing migration degrades `/health/ready` without failing it. Opt out with `c.register_default_checks standard_id_migrations: false`. With an older standard_health, register it yourself:
|
|
2212
2323
|
|
|
2213
2324
|
```ruby
|
|
2214
2325
|
c.register_check :standard_id_migrations, StandardId::Checks::Migrations, critical: false
|
|
2215
2326
|
```
|
|
2216
2327
|
|
|
2328
|
+
The same hook declares the env vars StandardId cares about for `/diagnostics/env`: `APP_ENVIRONMENT` (recommended; it decides StandardId's production-only guards) and `STANDARD_ID_BYPASS_CODE` (forbidden in production). An entry your app declares in its own `env_spec` wins. StandardId does not depend on standard_health; without it the hook never runs.
|
|
2329
|
+
|
|
2217
2330
|
Two cases are built in and documented in `StandardId::MigrationCheck`:
|
|
2218
2331
|
|
|
2219
2332
|
- **Superseded** (`SUPERSEDED_BY`): `20260414200000_add_target_created_at_index_to_code_challenges` counts as satisfied when `20260416180511` (whose partial, concurrently built index replaces it) is installed.
|
|
@@ -376,14 +376,15 @@ module StandardId
|
|
|
376
376
|
|
|
377
377
|
# SOCIAL_ACCOUNT_LINKED reports a link that has already committed, so it
|
|
378
378
|
# cannot refuse the login: a subscriber that raises here would fail the
|
|
379
|
-
# callback while the link stays. Its error is logged and reported
|
|
380
|
-
# Rails.error instead of
|
|
381
|
-
# run before anything is
|
|
379
|
+
# callback while the link stays. Its error is logged and reported
|
|
380
|
+
# (StandardId::ErrorReporting; Rails.error by default) instead of
|
|
381
|
+
# propagating. (Guards belong on the events that run before anything is
|
|
382
|
+
# written.)
|
|
382
383
|
def emit_committed_social_link(identifier, provider)
|
|
383
384
|
emit_social_account_linked(identifier.account, provider, identifier)
|
|
384
385
|
rescue StandardError => e
|
|
385
386
|
Rails.logger&.error("[StandardId] SOCIAL_ACCOUNT_LINKED subscriber raised after the link committed: #{e.class}: #{e.message}")
|
|
386
|
-
|
|
387
|
+
StandardId::ErrorReporting.report(e, event: StandardId::Events.namespaced_event_name(StandardId::Events::SOCIAL_ACCOUNT_LINKED))
|
|
387
388
|
end
|
|
388
389
|
|
|
389
390
|
# A social login that recorded a link (and maybe created an account) and
|
|
@@ -160,6 +160,8 @@ module StandardId
|
|
|
160
160
|
auth_method: :password,
|
|
161
161
|
flow: :web_password
|
|
162
162
|
)
|
|
163
|
+
# Before the remember-me cookie, whose token fingerprints the digest.
|
|
164
|
+
password_credential.rehash_password(password)
|
|
163
165
|
session_manager.set_remember_cookie(password_credential) if remember_me
|
|
164
166
|
|
|
165
167
|
StandardId::Events.publish(
|
|
@@ -31,6 +31,7 @@ module StandardId
|
|
|
31
31
|
# reset back, but one that reads the rows must do so after commit
|
|
32
32
|
# (e.g. from a job, which Rails enqueues after commit).
|
|
33
33
|
ActiveRecord::Base.transaction do
|
|
34
|
+
@password_credential.password_change_reason = :password_reset
|
|
34
35
|
@password_credential.update!(password: password, password_confirmation: password_confirmation)
|
|
35
36
|
revoke_access!(account)
|
|
36
37
|
end
|
|
@@ -55,7 +56,7 @@ module StandardId
|
|
|
55
56
|
account: account
|
|
56
57
|
)
|
|
57
58
|
rescue StandardError => e
|
|
58
|
-
|
|
59
|
+
StandardId::ErrorReporting.report(e, event: StandardId::Events.namespaced_event_name(StandardId::Events::CREDENTIAL_PASSWORD_RESET_COMPLETED))
|
|
59
60
|
logger = StandardId.logger
|
|
60
61
|
return unless logger.respond_to?(:error)
|
|
61
62
|
|
|
@@ -6,6 +6,10 @@ module StandardId
|
|
|
6
6
|
# an account, while `c.email_password.reveal_existing_accounts` is false
|
|
7
7
|
# (the API then answers as if the sign-up went ahead). The owner learns
|
|
8
8
|
# about it and how to get in; the requester learns nothing.
|
|
9
|
+
# * #password_changed: the account's password was changed or reset, while
|
|
10
|
+
# `c.password.changed_notice_delivery` is :built_in
|
|
11
|
+
# (Events::Subscribers::PasswordChangedNoticeSubscriber). The owner learns
|
|
12
|
+
# of a change they did not make.
|
|
9
13
|
#
|
|
10
14
|
# Copy lives under `standard_id.account_notice_mailer.<action>.*` in
|
|
11
15
|
# config/locales/en.yml; override any key in the host's locale files, or the
|
|
@@ -22,6 +26,13 @@ module StandardId
|
|
|
22
26
|
mail(to: @email, from: StandardId.config.passwordless.mailer_from, subject: notice_copy(:subject))
|
|
23
27
|
end
|
|
24
28
|
|
|
29
|
+
# @param email [String]
|
|
30
|
+
def password_changed
|
|
31
|
+
@email = params[:email]
|
|
32
|
+
|
|
33
|
+
mail(to: @email, from: StandardId.config.passwordless.mailer_from, subject: notice_copy(:subject))
|
|
34
|
+
end
|
|
35
|
+
|
|
25
36
|
# Copy for the current action, falling back to the gem's English (see
|
|
26
37
|
# PasswordlessMailer#otp_copy).
|
|
27
38
|
def notice_copy(key, default: nil, **options)
|
|
@@ -62,12 +62,15 @@ module StandardId
|
|
|
62
62
|
|
|
63
63
|
# Preloads :account — every caller (the token exchange) reads it, and hosts
|
|
64
64
|
# running strict_loading_by_default would otherwise raise on the lazy read.
|
|
65
|
+
# Matches the hash under the current secret or any of
|
|
66
|
+
# `config.previous_secret_key_bases`, in one indexed query.
|
|
65
67
|
def self.lookup(plaintext_code)
|
|
66
|
-
|
|
68
|
+
hashes = StandardId::KeyedDigest.candidates { |secret| hash_for(plaintext_code, secret:) }
|
|
69
|
+
includes(:account).find_by(code_hash: hashes)
|
|
67
70
|
end
|
|
68
71
|
|
|
69
|
-
def self.hash_for(plaintext_code)
|
|
70
|
-
Digest::SHA256.hexdigest("#{plaintext_code}:#{
|
|
72
|
+
def self.hash_for(plaintext_code, secret: StandardId::KeyedDigest.current_secret)
|
|
73
|
+
Digest::SHA256.hexdigest("#{plaintext_code}:#{secret}")
|
|
71
74
|
end
|
|
72
75
|
|
|
73
76
|
def self.default_ttl
|
|
@@ -204,21 +204,22 @@ module StandardId
|
|
|
204
204
|
|
|
205
205
|
# Keyed with secret_key_base like AuthorizationCode.hash_for, so a leaked
|
|
206
206
|
# table does not yield usable management credentials.
|
|
207
|
-
def self.digest_registration_access_token(token)
|
|
208
|
-
Digest::SHA256.hexdigest("#{token}:#{
|
|
207
|
+
def self.digest_registration_access_token(token, secret: StandardId::KeyedDigest.current_secret)
|
|
208
|
+
Digest::SHA256.hexdigest("#{token}:#{secret}")
|
|
209
209
|
end
|
|
210
210
|
|
|
211
211
|
def dynamically_registered?
|
|
212
212
|
self.class.registration_management_column? && registration_access_token_digest.present?
|
|
213
213
|
end
|
|
214
214
|
|
|
215
|
-
# Constant-time check of an RFC 7592 registration access token
|
|
215
|
+
# Constant-time check of an RFC 7592 registration access token, under the
|
|
216
|
+
# current secret or any of `config.previous_secret_key_bases`.
|
|
216
217
|
def authenticate_registration_access_token(token)
|
|
217
218
|
return false unless dynamically_registered? && token.present?
|
|
218
219
|
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
220
|
+
StandardId::KeyedDigest.secure_match?(
|
|
221
|
+
registration_access_token_digest,
|
|
222
|
+
StandardId::KeyedDigest.candidates { |secret| self.class.digest_registration_access_token(token.to_s, secret:) }
|
|
222
223
|
)
|
|
223
224
|
end
|
|
224
225
|
|
|
@@ -17,13 +17,81 @@ module StandardId
|
|
|
17
17
|
validates :realm, presence: true
|
|
18
18
|
validates :channel, presence: true, inclusion: { in: CHANNELS }
|
|
19
19
|
validates :target, presence: true
|
|
20
|
-
|
|
20
|
+
# On create only: a challenge read back from the database has no raw code
|
|
21
|
+
# (see #code), and an update (#use!, the attempt counter) must not need one.
|
|
22
|
+
validates :code, presence: true, on: :create
|
|
21
23
|
validates :expires_at, presence: true
|
|
22
24
|
|
|
23
25
|
scope :active, -> { where(used_at: nil).where("expires_at > ?", Time.current) }
|
|
24
26
|
scope :expired, -> { where("expires_at <= ?", Time.current) }
|
|
25
27
|
scope :used, -> { where.not(used_at: nil) }
|
|
26
28
|
|
|
29
|
+
# HMAC-SHA256 of a one-time code under `secret_key_base`, which is all a
|
|
30
|
+
# challenge stores of it (migration 20261122000000). It must be keyed: a
|
|
31
|
+
# plain SHA256 of a 6-digit code is reversed by hashing all million
|
|
32
|
+
# candidates. The versioned prefix domain-separates it from every other
|
|
33
|
+
# digest keyed on the same secret.
|
|
34
|
+
CODE_DIGEST_PREFIX = "standard_id.code_challenge.code_digest.v1:".freeze
|
|
35
|
+
|
|
36
|
+
def self.digest_code(code, secret: StandardId::KeyedDigest.current_secret)
|
|
37
|
+
StandardId::KeyedDigest.hmac_hexdigest("#{CODE_DIGEST_PREFIX}#{code}", secret:)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Whether the host has run migration 20261122000000. Until then challenges
|
|
41
|
+
# keep storing the plaintext code, exactly as before it existed.
|
|
42
|
+
def self.code_digest_column?
|
|
43
|
+
column_names.include?("code_digest")
|
|
44
|
+
rescue ActiveRecord::ActiveRecordError
|
|
45
|
+
false
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# The raw code, on the instance that was created with it, and only there:
|
|
49
|
+
# it reaches delivery (PASSWORDLESS_CODE_GENERATED's `code_challenge:`, the
|
|
50
|
+
# built-in mailer, `Otp.issue(delivery: :manual).code`) on that in-memory
|
|
51
|
+
# record. A challenge loaded from the database returns nil, or, for one
|
|
52
|
+
# issued before the digest migration, the legacy plaintext column.
|
|
53
|
+
def code
|
|
54
|
+
@code || read_attribute(:code)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def code=(value)
|
|
58
|
+
@code = value&.to_s
|
|
59
|
+
|
|
60
|
+
if self.class.code_digest_column?
|
|
61
|
+
self.code_digest = @code.presence && self.class.digest_code(@code)
|
|
62
|
+
else
|
|
63
|
+
super(@code)
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Constant-time check of a submitted code. Accepts a digest written under
|
|
68
|
+
# the current secret or any of `config.previous_secret_key_bases`; falls
|
|
69
|
+
# back to the plaintext column only for a row that has no digest (issued
|
|
70
|
+
# before the migration, or while it is pending).
|
|
71
|
+
def code_matches?(candidate)
|
|
72
|
+
candidate = candidate.to_s
|
|
73
|
+
return false if candidate.empty?
|
|
74
|
+
|
|
75
|
+
if has_attribute?(:code_digest) && code_digest.present?
|
|
76
|
+
StandardId::KeyedDigest.secure_match?(
|
|
77
|
+
code_digest,
|
|
78
|
+
StandardId::KeyedDigest.candidates { |secret| self.class.digest_code(candidate, secret:) }
|
|
79
|
+
)
|
|
80
|
+
else
|
|
81
|
+
legacy = read_attribute(:code).to_s
|
|
82
|
+
legacy.present? && ActiveSupport::SecurityUtils.secure_compare(legacy, candidate)
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# Never serialise the code or its digest: event subscribers that write the
|
|
87
|
+
# whole record (audit rows, logs) would otherwise store the raw code of a
|
|
88
|
+
# just-issued challenge, which is exactly what the digest exists to avoid.
|
|
89
|
+
def serializable_hash(options = nil)
|
|
90
|
+
options = options&.dup || {}
|
|
91
|
+
options[:except] = Array(options[:except]).map(&:to_s) | %w[code code_digest]
|
|
92
|
+
super(options)
|
|
93
|
+
end
|
|
94
|
+
|
|
27
95
|
def expired?
|
|
28
96
|
expires_at <= Time.current
|
|
29
97
|
end
|