standard_id 0.58.1 → 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 (37) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +103 -0
  3. data/README.md +80 -3
  4. data/app/controllers/concerns/standard_id/web_authentication.rb +2 -0
  5. data/app/controllers/standard_id/web/login_verify_controller.rb +7 -1
  6. data/app/forms/standard_id/web/reset_password_confirm_form.rb +1 -0
  7. data/app/mailers/standard_id/account_notice_mailer.rb +11 -0
  8. data/app/models/standard_id/authorization_code.rb +6 -3
  9. data/app/models/standard_id/client_application.rb +7 -6
  10. data/app/models/standard_id/code_challenge.rb +69 -1
  11. data/app/models/standard_id/email_identifier.rb +14 -0
  12. data/app/models/standard_id/password_credential.rb +141 -0
  13. data/app/models/standard_id/session.rb +22 -12
  14. data/app/views/standard_id/account_notice_mailer/password_changed.html.erb +22 -0
  15. data/app/views/standard_id/account_notice_mailer/password_changed.text.erb +10 -0
  16. data/app/views/standard_id/web/login_verify/show.html.erb +9 -1
  17. data/config/locales/en.yml +7 -0
  18. data/db/migrate/20261122000000_add_code_digest_to_standard_id_code_challenges.rb +24 -0
  19. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +21 -1
  20. data/lib/standard_id/config/schema.rb +48 -0
  21. data/lib/standard_id/email_domain.rb +169 -0
  22. data/lib/standard_id/email_password/authentication.rb +8 -2
  23. data/lib/standard_id/email_password/password_reset.rb +1 -0
  24. data/lib/standard_id/email_password/verification.rb +5 -1
  25. data/lib/standard_id/engine.rb +1 -0
  26. data/lib/standard_id/events/definitions.rb +5 -0
  27. data/lib/standard_id/events/subscribers/password_changed_notice_subscriber.rb +42 -0
  28. data/lib/standard_id/keyed_digest.rb +65 -0
  29. data/lib/standard_id/oauth/password_flow.rb +1 -0
  30. data/lib/standard_id/passwordless/base_strategy.rb +8 -0
  31. data/lib/standard_id/passwordless/email_strategy.rb +7 -0
  32. data/lib/standard_id/passwordless/verification_service.rb +9 -7
  33. data/lib/standard_id/testing/otp_helpers.rb +58 -0
  34. data/lib/standard_id/testing.rb +1 -0
  35. data/lib/standard_id/version.rb +1 -1
  36. data/lib/standard_id.rb +3 -0
  37. metadata +30 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a54cd12c3c45d8f8dac8a342250327c073ba479ba7fa4568483bf8a9d06fb22e
4
- data.tar.gz: 8886b09be9316a38f55d2d5a16680457bd6c579b5dbf660137a4b457645bc30b
3
+ metadata.gz: 6b16c75edf932c75abfde26acde06652cea845e13d60b5ec943894355eb89327
4
+ data.tar.gz: 5ccd8c3889f612353415998ba063d2e10a2a0450ba099f28e7f863040ccf57e8
5
5
  SHA512:
6
- metadata.gz: f2cdd0a002610a2891adf548dde939b392d83f9848b14106458ecd61757f06c0eba90e8c00a5a5bc1846f602430f698ef5352af3caf9b928532c775a22c43e0f
7
- data.tar.gz: 9fae127fd3c4a0defbfe189437f38327c6b870e987e4f32d46343b5e263cd64e8895111aeed61d264890309d5b8464d72e7c7de4db18b7f2c006f2008464cd4d
6
+ metadata.gz: f2a159cbe0415275e12c90ca0b43d241f7010d4ee3c7bb0d5ad817b9668a6104f5d829fc41db76fb07deadb4164a9d3dc726957305d28053b848fa26c9198bb2
7
+ data.tar.gz: 1f35e1824c63d566905576992b00cba1f62377874d069286a4353bb4f8513416809662d68e0cbcf5cc41ef61e06b5744c6680827cd6132a9f4d406a3a053c4a2
data/CHANGELOG.md CHANGED
@@ -7,6 +7,109 @@ 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
+
86
+ ## [0.59.0] - 2026-11-03
87
+
88
+ ### Added
89
+
90
+ - **E-mail addresses must end in an ICANN-registered TLD (on by default).** A sign-in code sent to
91
+ `jaryl@rarebit.ome` was accepted by the ESP and bounced hours later on the missing MX, so the user
92
+ just never got a code: every format check in use (`EmailIdentifier::EMAIL_FORMAT`, Truemail's
93
+ `:regex`, `URI::MailTo::EMAIL_REGEXP`) accepts any run of letters as a TLD. The new
94
+ `StandardId::EmailDomain.registered_tld?(email_or_domain)` checks the domain against the ICANN
95
+ section of the Public Suffix List, offline (no DNS), including punycode IDN TLDs such as
96
+ `xn--p1ai`. It is applied (a) when a passwordless code is requested on an `email` connection, web
97
+ and API, before the code is generated or any delivery event fires, and before the host's
98
+ `passwordless.username_validator` (which still runs after), failing with "rarebit.ome isn't a
99
+ valid e-mail domain. Check the address."; and (b) when a `StandardId::EmailIdentifier`'s value is
100
+ set or changed (error `:unregistered_tld`). Existing identifier rows are never re-checked. The
101
+ special-use TLDs (`test`, `example`, `invalid`, `localhost`, `local`) still pass, since
102
+ they are never delegated and apps use them on purpose for bot accounts and fixtures; change the
103
+ list with `c.email.allowed_special_use_tlds`. Turn the check off with
104
+ `c.email.require_registered_tld = false`. Host e-mail validators should call
105
+ `StandardId::EmailDomain.allowed?` (the gem's rule) so every path agrees;
106
+ `StandardId::EmailDomain.registered_tld?` is the strict ICANN-only predicate. `public_suffix`
107
+ (`>= 5.0, < 8`) is now an explicit dependency.
108
+ - **The login-verify page shows where the code went.** The built-in ERB view names the address and
109
+ links back to the login page ("Use a different e-mail"), and the Inertia props for
110
+ `login_verify/show` gain `identifier`, `channel` and `login_path` so host front ends can do the
111
+ same.
112
+
10
113
  ## [0.58.1] - 2026-10-30
11
114
 
12
115
  ### Fixed
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
@@ -776,6 +782,8 @@ Authentication pages receive the following props:
776
782
  | `enabled_social_providers` | `string[]` | Names of the enabled providers, e.g. `["google"]` — iterate this rather than hard-coding provider names |
777
783
  | `errors` | `object` | Validation errors (on form submission failures) |
778
784
 
785
+ The code-entry page (`login_verify/show`) instead receives `flash`, plus `identifier` (the address or phone number the code was sent to), `channel` (`"email"` or `"sms"`) and `login_path` (the engine's login page, mount path included). Show the address and link back to `login_path` ("Use a different e-mail"), so a user who mistyped it can see why no code arrived and start again; the built-in ERB view does this.
786
+
779
787
  #### Using Authentication in Host App Controllers
780
788
 
781
789
  You can use the `authenticate_account!` method in your own controllers to require authentication with Inertia-compatible redirects:
@@ -834,7 +842,10 @@ parent's `default from:` does not apply to them.
834
842
  Event payload includes:
835
843
  - `channel` - `"email"` or `"sms"`
836
844
  - `identifier` - The email address or phone number
837
- - `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`
838
849
  - `expires_at` - When the code expires
839
850
  - `realm` - The OTP realm (`"authentication"` for sign-in)
840
851
  - `skip_sender` - `true` for `Otp.issue(delivery: :manual)`; don't deliver
@@ -842,6 +853,18 @@ Event payload includes:
842
853
 
843
854
  > **Note**: `passwordless_email_sender` / `passwordless_sms_sender` were removed in 0.43; see the [Migration Guide](docs/MIGRATION_GUIDE.md).
844
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
+
845
868
  ### Starting a passwordless login from your own controller
846
869
 
847
870
  To send the code from your own controller (a sign-up form, an invite page) and
@@ -1014,7 +1037,8 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1014
1037
  | Credential | `credential.password.created` | `credential`, `account` | After a password credential is created |
1015
1038
  | | `credential.password.reset_initiated` | `credential`, `account`, `reset_token_expires_at` | After a password reset is initiated |
1016
1039
  | | `credential.password.reset_completed` | `credential`, `account` | After a password reset is confirmed |
1017
- | | `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 |
1018
1042
  | | `credential.client_secret.created` | `credential`, `client_id` | After a client secret is created |
1019
1043
  | | `credential.client_secret.rotated` | `credential`, `client_id`, `old_secret_revoked_at` | After a client secret rotation |
1020
1044
 
@@ -1879,7 +1903,7 @@ StandardId creates the following tables:
1879
1903
  - `standard_id_clients` - OAuth clients
1880
1904
  - `standard_id_client_secret_credentials` - Client secrets
1881
1905
  - `standard_id_password_credentials` - Password storage
1882
- - `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)
1883
1907
 
1884
1908
  ## API Endpoints
1885
1909
 
@@ -2146,6 +2170,27 @@ scoped login request instead. It replaces controller stubbing
2146
2170
  (`stub_web_authentication`, `allow_any_instance_of(...).to receive(:current_user)`)
2147
2171
  and per-app `/test/set-session` routes.
2148
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
+
2149
2194
  ### This gem's own suite
2150
2195
 
2151
2196
  StandardId includes comprehensive test coverage:
@@ -2172,6 +2217,38 @@ bundle exec rspec spec/controllers/
2172
2217
  requests that omit `code_challenge` for a PKCE-required client are
2173
2218
  rejected with `invalid_request`.
2174
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.
2175
2252
 
2176
2253
  ## OTP Start Limits
2177
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(
@@ -126,12 +126,18 @@ module StandardId
126
126
  )
127
127
  end
128
128
 
129
+ # identifier / channel / login_path let a front end show where the code
130
+ # went and offer a way back to correct it: a mistyped address otherwise
131
+ # looks exactly like a slow e-mail.
129
132
  def verify_page_props
130
133
  {
131
134
  flash: {
132
135
  notice: flash[:notice],
133
136
  alert: flash[:alert]
134
- }.compact
137
+ }.compact,
138
+ identifier: @otp_data[:username],
139
+ channel: @otp_data[:connection],
140
+ login_path: engine_path(login_path)
135
141
  }
136
142
  end
137
143
  end
@@ -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
@@ -24,5 +24,19 @@ module StandardId
24
24
  # actually edits the address. Without this, saving an unrelated attribute on
25
25
  # a grandfathered identifier would start raising.
26
26
  validates :value, format: { with: EMAIL_FORMAT }, if: :value_changed?
27
+
28
+ # The format above accepts any run of letters as a TLD, so "a@rarebit.ome"
29
+ # passes it. Same grandfathering: only a new or edited value is checked.
30
+ validate :value_has_registered_tld, if: :value_changed?
31
+
32
+ private
33
+
34
+ def value_has_registered_tld
35
+ return if value.blank? || errors.include?(:value)
36
+ return unless StandardId.config.email.require_registered_tld
37
+ return if StandardId::EmailDomain.allowed?(value)
38
+
39
+ errors.add(:value, :unregistered_tld, message: "has a domain that isn't a valid e-mail domain")
40
+ end
27
41
  end
28
42
  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