standard_id 0.59.0 → 0.61.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +110 -0
  3. data/README.md +121 -8
  4. data/app/controllers/concerns/standard_id/social_authentication.rb +5 -4
  5. data/app/controllers/concerns/standard_id/web_authentication.rb +2 -0
  6. data/app/forms/standard_id/web/reset_password_confirm_form.rb +2 -1
  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/password_credential.rb +141 -0
  12. data/app/models/standard_id/session.rb +22 -12
  13. data/app/views/standard_id/account_notice_mailer/password_changed.html.erb +22 -0
  14. data/app/views/standard_id/account_notice_mailer/password_changed.text.erb +10 -0
  15. data/config/locales/en.yml +7 -0
  16. data/db/migrate/20261122000000_add_code_digest_to_standard_id_code_challenges.rb +24 -0
  17. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +20 -0
  18. data/lib/standard_id/config/callable_validator.rb +26 -3
  19. data/lib/standard_id/config/schema.rb +56 -0
  20. data/lib/standard_id/email_password/authentication.rb +8 -2
  21. data/lib/standard_id/email_password/password_reset.rb +2 -1
  22. data/lib/standard_id/email_password/verification.rb +5 -1
  23. data/lib/standard_id/engine.rb +1 -0
  24. data/lib/standard_id/error_reporting.rb +38 -0
  25. data/lib/standard_id/events/definitions.rb +5 -0
  26. data/lib/standard_id/events/subscribers/password_changed_notice_subscriber.rb +42 -0
  27. data/lib/standard_id/events.rb +47 -0
  28. data/lib/standard_id/health_contributions.rb +27 -0
  29. data/lib/standard_id/http_client.rb +39 -6
  30. data/lib/standard_id/keyed_digest.rb +65 -0
  31. data/lib/standard_id/oauth/password_flow.rb +1 -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 +4 -0
  37. metadata +11 -3
@@ -6,7 +6,54 @@ module StandardId
6
6
  # Event namespace prefix for all StandardId events
7
7
  NAMESPACE = "standard_id"
8
8
 
9
+ # Event names worth an audit row, as Regexps and full Strings that both
10
+ # ActiveSupport::Notifications and standard_audit's `subscribe_to` accept.
11
+ # See `.auditable`.
12
+ AUDITABLE = [
13
+ # What the apps subscribed to before this list existed.
14
+ /\Astandard_id\.authentication\./,
15
+ "#{NAMESPACE}.#{SESSION_CREATED}",
16
+ "#{NAMESPACE}.#{SESSION_REVOKED}",
17
+ "#{NAMESPACE}.#{SESSION_EXPIRED}",
18
+ /\Astandard_id\.account\./,
19
+ /\Astandard_id\.social\./,
20
+ /\Astandard_id\.passwordless\./,
21
+ # Changes to how an account or client authenticates. (Not
22
+ # CREDENTIAL_PASSWORD_REHASHED: the password itself is unchanged.)
23
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_CREATED}",
24
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_RESET_INITIATED}",
25
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_RESET_COMPLETED}",
26
+ "#{NAMESPACE}.#{CREDENTIAL_PASSWORD_CHANGED}",
27
+ "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_CREATED}",
28
+ "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_ROTATED}",
29
+ "#{NAMESPACE}.#{CREDENTIAL_CLIENT_SECRET_REVOKED}",
30
+ # OAuth: token theft and revocation, a token sent to the wrong resource,
31
+ # and changes to who may request tokens at all.
32
+ "#{NAMESPACE}.#{OAUTH_REFRESH_TOKEN_REUSE_DETECTED}",
33
+ "#{NAMESPACE}.#{OAUTH_TOKEN_REVOKED}",
34
+ "#{NAMESPACE}.#{OAUTH_AUDIENCE_MISMATCH}",
35
+ "#{NAMESPACE}.#{OAUTH_CLIENT_REGISTERED}",
36
+ "#{NAMESPACE}.#{OAUTH_CLIENT_UPDATED}",
37
+ "#{NAMESPACE}.#{OAUTH_CLIENT_DEREGISTERED}"
38
+ ].map(&:freeze).freeze
39
+
9
40
  class << self
41
+ # The event names a host should persist to its audit log:
42
+ #
43
+ # StandardAudit.configure do |config|
44
+ # StandardId::Events.auditable.each { |pattern| config.subscribe_to(pattern) }
45
+ # end
46
+ #
47
+ # Deliberately left out: per-request noise (session.validating /
48
+ # validated), high-volume token minting (oauth.token.issued,
49
+ # oauth.token.refreshed), and the benign refresh race
50
+ # (oauth.refresh_token.reuse_graced).
51
+ #
52
+ # @return [Array<Regexp, String>] frozen
53
+ def auditable
54
+ AUDITABLE
55
+ end
56
+
10
57
  # Publish an event with the given name and payload
11
58
  #
12
59
  # @param event_name [String, Symbol] The event name (use constants from Definitions)
@@ -0,0 +1,27 @@
1
+ # What StandardId offers standard_health, through its load hook. There is no
2
+ # dependency either way: without standard_health (or with a version older than
3
+ # the hook) the block never runs. With it, the block runs once, whichever gem
4
+ # is required first, and receives standard_health's contribution registry,
5
+ # which exposes only `contribute_check` and `contribute_env_vars`.
6
+ #
7
+ # Apps still decide: the check registers through `register_default_checks`
8
+ # (opt out with `standard_id_migrations: false`), and an env var the app
9
+ # declares in its own env_spec wins over the declaration here.
10
+ ActiveSupport.on_load(:standard_health) do |health|
11
+ # Resolved by name when the check runs, so nothing here loads it early.
12
+ health.contribute_check :standard_id_migrations, "StandardId::Checks::Migrations", critical: false
13
+
14
+ # APP_ENVIRONMENT is the one deploy variable StandardId reads itself.
15
+ # STANDARD_ID_BYPASS_CODE it never reads, but its production guard names it
16
+ # and the apps feed c.passwordless.bypass_code from it. Provider credentials (GOOGLE_CLIENT_ID, APPLE_PRIVATE_KEY, ...) are not
17
+ # declared here: which apply depends on the plugins an app registers.
18
+ health.contribute_env_vars "standard_id" do
19
+ recommended :APP_ENVIRONMENT,
20
+ description: "Decides StandardId's production-only guards (the bypass-code refusal, the empty " \
21
+ "allowed_audiences warning, provider_misconfiguration = :raise). Any value other than staging, " \
22
+ "preview, development or test counts as production; unset falls back to Rails.env"
23
+ forbidden :STANDARD_ID_BYPASS_CODE, in: %w[production],
24
+ description: "Conventional source for c.passwordless.bypass_code, a fixed OTP for e2e tests. StandardId " \
25
+ "refuses to verify any code in production while a bypass code is configured"
26
+ end
27
+ end
@@ -23,19 +23,33 @@ module StandardId
23
23
  IPAddr.new("fe80::/10")
24
24
  ].freeze
25
25
 
26
+ # Provider name passed to `StandardId.config.network_wrapper` when a caller
27
+ # does not name one.
28
+ DEFAULT_PROVIDER = :standard_id
29
+
26
30
  class << self
27
- def post_form(endpoint, params)
31
+ # `provider:` names the remote service (`:google`, `:apple`, ...) for
32
+ # `StandardId.config.network_wrapper`, e.g. to keep one circuit per
33
+ # provider. It has no other effect on the request.
34
+ #
35
+ # The form may also come as bare keywords (`post_form(url, id_token: t)`),
36
+ # which is how callers written before `provider:` existed pass it: once
37
+ # the method takes a keyword, Ruby reads a braceless Hash as keywords, so
38
+ # `**form` keeps those calls working. A form field named `provider` must
39
+ # therefore go in an explicit Hash. With no bare keywords, `params` goes
40
+ # to `set_form_data` as given, so an Array of pairs keeps repeated keys.
41
+ def post_form(endpoint, params = nil, provider: DEFAULT_PROVIDER, **form)
28
42
  uri, resolved_ip = validate_url!(endpoint)
29
43
  request = Net::HTTP::Post.new(uri)
30
- request.set_form_data(params)
31
- start_connection(uri, resolved_ip:) { |http| http.request(request) }
44
+ request.set_form_data(form.empty? ? (params || {}) : (params || {}).to_h.merge(form))
45
+ start_connection(uri, resolved_ip:, provider:) { |http| http.request(request) }
32
46
  end
33
47
 
34
- def get_with_bearer(endpoint, access_token)
48
+ def get_with_bearer(endpoint, access_token, provider: DEFAULT_PROVIDER)
35
49
  uri, resolved_ip = validate_url!(endpoint)
36
50
  request = Net::HTTP::Get.new(uri)
37
51
  request["Authorization"] = "Bearer #{access_token}"
38
- start_connection(uri, resolved_ip:) { |http| http.request(request) }
52
+ start_connection(uri, resolved_ip:, provider:) { |http| http.request(request) }
39
53
  end
40
54
 
41
55
  private
@@ -59,7 +73,26 @@ module StandardId
59
73
  [uri, addresses.first]
60
74
  end
61
75
 
62
- def start_connection(uri, resolved_ip: nil, &block)
76
+ # Private, but provider plugins call it through `send` to fetch a JWKS
77
+ # with a plain GET, so its signature is part of the plugin contract:
78
+ # `provider:` is optional and new keywords must stay optional.
79
+ def start_connection(uri, resolved_ip: nil, provider: DEFAULT_PROVIDER, &block)
80
+ with_network_wrapper(provider) { open_connection(uri, resolved_ip:, &block) }
81
+ end
82
+
83
+ # Runs the block through `StandardId.config.network_wrapper`, or
84
+ # directly when none is configured. The wrapper sees the whole
85
+ # connection (connect, request, response), so a timeout or refused
86
+ # connection raises inside it; whatever it raises or returns is the
87
+ # caller's.
88
+ def with_network_wrapper(provider, &block)
89
+ wrapper = StandardId.config.network_wrapper
90
+ return yield unless wrapper.respond_to?(:call)
91
+
92
+ wrapper.call(**StandardId::Utils::CallableParameterFilter.filter(wrapper, { provider: provider&.to_sym }), &block)
93
+ end
94
+
95
+ def open_connection(uri, resolved_ip: nil, &block)
63
96
  http = Net::HTTP.new(uri.host, uri.port)
64
97
  http.use_ssl = (uri.scheme == "https")
65
98
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER if http.use_ssl?
@@ -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.61.0"
3
3
  end
data/lib/standard_id.rb CHANGED
@@ -14,7 +14,10 @@ require "standard_id/association_strict_loading"
14
14
  require "standard_id/migration_check"
15
15
  require "standard_id/migration_helpers"
16
16
  require "standard_id/checks/migrations"
17
+ require "standard_id/health_contributions"
17
18
  require "standard_id/errors"
19
+ require "standard_id/error_reporting"
20
+ require "standard_id/keyed_digest"
18
21
  require "standard_id/events"
19
22
  require "standard_id/events/subscribers/base"
20
23
  require "standard_id/events/subscribers/logging_subscriber"
@@ -22,6 +25,7 @@ require "standard_id/events/subscribers/account_status_subscriber"
22
25
  require "standard_id/events/subscribers/account_locking_subscriber"
23
26
  require "standard_id/events/subscribers/passwordless_delivery_subscriber"
24
27
  require "standard_id/events/subscribers/password_reset_delivery_subscriber"
28
+ require "standard_id/events/subscribers/password_changed_notice_subscriber"
25
29
  require "standard_id/account_status"
26
30
  require "standard_id/account_locking"
27
31
  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.61.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
@@ -305,6 +308,7 @@ files:
305
308
  - lib/standard_id/email_password/token_flow.rb
306
309
  - lib/standard_id/email_password/verification.rb
307
310
  - lib/standard_id/engine.rb
311
+ - lib/standard_id/error_reporting.rb
308
312
  - lib/standard_id/errors.rb
309
313
  - lib/standard_id/events.rb
310
314
  - lib/standard_id/events/definitions.rb
@@ -313,11 +317,14 @@ files:
313
317
  - lib/standard_id/events/subscribers/account_status_subscriber.rb
314
318
  - lib/standard_id/events/subscribers/base.rb
315
319
  - lib/standard_id/events/subscribers/logging_subscriber.rb
320
+ - lib/standard_id/events/subscribers/password_changed_notice_subscriber.rb
316
321
  - lib/standard_id/events/subscribers/password_reset_delivery_subscriber.rb
317
322
  - lib/standard_id/events/subscribers/passwordless_delivery_subscriber.rb
323
+ - lib/standard_id/health_contributions.rb
318
324
  - lib/standard_id/http_client.rb
319
325
  - lib/standard_id/instrumentation.rb
320
326
  - lib/standard_id/jwt_service.rb
327
+ - lib/standard_id/keyed_digest.rb
321
328
  - lib/standard_id/login_method_policy.rb
322
329
  - lib/standard_id/migration_check.rb
323
330
  - lib/standard_id/migration_helpers.rb
@@ -370,6 +377,7 @@ files:
370
377
  - lib/standard_id/testing/factories/oauth.rb
371
378
  - lib/standard_id/testing/factories/sessions.rb
372
379
  - lib/standard_id/testing/factory_bot.rb
380
+ - lib/standard_id/testing/otp_helpers.rb
373
381
  - lib/standard_id/testing/provider_examples.rb
374
382
  - lib/standard_id/testing/request_helpers.rb
375
383
  - lib/standard_id/token_minter.rb
@@ -403,7 +411,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
403
411
  - !ruby/object:Gem::Version
404
412
  version: '0'
405
413
  requirements: []
406
- rubygems_version: 4.0.10
414
+ rubygems_version: 4.0.20
407
415
  specification_version: 4
408
416
  summary: A comprehensive authentication engine for Rails, built on the security primitives
409
417
  introduced in Rails 8.