standard_id 0.59.0 → 0.60.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 (31) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +76 -0
  3. data/README.md +78 -3
  4. data/app/controllers/concerns/standard_id/web_authentication.rb +2 -0
  5. data/app/forms/standard_id/web/reset_password_confirm_form.rb +1 -0
  6. data/app/mailers/standard_id/account_notice_mailer.rb +11 -0
  7. data/app/models/standard_id/authorization_code.rb +6 -3
  8. data/app/models/standard_id/client_application.rb +7 -6
  9. data/app/models/standard_id/code_challenge.rb +69 -1
  10. data/app/models/standard_id/password_credential.rb +141 -0
  11. data/app/models/standard_id/session.rb +22 -12
  12. data/app/views/standard_id/account_notice_mailer/password_changed.html.erb +22 -0
  13. data/app/views/standard_id/account_notice_mailer/password_changed.text.erb +10 -0
  14. data/config/locales/en.yml +7 -0
  15. data/db/migrate/20261122000000_add_code_digest_to_standard_id_code_challenges.rb +24 -0
  16. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +9 -0
  17. data/lib/standard_id/config/schema.rb +30 -0
  18. data/lib/standard_id/email_password/authentication.rb +8 -2
  19. data/lib/standard_id/email_password/password_reset.rb +1 -0
  20. data/lib/standard_id/email_password/verification.rb +5 -1
  21. data/lib/standard_id/engine.rb +1 -0
  22. data/lib/standard_id/events/definitions.rb +5 -0
  23. data/lib/standard_id/events/subscribers/password_changed_notice_subscriber.rb +42 -0
  24. data/lib/standard_id/keyed_digest.rb +65 -0
  25. data/lib/standard_id/oauth/password_flow.rb +1 -0
  26. data/lib/standard_id/passwordless/verification_service.rb +9 -7
  27. data/lib/standard_id/testing/otp_helpers.rb +58 -0
  28. data/lib/standard_id/testing.rb +1 -0
  29. data/lib/standard_id/version.rb +1 -1
  30. data/lib/standard_id.rb +2 -0
  31. metadata +9 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 79ed9cae0d273dccba684296744618a0002f84435359d00b56e3f5684b51d44f
4
- data.tar.gz: 2635c31d2ee0eef5a63555ced32491b884fe67b47fc9e494c6bb55b08dfd753d
3
+ metadata.gz: 6b16c75edf932c75abfde26acde06652cea845e13d60b5ec943894355eb89327
4
+ data.tar.gz: 5ccd8c3889f612353415998ba063d2e10a2a0450ba099f28e7f863040ccf57e8
5
5
  SHA512:
6
- metadata.gz: a9b37adf87a371f1b370462e902fdbac4405195ad17b061936b02275e6419a289e38d91ce1411fe30b2004d269959d2d90da92e20349d1f2a7f0b3b2940cf784
7
- data.tar.gz: fbf2478a0c4834ae47f877e7d1ebd3648a394c8a1739ce3917b54283a6bcab662f1cfb7c1b05652ff42f4f7bf06ba4c6b4618ef9317958309c2e5ddb67717d1c
6
+ metadata.gz: f2a159cbe0415275e12c90ca0b43d241f7010d4ee3c7bb0d5ad817b9668a6104f5d829fc41db76fb07deadb4164a9d3dc726957305d28053b848fa26c9198bb2
7
+ data.tar.gz: 1f35e1824c63d566905576992b00cba1f62377874d069286a4353bb4f8513416809662d68e0cbcf5cc41ef61e06b5744c6680827cd6132a9f4d406a3a053c4a2
data/CHANGELOG.md CHANGED
@@ -7,6 +7,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.60.0] - 2026-11-22
11
+
12
+ ### Security
13
+
14
+ - **One-time codes are stored as an HMAC, not in plaintext.** `standard_id_code_challenges.code`
15
+ held every passwordless and `StandardId::Otp` code, so anyone who could read the table (a
16
+ replica, a backup, a SQL console, audit rows that serialised the record) could sign in with any
17
+ active code. New challenges store only `code_digest`, an HMAC-SHA256 of the code keyed on
18
+ `secret_key_base` (a plain SHA256 of a 6-digit code is reversed by hashing a million
19
+ candidates), and `VerificationService` compares it in constant time; a request with no
20
+ challenge runs the same comparison, so timing still doesn't reveal one. **Install and run the
21
+ new migration** `20261122000000_add_code_digest_to_standard_id_code_challenges`
22
+ (`bin/rails standard_id:install:migrations && bin/rails db:migrate`), which adds the nullable
23
+ `code_digest` column and drops `NOT NULL` from `code`, both metadata-only on PostgreSQL. Until
24
+ it has run the gem keeps writing plaintext as before, so deploying the gem first breaks nothing.
25
+ Codes issued before the migration keep verifying against the plaintext column until they
26
+ expire (`passwordless.code_ttl`). **`CodeChallenge#code` now returns the raw code only on the
27
+ record the engine just created** (the one in `PASSWORDLESS_CODE_GENERATED`'s `code_challenge:`
28
+ and behind `Otp.issue(delivery: :manual).code`), so delivery subscribers that read
29
+ `event[:code_challenge].code` are unaffected; a challenge loaded from the database returns
30
+ `nil` (or a pre-migration row's plaintext). Host specs that read `CodeChallenge.last.code` must
31
+ capture the code as it is issued with the new `StandardId::Testing::OtpHelpers#capture_otp_code`
32
+ (or `#capture_otp_codes`); challenges created with `create!(code: "123456")` still verify with
33
+ that code. `CodeChallenge#serializable_hash` / `#as_json` leave out `code` and `code_digest`. A
34
+ later release drops the plaintext `code` column and its fallback. See `docs/MIGRATION_GUIDE.md`.
35
+
36
+ ### Added
37
+
38
+ - **`config.previous_secret_key_bases` (default `[]`) for rotating `secret_key_base`.** Session
39
+ tokens, one-time code digests, authorization codes and RFC 7592 registration access tokens are
40
+ all keyed on `secret_key_base`, so rotating it signed everyone out. Secrets listed here are
41
+ still accepted on read while everything new is written under the current one.
42
+ `Session.by_token` checks every candidate in one indexed query (`lookup_hash IN (...)`), and with
43
+ nothing listed does the same work as before. Rails' own derived secrets (encrypted cookies,
44
+ message verifiers) need Rails' rotations as well, and HS256-signed JWTs are not covered: see the
45
+ README, "Rotating `secret_key_base`". The shared helper is `StandardId::KeyedDigest`.
46
+
47
+ - **Passwords are re-hashed on login when the bcrypt cost has changed (on by default).** Stored
48
+ digests were never upgraded, so raising `BCrypt::Engine.cost` only reached passwords set
49
+ afterwards. `StandardId::PasswordCredential#rehash_password` now re-hashes the password at the
50
+ cost `has_secure_password` uses when the stored digest was made at another one, after every
51
+ successful password login: `sign_in_account` (web), the OAuth password grant, and the email +
52
+ password API's `Authentication.call` and `Verification.verify!`. The write is a single `UPDATE`
53
+ conditional on the row still holding the digest the password was checked against, so a reset
54
+ that lands first wins and the rehash is skipped; where the login re-checks the digest under a
55
+ 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
56
+ login. Publishes the new `credential.password.rehashed` (`credential`, `account`,
57
+ `previous_cost`, `cost`) after commit. All digests are at the default cost today, so this is a
58
+ no-op until a host raises it. When it does, each user's first login afterwards replaces their
59
+ digest, which is the fingerprint of the `:remember_me` and `:password_reset` tokens: their
60
+ remember-me cookies on other browsers stop working and unused reset links are voided (the
61
+ login's own remember-me cookie is minted after the rehash). Turn it off with
62
+ `c.password.rehash_on_login = false`.
63
+
64
+ - **Opt-in "your password was changed" email.** Set `c.password.changed_notice_delivery =
65
+ :built_in` (default `:custom`: the engine sends nothing) to have
66
+ `StandardId::AccountNoticeMailer#password_changed` email the credential's e-mail identifier
67
+ whenever its password is changed or reset, telling the owner what to do if it wasn't them. Copy is
68
+ under `standard_id.account_notice_mailer.password_changed.*`. Delivered by the new
69
+ `Events::Subscribers::PasswordChangedNoticeSubscriber` on `credential.password.changed`. Off by
70
+ default so upgrading sends no new mail. A host that already sends its own notice from a
71
+ `credential.password.reset_completed` subscriber should leave it off, or the owner gets two.
72
+
73
+ ### Fixed
74
+
75
+ - **`credential.password.changed` is now published.** It was defined and documented but nothing
76
+ published it. `StandardId::PasswordCredential` now publishes it after commit whenever an update
77
+ assigns a new password through `password=`. That includes both reset flows, which set
78
+ `reason: :password_reset`, and host code (`reason: :changed`). Writing `password_digest`
79
+ directly, as a re-hash of the same password does, does not publish it. The check runs at
80
+ commit against the digest in the row, so a password change that survives a rolled-back
81
+ savepoint, or a rolled-back save that is retried, still publishes once it commits. The payload
82
+ carries `credential_id` explicitly, so the built-in notice still finds its recipient under
83
+ `events.publish_records = false`. The documented `changed_by` payload field, which was never
84
+ sent, is replaced by `reason`. A subscriber that raises is reported and does not fail the save.
85
+
10
86
  ## [0.59.0] - 2026-11-03
11
87
 
12
88
  ### 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
@@ -836,7 +842,10 @@ parent's `default from:` does not apply to them.
836
842
  Event payload includes:
837
843
  - `channel` - `"email"` or `"sms"`
838
844
  - `identifier` - The email address or phone number
839
- - `code_challenge` - The code challenge object with `.code` method
845
+ - `code_challenge` - The code challenge object with `.code` method. The raw code exists only on
846
+ this in-memory record: the database stores an HMAC of it (`code_digest`), so read `.code` in the
847
+ subscriber and pass the string on; a challenge reloaded later (e.g. in a job that received the
848
+ record) returns `nil`
840
849
  - `expires_at` - When the code expires
841
850
  - `realm` - The OTP realm (`"authentication"` for sign-in)
842
851
  - `skip_sender` - `true` for `Otp.issue(delivery: :manual)`; don't deliver
@@ -844,6 +853,18 @@ Event payload includes:
844
853
 
845
854
  > **Note**: `passwordless_email_sender` / `passwordless_sms_sender` were removed in 0.43; see the [Migration Guide](docs/MIGRATION_GUIDE.md).
846
855
 
856
+ ### Password changed notice
857
+
858
+ 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.
859
+
860
+ 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:
861
+
862
+ ```ruby
863
+ config.password.changed_notice_delivery = :built_in # default :custom (send nothing)
864
+ ```
865
+
866
+ 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.
867
+
847
868
  ### Starting a passwordless login from your own controller
848
869
 
849
870
  To send the code from your own controller (a sign-up form, an invite page) and
@@ -1016,7 +1037,8 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1016
1037
  | Credential | `credential.password.created` | `credential`, `account` | After a password credential is created |
1017
1038
  | | `credential.password.reset_initiated` | `credential`, `account`, `reset_token_expires_at` | After a password reset is initiated |
1018
1039
  | | `credential.password.reset_completed` | `credential`, `account` | After a password reset is confirmed |
1019
- | | `credential.password.changed` | `credential`, `account`, `changed_by` | After a password is updated |
1040
+ | | `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` |
1041
+ | | `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
1042
  | | `credential.client_secret.created` | `credential`, `client_id` | After a client secret is created |
1021
1043
  | | `credential.client_secret.rotated` | `credential`, `client_id`, `old_secret_revoked_at` | After a client secret rotation |
1022
1044
 
@@ -1881,7 +1903,7 @@ StandardId creates the following tables:
1881
1903
  - `standard_id_clients` - OAuth clients
1882
1904
  - `standard_id_client_secret_credentials` - Client secrets
1883
1905
  - `standard_id_password_credentials` - Password storage
1884
- - `standard_id_code_challenges` - OTP codes for authentication and verification
1906
+ - `standard_id_code_challenges` - OTP codes for authentication and verification (stored as an HMAC digest)
1885
1907
 
1886
1908
  ## API Endpoints
1887
1909
 
@@ -2148,6 +2170,27 @@ scoped login request instead. It replaces controller stubbing
2148
2170
  (`stub_web_authentication`, `allow_any_instance_of(...).to receive(:current_user)`)
2149
2171
  and per-app `/test/set-session` routes.
2150
2172
 
2173
+ ### Reading one-time codes in specs
2174
+
2175
+ A `CodeChallenge` stores only an HMAC of its code, so `StandardId::CodeChallenge.last.code` is
2176
+ `nil`. Capture the code as it is issued instead:
2177
+
2178
+ ```ruby
2179
+ RSpec.configure do |config|
2180
+ config.include StandardId::Testing::OtpHelpers, type: :request
2181
+ end
2182
+
2183
+ code = capture_otp_code(email) { post "/login", params: { login: { email: email } } }
2184
+ patch "/login_verify", params: { code: code }
2185
+
2186
+ codes = capture_otp_codes { ... } # every code issued in the block: identifier, channel, realm, code
2187
+ ```
2188
+
2189
+ They read `PASSWORDLESS_CODE_GENERATED`, as a delivery subscriber does, so they see nothing when
2190
+ `c.events.publish_records = false`. A challenge you create yourself
2191
+ (`CodeChallenge.create!(code: "123456", ...)` or the `:standard_id_code_challenge` factory) still
2192
+ verifies with the code you gave it.
2193
+
2151
2194
  ### This gem's own suite
2152
2195
 
2153
2196
  StandardId includes comprehensive test coverage:
@@ -2174,6 +2217,38 @@ bundle exec rspec spec/controllers/
2174
2217
  requests that omit `code_challenge` for a PKCE-required client are
2175
2218
  rejected with `invalid_request`.
2176
2219
  - Rate limiting on authentication endpoints
2220
+ - Passwordless / OTP codes are stored as HMAC-SHA256 digests keyed on `secret_key_base`, never in
2221
+ plaintext (since migration `20261122000000`; see the Migration Guide)
2222
+
2223
+ ### Rotating `secret_key_base`
2224
+
2225
+ Session tokens, passwordless codes, authorization codes and RFC 7592 registration access tokens are
2226
+ stored as digests keyed on `secret_key_base`, so changing it invalidates all of them: everyone is
2227
+ signed out. To rotate without that, list the old secret, newest first:
2228
+
2229
+ ```ruby
2230
+ StandardId.configure do |c|
2231
+ c.previous_secret_key_bases = [Rails.application.credentials.old_secret_key_base]
2232
+ end
2233
+ ```
2234
+
2235
+ Digests are then still looked up and verified under the old secret (one indexed query covers every
2236
+ candidate session lookup hash), while everything new is written under the current one
2237
+ (`StandardId::KeyedDigest`). Nothing is re-written in place, so keep the entry until the longest
2238
+ session lifetime you issue (`session.*_lifetime`, and the lifetime of any long-lived
2239
+ `ServiceSession`) has passed, then remove it.
2240
+
2241
+ This covers StandardId's own digests only. The rest of the app needs Rails' rotations too:
2242
+
2243
+ - **Cookies**, including the encrypted `session_token` cookie and the Rails session that carry the
2244
+ web session: `config.action_dispatch.cookies_rotations` (see the Rails security guide,
2245
+ "Rotating Encrypted and Signed Cookies Configurations").
2246
+ - **Message verifiers** (`generates_token_for`, so remember-me and password-reset tokens, and the
2247
+ signed passwordless OTP payload): `Rails.application.message_verifiers.rotate(secret_key_base:
2248
+ old)` in a `before_initialize` block.
2249
+ - **JWTs signed with HS256** (the default `oauth.signing_algorithm`) use `secret_key_base` directly
2250
+ and are not covered: access tokens fail until re-issued and HS256 refresh tokens stop refreshing.
2251
+ Use an asymmetric `oauth.signing_key` if you need to rotate without that.
2177
2252
 
2178
2253
  ## OTP Start Limits
2179
2254
 
@@ -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
@@ -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
- includes(:account).find_by(code_hash: hash_for(plaintext_code))
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}:#{Rails.configuration.secret_key_base}")
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}:#{Rails.configuration.secret_key_base}")
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
- ActiveSupport::SecurityUtils.secure_compare(
220
- self.class.digest_registration_access_token(token.to_s),
221
- registration_access_token_digest.to_s
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
- validates :code, presence: true
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
@@ -16,10 +16,151 @@ module StandardId
16
16
  validates :login, presence: true, uniqueness: true
17
17
  validates :password, confirmation: true, if: :validate_password?
18
18
 
19
+ # Why the next password change happens, published as
20
+ # CREDENTIAL_PASSWORD_CHANGED's +reason+: the engine's reset flows set
21
+ # :password_reset; otherwise it is :changed.
22
+ attr_writer :password_change_reason
23
+
24
+ # CREDENTIAL_PASSWORD_CHANGED, once an update that set a new password
25
+ # commits: the engine's resets and any host code that assigns +password+.
26
+ # Writing password_digest without going through +password=+ (a rehash of
27
+ # the same password) does not count.
28
+ #
29
+ # The digest +password=+ made is kept until a commit, and published only
30
+ # when it is the digest that commit left in the row. Nothing is decided at
31
+ # save time, so a rolled-back savepoint inside the transaction, or a
32
+ # rolled-back save retried later, still publishes when the new password
33
+ # finally commits; a commit that did not write it publishes nothing.
34
+ after_create_commit :forget_assigned_password
35
+ after_update_commit :publish_password_changed, if: :password_change_committed?
36
+
37
+ # has_secure_password's setter, remembering the digest it made so the
38
+ # commit can tell a new password from a direct write of the digest. An
39
+ # empty assignment changes nothing, as has_secure_password ignores it.
40
+ def password=(unencrypted_password)
41
+ super
42
+ @assigned_password_digest = (password_digest if unencrypted_password.present?)
43
+ end
44
+
45
+ # The bcrypt cost has_secure_password hashes a new password at, worked out
46
+ # the way ActiveModel::SecurePassword does.
47
+ def self.password_cost
48
+ ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
49
+ end
50
+
51
+ # Re-hashes +password+ when the stored digest was made at a bcrypt cost
52
+ # other than .password_cost, so raising BCrypt::Engine.cost reaches
53
+ # existing passwords as their owners sign in instead of only new ones.
54
+ # Every password login calls it once +password+ has authenticated; turn it
55
+ # off with c.password.rehash_on_login = false.
56
+ #
57
+ # +authenticated_digest+ is the digest +password+ was checked against. The
58
+ # write is one UPDATE conditional on the row still holding it, so a reset
59
+ # that got there first wins and nothing changes. A caller that re-checks
60
+ # the digest under a lock (EmailPassword::Authentication, Verification)
61
+ # must call this after that check, inside the lock, or its own check would
62
+ # see the new digest. Nothing is reloaded, so the caller's preloaded
63
+ # associations survive.
64
+ #
65
+ # The digest is the fingerprint of the :remember_me and :password_reset
66
+ # tokens, so a rehash invalidates the user's outstanding remember-me
67
+ # cookies and reset links: mint any new one after calling this.
68
+ #
69
+ # Never raises: a failed rehash keeps the old digest and the login goes on.
70
+ #
71
+ # @return [Boolean] whether the digest was replaced
72
+ def rehash_password(password, authenticated_digest = password_digest)
73
+ return false unless StandardId.config.password.rehash_on_login && password_rehash_needed?
74
+
75
+ previous_cost = BCrypt::Password.new(password_digest).cost
76
+ attributes = { password_digest: BCrypt::Password.create(password, cost: self.class.password_cost), updated_at: Time.current }
77
+ # The savepoint keeps a failed UPDATE from aborting the caller's
78
+ # transaction (PostgreSQL refuses every later statement in it).
79
+ rehashed = self.class.transaction(requires_new: true) do
80
+ self.class.where(id: id, password_digest: authenticated_digest).update_all(attributes) == 1
81
+ end
82
+ return false unless rehashed
83
+
84
+ assign_attributes(attributes)
85
+ clear_attribute_changes(attributes.keys)
86
+ # Held until the caller's transaction commits, so a login that rolls
87
+ # back (a policy refusal inside EmailPassword::Authentication's lock)
88
+ # reports no rehash.
89
+ ActiveRecord.after_all_transactions_commit { publish_password_rehashed(previous_cost) }
90
+ true
91
+ rescue StandardError => e
92
+ report_failure("rehash password credential #{id}", e)
93
+ false
94
+ end
95
+
19
96
  private
20
97
 
21
98
  def validate_password?
22
99
  password.present? || password_confirmation.present?
23
100
  end
101
+
102
+ def password_rehash_needed?
103
+ BCrypt::Password.new(password_digest).cost != self.class.password_cost
104
+ rescue BCrypt::Errors::InvalidHash
105
+ false
106
+ end
107
+
108
+ # The event carries the account: load the chain (a no-op where the caller
109
+ # preloaded it) so a subscriber under strict loading can walk it.
110
+ def publish_password_rehashed(previous_cost)
111
+ ActiveRecord::Associations::Preloader.new(records: [self], associations: { credential: { identifier: :account } }).call
112
+ StandardId::Events.publish(
113
+ StandardId::Events::CREDENTIAL_PASSWORD_REHASHED,
114
+ credential: self,
115
+ account: account,
116
+ previous_cost: previous_cost,
117
+ cost: self.class.password_cost
118
+ )
119
+ rescue StandardError => e
120
+ report_failure("publish CREDENTIAL_PASSWORD_REHASHED for password credential #{id}", e)
121
+ end
122
+
123
+ def report_failure(action, error)
124
+ Rails.error.report(error, handled: true, source: "standard_id")
125
+ logger = StandardId.logger
126
+ return unless logger.respond_to?(:error)
127
+
128
+ logger.error("[StandardId::PasswordCredential] Failed to #{action}: #{error.class}: #{error.message}")
129
+ end
130
+
131
+ def forget_assigned_password
132
+ @assigned_password_digest = nil
133
+ end
134
+
135
+ # Read from the row rather than the record: after a rollback the record
136
+ # can still hold the assigned digest while the row does not.
137
+ def password_change_committed?
138
+ @assigned_password_digest.present? &&
139
+ self.class.where(id: id).pick(:password_digest) == @assigned_password_digest
140
+ end
141
+
142
+ # The change has committed, so a failing subscriber must not raise out of
143
+ # the caller's save; report and carry on, as the reset flows do for
144
+ # CREDENTIAL_PASSWORD_RESET_COMPLETED. The event carries the account: load
145
+ # the chain so a subscriber under strict loading can walk it.
146
+ #
147
+ # +credential_id+ is explicit, as on PASSWORD_VALIDATED: the record keys
148
+ # are left out under events.publish_records = false, and so are their
149
+ # _id/_gid companions when publish_record_identifiers is off too.
150
+ def publish_password_changed
151
+ reason = @password_change_reason || :changed
152
+ forget_assigned_password
153
+ @password_change_reason = nil
154
+ ActiveRecord::Associations::Preloader.new(records: [self], associations: { credential: { identifier: :account } }).call
155
+ StandardId::Events.publish(
156
+ StandardId::Events::CREDENTIAL_PASSWORD_CHANGED,
157
+ credential: self,
158
+ credential_id: id,
159
+ account: credential&.account,
160
+ reason: reason
161
+ )
162
+ rescue StandardError => e
163
+ report_failure("publish CREDENTIAL_PASSWORD_CHANGED for password credential #{id}", e)
164
+ end
24
165
  end
25
166
  end
@@ -17,10 +17,20 @@ module StandardId
17
17
  scope :revoked, -> { where.not(revoked_at: nil) }
18
18
 
19
19
  scope :api_compatible, -> { where(type: ["StandardId::DeviceSession", "StandardId::ServiceSession"]) }
20
- scope :by_token, ->(token) {
21
- lookup_hash = Digest::SHA256.hexdigest("#{token}:#{Rails.configuration.secret_key_base}")
22
- where(lookup_hash:)
23
- }
20
+ # One indexed query for every lookup hash the token may be stored under:
21
+ # the current secret's, plus one per `config.previous_secret_key_bases`
22
+ # entry (see StandardId::KeyedDigest).
23
+ scope :by_token, ->(token) { where(lookup_hash: lookup_hashes_for(token)) }
24
+
25
+ # SHA256 of the token under `secret` — an indexable locator, never the
26
+ # credential (see .authenticate_by_token).
27
+ def self.lookup_hash_for(token, secret: StandardId::KeyedDigest.current_secret)
28
+ Digest::SHA256.hexdigest("#{token}:#{secret}")
29
+ end
30
+
31
+ def self.lookup_hashes_for(token)
32
+ StandardId::KeyedDigest.candidates { |secret| lookup_hash_for(token, secret:) }
33
+ end
24
34
 
25
35
  # Authenticate an opaque session token.
26
36
  #
@@ -64,10 +74,8 @@ module StandardId
64
74
  # with SHA256; this brings session tokens in line with both.
65
75
  DIGEST_PREFIX = "standard_id.session.token_digest.v1:".freeze
66
76
 
67
- def self.hmac_token_digest(token)
68
- OpenSSL::HMAC.hexdigest(
69
- "SHA256", Rails.configuration.secret_key_base, "#{DIGEST_PREFIX}#{token}"
70
- )
77
+ def self.hmac_token_digest(token, secret: StandardId::KeyedDigest.current_secret)
78
+ StandardId::KeyedDigest.hmac_hexdigest("#{DIGEST_PREFIX}#{token}", secret:)
71
79
  end
72
80
 
73
81
  # Timing-safe verification of `token` against this session's stored digest.
@@ -79,7 +87,8 @@ module StandardId
79
87
  # way a config change never strands existing sessions, and no rewrite of
80
88
  # stored digests is needed. Both branches end in a constant-time compare, so
81
89
  # the response time carries no information about how much of the digest
82
- # matched.
90
+ # matched. An HMAC digest is accepted under the current secret or any of
91
+ # `config.previous_secret_key_bases`; BCrypt digests are not keyed.
83
92
  #
84
93
  # @return [Boolean] false for a blank or malformed digest — never raises.
85
94
  def authenticate_token(token)
@@ -92,8 +101,9 @@ module StandardId
92
101
  BCrypt::Engine.hash_secret(token, stored.salt)
93
102
  )
94
103
  else
95
- ActiveSupport::SecurityUtils.secure_compare(
96
- token_digest, self.class.hmac_token_digest(token)
104
+ StandardId::KeyedDigest.secure_match?(
105
+ token_digest,
106
+ StandardId::KeyedDigest.candidates { |secret| self.class.hmac_token_digest(token, secret:) }
97
107
  )
98
108
  end
99
109
  rescue BCrypt::Errors::InvalidHash, BCrypt::Errors::InvalidSalt
@@ -265,7 +275,7 @@ module StandardId
265
275
  end
266
276
 
267
277
  def generate_lookup_hash
268
- self.lookup_hash = Digest::SHA256.hexdigest("#{token}:#{Rails.configuration.secret_key_base}")
278
+ self.lookup_hash = self.class.lookup_hash_for(token)
269
279
  end
270
280
 
271
281
  # Revoke any still-active refresh tokens before the session row is deleted,
@@ -0,0 +1,22 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <style>
6
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 0; }
7
+ .container { max-width: 480px; margin: 40px auto; background-color: #ffffff; border-radius: 8px; padding: 40px; }
8
+ .footer { margin-top: 32px; font-size: 13px; color: #888888; text-align: center; }
9
+ </style>
10
+ </head>
11
+ <body>
12
+ <div class="container">
13
+ <p><%= notice_copy(:greeting) %></p>
14
+ <p><%= notice_copy(:intro) %></p>
15
+ <p><%= notice_copy(:action) %></p>
16
+ <p><%= notice_copy(:warning) %></p>
17
+ <div class="footer">
18
+ <p><%= notice_copy(:footer) %></p>
19
+ </div>
20
+ </div>
21
+ </body>
22
+ </html>
@@ -0,0 +1,10 @@
1
+ <%= notice_copy(:greeting) %>
2
+
3
+ <%= notice_copy(:intro) %>
4
+
5
+ <%= notice_copy(:action) %>
6
+
7
+ <%= notice_copy(:warning) %>
8
+
9
+ --
10
+ <%= notice_copy(:footer) %>
@@ -28,3 +28,10 @@ en:
28
28
  action: "If that was you, sign in the way you did before, or reset your password if you have forgotten it."
29
29
  ignore: "If it wasn't you, you can safely ignore this email. Your account has not changed."
30
30
  footer: "This is an automated message. Please do not reply."
31
+ password_changed:
32
+ subject: "Your password was changed"
33
+ greeting: "Hi,"
34
+ intro: "The password for your account was just changed."
35
+ action: "If you made this change, you don't need to do anything."
36
+ warning: "If you didn't, reset your password straight away and check your account for anything you don't recognise."
37
+ footer: "This is an automated message. Please do not reply."
@@ -0,0 +1,24 @@
1
+ # Passwordless / OTP codes were stored in plaintext in `code`, so anyone who
2
+ # could read the table could sign in with any active code. From this migration
3
+ # on, StandardId stores only `code_digest`, an HMAC-SHA256 of the code keyed on
4
+ # secret_key_base (StandardId::CodeChallenge.digest_code), and leaves `code`
5
+ # NULL on new rows.
6
+ #
7
+ # Both steps are metadata-only on PostgreSQL: a nullable string column with no
8
+ # default and no index (a challenge is found by realm/channel/target, then its
9
+ # digest is compared in constant time), and dropping a NOT NULL constraint.
10
+ #
11
+ # `code` is kept, nullable, for one transition: challenges issued before the
12
+ # deploy still carry a plaintext code and are verified against it until they
13
+ # expire (code_ttl, 10 minutes by default) and CleanupExpiredCodeChallengesJob
14
+ # deletes them. A later release drops the column; see docs/MIGRATION_GUIDE.md.
15
+ # Until this has run, the gem keeps writing the plaintext column as before.
16
+ #
17
+ # Rolling back restores NOT NULL on `code`, which fails while any digest-only
18
+ # row exists: delete those first (they are at most code_ttl old).
19
+ class AddCodeDigestToStandardIdCodeChallenges < ActiveRecord::Migration[8.0]
20
+ def change
21
+ add_column :standard_id_code_challenges, :code_digest, :string
22
+ change_column_null :standard_id_code_challenges, :code, true
23
+ end
24
+ end
@@ -104,6 +104,15 @@ StandardId.configure do |c|
104
104
  # Default: Rails.logger
105
105
  # c.logger = Rails.logger
106
106
 
107
+ # Old secret_key_base values (newest first) still accepted for StandardId's
108
+ # keyed digests — session tokens, OTP codes, authorization codes, registration
109
+ # access tokens — so rotating the secret does not sign everyone out. New
110
+ # digests always use the current secret. Keep an entry for the longest
111
+ # session lifetime, and rotate Rails' cookies and message verifiers too
112
+ # (README "Rotating secret_key_base").
113
+ # Default: []
114
+ # c.previous_secret_key_bases = [Rails.application.credentials.old_secret_key_base]
115
+
107
116
  # Layout used by built-in ERB web views. Ignored when use_inertia is true.
108
117
  # Default: nil (StandardId's packaged layout)
109
118
  # c.web_layout = "application"
@@ -86,6 +86,20 @@ StandardId::ConfigSchema.define do
86
86
  # deliberately superseded or deferred.
87
87
  field :ignored_migrations, type: :array, default: -> { [] }
88
88
 
89
+ # Previous `secret_key_base` values, newest first, still ACCEPTED when
90
+ # looking up and verifying the engine's keyed digests: session tokens
91
+ # (lookup_hash and the HMAC token_digest), passwordless code digests,
92
+ # authorization codes and RFC 7592 registration access tokens. New digests
93
+ # are always written under the current secret. See StandardId::KeyedDigest.
94
+ #
95
+ # Empty (default) means rotating `secret_key_base` invalidates all of them
96
+ # at once, which is what it always did. To rotate without signing everyone
97
+ # out, list the old secret here for at least the longest session lifetime,
98
+ # alongside Rails' own rotations for its cookies and message verifiers
99
+ # (README "Rotating secret_key_base"). Each extra entry costs one more
100
+ # candidate per lookup and one more HMAC per verification.
101
+ field :previous_secret_key_bases, type: :array, default: -> { [] }
102
+
89
103
  # Scope-aware authentication: maps scope names to profile-based access config.
90
104
  # Each scope is a hash with keys: :profile_types (Array<String>), :after_sign_in_path,
91
105
  # :no_profile_message, :label, :allow_registration, :authorizer.
@@ -306,6 +320,22 @@ StandardId::ConfigSchema.define do
306
320
  field :require_special_chars, type: :boolean, default: true
307
321
  field :require_uppercase, type: :boolean, default: true
308
322
  field :require_numbers, type: :boolean, default: true
323
+ # Re-hash a password on a successful login when its stored digest was
324
+ # made at a bcrypt cost other than the one has_secure_password uses now
325
+ # (BCrypt::Engine.cost), so raising the cost reaches existing passwords.
326
+ # A no-op until the cost changes. A rehash replaces the digest, which
327
+ # signs that user out of remember-me cookies and voids their reset links.
328
+ # See StandardId::PasswordCredential#rehash_password.
329
+ field :rehash_on_login, type: :boolean, default: true
330
+ # Who tells the owner, by email, that their password was changed or reset
331
+ # (CREDENTIAL_PASSWORD_CHANGED):
332
+ # :custom — (default) the engine sends nothing; subscribe to the event
333
+ # to send your own
334
+ # :built_in — the engine sends AccountNoticeMailer#password_changed to
335
+ # the credential's e-mail identifier
336
+ # Off by default so an upgrade does not start sending mail, nor a second
337
+ # notice next to one a host already sends on reset_completed.
338
+ field :changed_notice_delivery, type: :symbol, default: :custom
309
339
  end
310
340
 
311
341
  scope :reset_password do
@@ -12,7 +12,9 @@ module StandardId
12
12
  # locked, after re-checking that the password has not changed since it was
13
13
  # verified. Mint tokens inside it: PasswordReset.complete! takes the same
14
14
  # lock to change the password and revoke access, so a login racing a reset
15
- # either finishes first (and its tokens are revoked) or fails.
15
+ # either finishes first (and its tokens are revoked) or fails. The password
16
+ # is rehashed (PasswordCredential#rehash_password) only after that
17
+ # re-check passes, so the re-check never sees its own rehash.
16
18
  module Authentication
17
19
  class << self
18
20
  # @return [Account]
@@ -45,10 +47,14 @@ module StandardId
45
47
  )
46
48
 
47
49
  raise StandardId::EmailPasswordError.new(:unverified) unless identifier.verified?
48
- return account unless block_given?
50
+ unless block_given?
51
+ password_credential.rehash_password(password, verified_digest)
52
+ return account
53
+ end
49
54
 
50
55
  password_credential.with_lock do
51
56
  failed!(email) unless password_credential.password_digest == verified_digest
57
+ password_credential.rehash_password(password, verified_digest)
52
58
  yield account
53
59
  end
54
60
  end
@@ -76,6 +76,7 @@ module StandardId
76
76
  raise TokenAlreadyUsed
77
77
  end
78
78
 
79
+ password_credential.password_change_reason = :password_reset
79
80
  password_credential.update!(password: password)
80
81
  api_signup = !identifier.verified? && EmailPassword.api_signup?(identifier)
81
82
  EmailPassword.complete_verification!(
@@ -69,10 +69,14 @@ module StandardId
69
69
  )
70
70
  identifier.account
71
71
  end
72
- return account unless block_given?
72
+ unless block_given?
73
+ password_credential.rehash_password(password, verified_digest)
74
+ return account
75
+ end
73
76
 
74
77
  password_credential.with_lock do
75
78
  password_unchanged!(password_credential, verified_digest)
79
+ password_credential.rehash_password(password, verified_digest)
76
80
  yield account
77
81
  end
78
82
  end
@@ -80,6 +80,7 @@ module StandardId
80
80
  StandardId::Events::Subscribers::AccountLockingSubscriber.attach
81
81
  StandardId::Events::Subscribers::PasswordlessDeliverySubscriber.attach
82
82
  StandardId::Events::Subscribers::PasswordResetDeliverySubscriber.attach
83
+ StandardId::Events::Subscribers::PasswordChangedNoticeSubscriber.attach
83
84
 
84
85
  StandardId::Engine.warn_about_issuer_config!
85
86
 
@@ -70,6 +70,9 @@ module StandardId
70
70
  CREDENTIAL_PASSWORD_RESET_INITIATED = "credential.password.reset_initiated"
71
71
  CREDENTIAL_PASSWORD_RESET_COMPLETED = "credential.password.reset_completed"
72
72
  CREDENTIAL_PASSWORD_CHANGED = "credential.password.changed"
73
+ # A login re-hashed the password at the current bcrypt cost
74
+ # (PasswordCredential#rehash_password). The password itself is unchanged.
75
+ CREDENTIAL_PASSWORD_REHASHED = "credential.password.rehashed"
73
76
  CREDENTIAL_CLIENT_SECRET_CREATED = "credential.client_secret.created"
74
77
  CREDENTIAL_CLIENT_SECRET_ROTATED = "credential.client_secret.rotated"
75
78
  CREDENTIAL_CLIENT_SECRET_REVOKED = "credential.client_secret.revoked"
@@ -156,6 +159,7 @@ module StandardId
156
159
  CREDENTIAL_PASSWORD_RESET_INITIATED,
157
160
  CREDENTIAL_PASSWORD_RESET_COMPLETED,
158
161
  CREDENTIAL_PASSWORD_CHANGED,
162
+ CREDENTIAL_PASSWORD_REHASHED,
159
163
  CREDENTIAL_CLIENT_SECRET_CREATED,
160
164
  CREDENTIAL_CLIENT_SECRET_ROTATED,
161
165
  CREDENTIAL_CLIENT_SECRET_REVOKED
@@ -201,6 +205,7 @@ module StandardId
201
205
  CREDENTIAL_PASSWORD_RESET_INITIATED,
202
206
  CREDENTIAL_PASSWORD_RESET_COMPLETED,
203
207
  CREDENTIAL_PASSWORD_CHANGED,
208
+ CREDENTIAL_PASSWORD_REHASHED,
204
209
  CREDENTIAL_CLIENT_SECRET_CREATED,
205
210
  CREDENTIAL_CLIENT_SECRET_ROTATED,
206
211
  CREDENTIAL_CLIENT_SECRET_REVOKED,
@@ -0,0 +1,42 @@
1
+ module StandardId
2
+ module Events
3
+ module Subscribers
4
+ # Emails the owner when their password is changed or reset, while
5
+ # c.password.changed_notice_delivery is :built_in. Sent to the
6
+ # credential's e-mail identifier; a credential behind a username or phone
7
+ # identifier gets nothing. Under events.publish_records = false the
8
+ # payload carries no records, so the credential is loaded from
9
+ # +credential_id+.
10
+ class PasswordChangedNoticeSubscriber < Base
11
+ subscribe_to StandardId::Events::CREDENTIAL_PASSWORD_CHANGED
12
+
13
+ def call(event)
14
+ return unless built_in_delivery?
15
+
16
+ identifier = password_credential(event)&.credential&.identifier
17
+ return unless identifier.is_a?(StandardId::EmailIdentifier) && identifier.value.present?
18
+
19
+ StandardId::AccountNoticeMailer.with(email: identifier.value).password_changed.deliver_later
20
+ end
21
+
22
+ def handle_error(error, event)
23
+ StandardId.logger.error(
24
+ "[StandardId::PasswordChangedNotice] Failed to deliver password changed notice " \
25
+ "for password credential #{event[:credential_id]}: #{error.message}"
26
+ )
27
+ end
28
+
29
+ private
30
+
31
+ def password_credential(event)
32
+ event[:credential] ||
33
+ (event[:credential_id] && StandardId::PasswordCredential.includes(credential: :identifier).find_by(id: event[:credential_id]))
34
+ end
35
+
36
+ def built_in_delivery?
37
+ StandardId.config.password.changed_notice_delivery == :built_in
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,65 @@
1
+ require "openssl"
2
+
3
+ module StandardId
4
+ # The secrets StandardId keys its stored token digests on, and the
5
+ # comparisons that accept any of them.
6
+ #
7
+ # Every keyed digest the engine stores (Session#lookup_hash and
8
+ # #token_digest, CodeChallenge#code_digest, AuthorizationCode#code_hash,
9
+ # ClientApplication#registration_access_token_digest) is derived from
10
+ # `secret_key_base`, so rotating that secret used to strand every one of
11
+ # them: all users signed out, every in-flight code and registration access
12
+ # token dead.
13
+ #
14
+ # `config.previous_secret_key_bases` is the opt-in that prevents it.
15
+ # Digests are always WRITTEN under the current secret; they are READ (looked
16
+ # up and verified) under the current secret and then each previous one, in
17
+ # order. Rails offers the same idea for its own derived secrets
18
+ # (`Rails.application.message_verifiers.rotate(secret_key_base: old)`,
19
+ # `config.action_dispatch.cookies_rotations`), but keeps no list of previous
20
+ # `secret_key_base` values a gem could read, hence the setting. The shape
21
+ # mirrors Rodauth's `hmac_old_secret`.
22
+ module KeyedDigest
23
+ module_function
24
+
25
+ # The secret new digests are written under. Read through
26
+ # Rails.configuration, as the stored digests always have been, so the
27
+ # values for the current secret are unchanged by this module.
28
+ def current_secret
29
+ Rails.configuration.secret_key_base
30
+ end
31
+
32
+ # Current secret first, then `config.previous_secret_key_bases` (blank
33
+ # entries and duplicates of an earlier secret dropped). With no previous
34
+ # secrets configured this is one element and every caller does exactly the
35
+ # work it did before.
36
+ def secrets
37
+ previous = Array(StandardId.config.previous_secret_key_bases).map(&:to_s).reject(&:blank?)
38
+ [current_secret, *previous].uniq
39
+ end
40
+
41
+ # HMAC-SHA256 of +data+ under +secret+, hex-encoded. Callers domain-separate
42
+ # by prefixing +data+ with a versioned label of their own.
43
+ def hmac_hexdigest(data, secret: current_secret)
44
+ OpenSSL::HMAC.hexdigest("SHA256", secret, data)
45
+ end
46
+
47
+ # The value a digest may be stored as, once per accepted secret: yields
48
+ # each secret (current first) and collects the block's results. Use it to
49
+ # query an indexed digest column for every candidate at once.
50
+ def candidates
51
+ secrets.map { |secret| yield secret }
52
+ end
53
+
54
+ # Constant-time check of +stored+ against every candidate. Compares against
55
+ # all of them rather than stopping at the first match, so the response time
56
+ # does not say which secret a digest was written under.
57
+ #
58
+ # @return [Boolean] false for a blank +stored+ value
59
+ def secure_match?(stored, candidates)
60
+ return false if stored.blank?
61
+
62
+ candidates.map { |candidate| ActiveSupport::SecurityUtils.secure_compare(stored.to_s, candidate.to_s) }.any?
63
+ end
64
+ end
65
+ end
@@ -28,6 +28,7 @@ module StandardId
28
28
 
29
29
  emit_password_validated
30
30
  validate_requested_scope!
31
+ @credential&.rehash_password(params[:password])
31
32
  end
32
33
 
33
34
  private
@@ -115,21 +115,23 @@ module StandardId
115
115
  challenge = lock_active_challenge
116
116
 
117
117
  unless challenge
118
- # Constant-time compare even when no challenge exists to prevent
119
- # timing-based enumeration of valid target+realm pairs. We compare
120
- # the submitted code against a random value of the same digit
121
- # length so an observer cannot distinguish "no challenge" from
122
- # "wrong code" by response time.
118
+ # Same comparison even when no challenge exists to prevent
119
+ # timing-based enumeration of valid target+realm pairs. We check
120
+ # the submitted code against an unsaved challenge for a random
121
+ # value of the same digit length, so the work (an HMAC per accepted
122
+ # secret and a constant-time compare) matches the wrong-code path
123
+ # and an observer cannot distinguish "no challenge" from "wrong
124
+ # code" by response time.
123
125
  padded_length = @code.length.clamp(4, 10)
124
126
  fabricated_code = SecureRandom.random_number(10**padded_length).to_s.rjust(padded_length, "0")
125
- secure_compare(fabricated_code, @code)
127
+ StandardId::CodeChallenge.new(code: fabricated_code).code_matches?(@code)
126
128
  # No event — matches prior behavior: we do not publish failure
127
129
  # events for probes that never triggered a real challenge.
128
130
  result = failure("Invalid or expired verification code", error_code: :not_found, attempts: 0)
129
131
  next
130
132
  end
131
133
 
132
- code_matches = secure_compare(challenge.code, @code)
134
+ code_matches = challenge.code_matches?(@code)
133
135
 
134
136
  unless code_matches
135
137
  attempts = record_failed_attempt!(challenge)
@@ -0,0 +1,58 @@
1
+ module StandardId
2
+ module Testing
3
+ # Raw one-time codes, for specs that need to submit one.
4
+ #
5
+ # A challenge stores only an HMAC of its code (migration 20261122000000),
6
+ # so `StandardId::CodeChallenge.last.code` is nil once the row is read back
7
+ # from the database. The raw code exists only on the record the engine has
8
+ # just created, which it publishes as PASSWORDLESS_CODE_GENERATED's
9
+ # `code_challenge:`; these helpers capture it from there, exactly as a
10
+ # delivery subscriber does. (With `config.events.publish_records = false`
11
+ # the record is not published, and there is nothing to capture.)
12
+ #
13
+ # Usage in rails_helper.rb:
14
+ #
15
+ # require "standard_id/testing"
16
+ #
17
+ # RSpec.configure do |config|
18
+ # config.include StandardId::Testing::OtpHelpers, type: :request
19
+ # end
20
+ #
21
+ # Example:
22
+ # code = capture_otp_code { post "/login", params: { email: email } }
23
+ # patch "/login_verify", params: { code: code }
24
+ #
25
+ module OtpHelpers
26
+ IssuedCode = Data.define(:identifier, :channel, :realm, :code)
27
+
28
+ # Every code issued while the block runs, oldest first.
29
+ #
30
+ # @return [Array<IssuedCode>]
31
+ def capture_otp_codes
32
+ codes = []
33
+ subscription = StandardId::Events.subscribe(StandardId::Events::PASSWORDLESS_CODE_GENERATED) do |event|
34
+ code = event[:code_challenge]&.code
35
+ next if code.blank?
36
+
37
+ codes << IssuedCode.new(identifier: event[:identifier], channel: event[:channel], realm: event[:realm], code: code)
38
+ end
39
+
40
+ yield
41
+ codes
42
+ ensure
43
+ ActiveSupport::Notifications.unsubscribe(subscription) if subscription
44
+ end
45
+
46
+ # The last code issued while the block runs, to +identifier+ when given.
47
+ #
48
+ # @return [String]
49
+ # @raise [RuntimeError] when no code was issued
50
+ def capture_otp_code(identifier = nil, &block)
51
+ codes = capture_otp_codes(&block)
52
+ codes = codes.select { |issued| issued.identifier == identifier } if identifier
53
+
54
+ codes.last&.code || raise("No one-time code was issued#{" to #{identifier}" if identifier}")
55
+ end
56
+ end
57
+ end
58
+ end
@@ -1,6 +1,7 @@
1
1
  require "standard_id/testing/authentication_helpers"
2
2
  require "standard_id/testing/request_helpers"
3
3
  require "standard_id/testing/config_helpers"
4
+ require "standard_id/testing/otp_helpers"
4
5
  require "standard_id/testing/provider_examples" if defined?(RSpec)
5
6
 
6
7
  module StandardId
@@ -1,3 +1,3 @@
1
1
  module StandardId
2
- VERSION = "0.59.0"
2
+ VERSION = "0.60.0"
3
3
  end
data/lib/standard_id.rb CHANGED
@@ -15,6 +15,7 @@ require "standard_id/migration_check"
15
15
  require "standard_id/migration_helpers"
16
16
  require "standard_id/checks/migrations"
17
17
  require "standard_id/errors"
18
+ require "standard_id/keyed_digest"
18
19
  require "standard_id/events"
19
20
  require "standard_id/events/subscribers/base"
20
21
  require "standard_id/events/subscribers/logging_subscriber"
@@ -22,6 +23,7 @@ require "standard_id/events/subscribers/account_status_subscriber"
22
23
  require "standard_id/events/subscribers/account_locking_subscriber"
23
24
  require "standard_id/events/subscribers/passwordless_delivery_subscriber"
24
25
  require "standard_id/events/subscribers/password_reset_delivery_subscriber"
26
+ require "standard_id/events/subscribers/password_changed_notice_subscriber"
25
27
  require "standard_id/account_status"
26
28
  require "standard_id/account_locking"
27
29
  require "standard_id/http_client"
metadata CHANGED
@@ -1,10 +1,10 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: standard_id
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.59.0
4
+ version: 0.60.0
5
5
  platform: ruby
6
6
  authors:
7
- - Jaryl Sim
7
+ - Rarebit One
8
8
  bindir: bin
9
9
  cert_chain: []
10
10
  date: 1980-01-02 00:00:00.000000000 Z
@@ -225,6 +225,8 @@ files:
225
225
  - app/models/standard_id/username_identifier.rb
226
226
  - app/views/standard_id/account_notice_mailer/existing_account.html.erb
227
227
  - app/views/standard_id/account_notice_mailer/existing_account.text.erb
228
+ - app/views/standard_id/account_notice_mailer/password_changed.html.erb
229
+ - app/views/standard_id/account_notice_mailer/password_changed.text.erb
228
230
  - app/views/standard_id/password_reset_mailer/reset_email.html.erb
229
231
  - app/views/standard_id/password_reset_mailer/reset_email.text.erb
230
232
  - app/views/standard_id/passwordless_mailer/otp_email.html.erb
@@ -271,6 +273,7 @@ files:
271
273
  - db/migrate/20261022000000_add_signup_source_to_standard_id_identifiers.rb
272
274
  - db/migrate/20261028000000_add_value_lookup_indexes_to_standard_id_tables.rb
273
275
  - db/migrate/20261028100000_remove_redundant_standard_id_indexes.rb
276
+ - db/migrate/20261122000000_add_code_digest_to_standard_id_code_challenges.rb
274
277
  - lib/generators/standard_id/install/install_generator.rb
275
278
  - lib/generators/standard_id/install/templates/standard_id.rb
276
279
  - lib/generators/standard_id/install/templates/standard_id_reference.rb
@@ -313,11 +316,13 @@ files:
313
316
  - lib/standard_id/events/subscribers/account_status_subscriber.rb
314
317
  - lib/standard_id/events/subscribers/base.rb
315
318
  - lib/standard_id/events/subscribers/logging_subscriber.rb
319
+ - lib/standard_id/events/subscribers/password_changed_notice_subscriber.rb
316
320
  - lib/standard_id/events/subscribers/password_reset_delivery_subscriber.rb
317
321
  - lib/standard_id/events/subscribers/passwordless_delivery_subscriber.rb
318
322
  - lib/standard_id/http_client.rb
319
323
  - lib/standard_id/instrumentation.rb
320
324
  - lib/standard_id/jwt_service.rb
325
+ - lib/standard_id/keyed_digest.rb
321
326
  - lib/standard_id/login_method_policy.rb
322
327
  - lib/standard_id/migration_check.rb
323
328
  - lib/standard_id/migration_helpers.rb
@@ -370,6 +375,7 @@ files:
370
375
  - lib/standard_id/testing/factories/oauth.rb
371
376
  - lib/standard_id/testing/factories/sessions.rb
372
377
  - lib/standard_id/testing/factory_bot.rb
378
+ - lib/standard_id/testing/otp_helpers.rb
373
379
  - lib/standard_id/testing/provider_examples.rb
374
380
  - lib/standard_id/testing/request_helpers.rb
375
381
  - lib/standard_id/token_minter.rb
@@ -403,7 +409,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
403
409
  - !ruby/object:Gem::Version
404
410
  version: '0'
405
411
  requirements: []
406
- rubygems_version: 4.0.10
412
+ rubygems_version: 4.0.20
407
413
  specification_version: 4
408
414
  summary: A comprehensive authentication engine for Rails, built on the security primitives
409
415
  introduced in Rails 8.