vp-login 0.3.0 → 0.4.1

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.
@@ -6,25 +6,39 @@ module VpLogin
6
6
  # Include in the app's Devise user model to keep its vpLogin identity in step:
7
7
  #
8
8
  # user.vplogin_provision_later # e.g. on invite: create (or find) the vpLogin identity
9
+ # rake vplogin:migrate_users # the same for every existing user (vplogin/tasks.rake)
9
10
  #
10
11
  # and, automatically, any saved password change (set, change, reset) is copied to vpLogin as its
11
12
  # bcrypt hash. Creates are not synced: an app's new-user password is typically a throwaway.
12
- # Both run as ActiveJob jobs and do nothing without the admin API.
13
+ # All of it runs as ActiveJob jobs and does nothing without the admin API.
13
14
  #
14
15
  # Overridable:
15
- # vplogin_name -> display name for a new identity (full_name / name / email)
16
- # vplogin_password_set? -> true once the user chose their own password, so provisioning
17
- # copies it too (default false)
16
+ # vplogin_name -> display name for a new identity (full_name / name / email)
17
+ # vplogin_password_set? -> true once the user chose their own password, so provisioning
18
+ # copies it to an identity that has none (default false)
19
+ # vplogin_mfa_devices -> { totp_secret_base32:, phone_number:, email_device: } to import
20
+ # into an identity with no MFA device yet (default nil: none)
21
+ # vplogin_identity_linked(pk) -> store the vpLogin user id, if the app keeps one (default no-op)
22
+ # self.vplogin_migration_scope -> users rake vplogin:migrate_users covers (default all)
18
23
  module DeviseUser
19
24
  def self.included(base)
20
25
  base.after_commit :vplogin_sync_password, on: :update, if: :saved_change_to_encrypted_password?
26
+ base.extend(ClassMethods)
27
+ end
28
+
29
+ module ClassMethods
30
+ def vplogin_migration_scope = all
21
31
  end
22
32
 
23
33
  # Enqueued after the surrounding transactions commit, so the job can find the user.
34
+ # Never raises: a failure to enqueue is logged, so it can't fail the invite it hangs off.
24
35
  def vplogin_provision_later
25
- return unless VpLogin.configuration.admin_api?
36
+ unless VpLogin.configuration.admin_api?
37
+ return VpLogin::Log.debug('user.provision_later.skipped', reason: 'admin API not configured',
38
+ model: self.class.name, user_id: id)
39
+ end
26
40
 
27
- enqueue = -> { VpLogin::ProvisionJob.perform_later(self.class.name, id) }
41
+ enqueue = -> { vplogin_enqueue(VpLogin::ProvisionJob) }
28
42
  if defined?(::ActiveRecord) && ::ActiveRecord.respond_to?(:after_all_transactions_commit)
29
43
  ::ActiveRecord.after_all_transactions_commit(&enqueue)
30
44
  else
@@ -41,36 +55,75 @@ module VpLogin
41
55
  end
42
56
 
43
57
  def vplogin_password_set? = false
58
+ def vplogin_mfa_devices = nil
59
+ def vplogin_identity_linked(_pk) = nil
44
60
 
45
61
  private
46
62
 
47
63
  def vplogin_sync_password
48
- return unless VpLogin.configuration.admin_api?
64
+ unless VpLogin.configuration.admin_api?
65
+ return VpLogin::Log.debug('user.password_sync.skipped', reason: 'admin API not configured',
66
+ model: self.class.name, user_id: id)
67
+ end
49
68
 
50
- VpLogin::PasswordSyncJob.perform_later(self.class.name, id)
69
+ vplogin_enqueue(VpLogin::PasswordSyncJob)
70
+ end
71
+
72
+ def vplogin_enqueue(job)
73
+ enqueued = job.perform_later(self.class.name, id)
74
+ VpLogin::Log.info('user.job_enqueued', job: job.name, model: self.class.name, user_id: id,
75
+ job_id: enqueued.try(:job_id), queue: VpLogin.configuration.job_queue,
76
+ enqueued: enqueued != false)
77
+ enqueued
78
+ rescue StandardError => e
79
+ VpLogin::Log.error('user.job_enqueue_failed', exception: e, job: job.name, model: self.class.name, user_id: id)
51
80
  end
52
81
  end
53
82
 
54
83
  class UserJob < ActiveJob::Base
55
84
  queue_as { VpLogin.configuration.job_queue }
56
85
 
57
- retry_on VpLogin::HttpError, VpLogin::ProvisioningError, wait: ->(executions) { (executions**4) + 2 }, attempts: 5
86
+ retry_on VpLogin::HttpError, VpLogin::Unavailable, VpLogin::ProvisioningError, wait: ->(executions) { (executions**4) + 2 }, attempts: 5
87
+
88
+ around_perform do |job, block|
89
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
90
+ context = { job: job.class.name, job_id: job.job_id, args: job.arguments, attempt: job.executions }
91
+ VpLogin::Log.debug('job.start', **context)
92
+ block.call
93
+ VpLogin::Log.info('job.done', **context, ms: ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round)
94
+ rescue StandardError => e
95
+ VpLogin::Log.error('job.failed', **context, exception: e, report: false,
96
+ will_retry: e.is_a?(VpLogin::HttpError) || e.is_a?(VpLogin::Unavailable) ||
97
+ e.is_a?(VpLogin::ProvisioningError))
98
+ raise
99
+ end
58
100
 
59
101
  private
60
102
 
61
103
  def find_user(user_class_name, user_id)
62
- return unless VpLogin.configuration.admin_api?
104
+ unless VpLogin.configuration.admin_api?
105
+ return VpLogin::Log.warn('job.skipped', job: self.class.name, reason: 'admin API not configured', user_id:)
106
+ end
63
107
 
64
- user_class_name.constantize.find_by(id: user_id)
108
+ user_class_name.constantize.find_by(id: user_id).tap do |user|
109
+ VpLogin::Log.warn('job.user_not_found', job: self.class.name, model: user_class_name, user_id:) if user.nil?
110
+ end
65
111
  end
66
112
 
67
113
  def sync_password(admin, user)
68
- return if user.encrypted_password.to_s.empty?
114
+ if user.encrypted_password.to_s.empty?
115
+ return VpLogin::Log.info('job.password_sync.skipped', reason: 'no encrypted_password', user_id: user.id)
116
+ end
69
117
 
70
- admin.sync_bcrypt_password!(email: user.email, bcrypt_hash: user.encrypted_password)
118
+ admin.sync_bcrypt_password!(email: user.email, bcrypt_hash: user.encrypted_password).tap do |synced|
119
+ VpLogin::Log.info('job.password_sync', user_id: user.id, synced:)
120
+ end
71
121
  end
72
122
  end
73
123
 
124
+ # Creates (or finds) the user's vpLogin identity, then fills in what it lacks: the password and MFA
125
+ # devices are imported only into an identity without them, so a password or factor the person
126
+ # already has in vpLogin (e.g. from another Volopay app) is never overwritten. Safe to re-run.
74
127
  class ProvisionJob < UserJob
75
128
  def perform(user_class_name, user_id)
76
129
  user = find_user(user_class_name, user_id)
@@ -79,11 +132,50 @@ module VpLogin
79
132
  admin = VpLogin::Admin.new
80
133
  result = admin.provision_user!(email: user.email, name: user.vplogin_name,
81
134
  email_mfa: VpLogin.configuration.provision_email_mfa)
82
- if result.mfa_error
83
- VpLogin.configuration.logger.warn("[VpLogin] email MFA factor failed for #{user.email}: #{result.mfa_error.message}")
135
+ warn_mfa_error(user, result.mfa_error) if result.mfa_error
136
+ user.vplogin_identity_linked(result.pk)
137
+ VpLogin::Log.info('job.provision.linked', user_id: user.id, pk: result.pk, created: result.created)
138
+
139
+ if user.vplogin_password_set?
140
+ import_password(admin, user, result)
141
+ else
142
+ VpLogin::Log.debug('job.provision.password_skipped', user_id: user.id, reason: 'vplogin_password_set? is false')
84
143
  end
85
- # A password chosen before the identity existed had nothing to sync to.
86
- sync_password(admin, user) if user.vplogin_password_set?
144
+ import_mfa(admin, user, result.pk)
145
+ end
146
+
147
+ private
148
+
149
+ def import_password(admin, user, result)
150
+ if user.encrypted_password.to_s.empty?
151
+ return VpLogin::Log.info('job.provision.password_skipped', user_id: user.id, reason: 'no encrypted_password')
152
+ end
153
+ unless result.created || result.identity['has_usable_password'] == false
154
+ return VpLogin::Log.info('job.provision.password_skipped', user_id: user.id, pk: result.pk,
155
+ reason: 'identity already has a password')
156
+ end
157
+
158
+ VpLogin::Log.debug('job.provision.password_import', user_id: user.id, pk: result.pk, created: result.created)
159
+ admin.set_password_hash!(result.pk, password_hash: "bcrypt$#{user.encrypted_password}")
160
+ end
161
+
162
+ def import_mfa(admin, user, pk)
163
+ devices = user.vplogin_mfa_devices.to_h.compact
164
+ if devices.empty?
165
+ return VpLogin::Log.debug('job.provision.mfa_skipped', user_id: user.id, reason: 'no devices from vplogin_mfa_devices')
166
+ end
167
+ if (existing = admin.mfa_devices(pk)).any?
168
+ return VpLogin::Log.info('job.provision.mfa_skipped', user_id: user.id, pk:, reason: 'identity already has MFA devices',
169
+ existing: existing.map { |d| d[:endpoint] || d[:type] })
170
+ end
171
+
172
+ VpLogin::Log.debug('job.provision.mfa_import', user_id: user.id, pk:, devices: devices.keys)
173
+ admin.import_mfa_devices!(pk, **devices)
174
+ end
175
+
176
+ def warn_mfa_error(user, error)
177
+ VpLogin::Log.warn('job.provision.email_mfa_failed', exception: error, report: false, user_id: user.id,
178
+ email: VpLogin::Log.mask_email(user.email))
87
179
  end
88
180
  end
89
181
 
@@ -9,13 +9,20 @@ module VpLogin
9
9
 
10
10
  def document
11
11
  @config.cache.fetch(key(:discovery), expires_in: @config.metadata_ttl) do
12
- @http.get_json!(@config.discovery_url)
12
+ Log.debug('discovery.fetch', config: @config, url: @config.discovery_url, ttl: @config.metadata_ttl)
13
+ @http.get_json!(@config.discovery_url).tap do |doc|
14
+ Log.info('discovery.fetched', config: @config, issuer: doc.is_a?(Hash) ? doc['issuer'] : nil,
15
+ keys: doc.is_a?(Hash) ? doc.keys.size : nil)
16
+ end
13
17
  end
14
18
  end
15
19
 
16
20
  def [](name)
17
21
  value = document[name.to_s]
18
- raise ConfigurationError, "vpLogin discovery document has no #{name}" if value.to_s.empty?
22
+ if value.to_s.empty?
23
+ Log.error('discovery.missing_field', config: @config, field: name.to_s, url: @config.discovery_url)
24
+ raise ConfigurationError, "vpLogin discovery document has no #{name}"
25
+ end
19
26
 
20
27
  value
21
28
  end
@@ -23,13 +30,22 @@ module VpLogin
23
30
  # Refetching on an unknown `kid` handles key rotation. The cooldown stops a stream of tokens
24
31
  # with made-up kids from turning into a stream of JWKS requests against vpLogin.
25
32
  def jwks(refresh: false)
26
- if refresh && refresh_allowed?
27
- @config.cache.write(key(:jwks_refreshed_at), Time.now.to_i, expires_in: @config.jwks_refresh_cooldown)
28
- @config.cache.delete(key(:jwks))
33
+ if refresh
34
+ if refresh_allowed?
35
+ Log.info('discovery.jwks_refresh', config: @config, reason: 'unknown kid')
36
+ @config.cache.write(key(:jwks_refreshed_at), Time.now.to_i, expires_in: @config.jwks_refresh_cooldown)
37
+ @config.cache.delete(key(:jwks))
38
+ else
39
+ Log.warn('discovery.jwks_refresh_skipped', config: @config, reason: 'cooldown',
40
+ cooldown: @config.jwks_refresh_cooldown)
41
+ end
29
42
  end
30
43
 
31
44
  @config.cache.fetch(key(:jwks), expires_in: @config.metadata_ttl) do
32
- @http.get_json!(self['jwks_uri'])
45
+ @http.get_json!(self['jwks_uri']).tap do |jwks|
46
+ kids = jwks.is_a?(Hash) ? Array(jwks['keys']).map { |k| k['kid'] } : []
47
+ Log.info('discovery.jwks_fetched', config: @config, kids:)
48
+ end
33
49
  end
34
50
  end
35
51
 
@@ -23,6 +23,11 @@ module VpLogin
23
23
  def code = 'VPLOGIN_UNAVAILABLE'
24
24
  end
25
25
 
26
+ # vpLogin couldn't be reached at all: refused, timed out, DNS or TLS failure.
27
+ class Unavailable < Error
28
+ def code = 'VPLOGIN_UNAVAILABLE'
29
+ end
30
+
26
31
  # Unknown, expired or already-used state / handoff code, or an app PKCE verifier that doesn't match.
27
32
  class InvalidAttempt < Error
28
33
  def code = 'INVALID_LOGIN_ATTEMPT'
data/lib/vplogin/http.rb CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  module VpLogin
4
4
  class Http
5
+ NETWORK_ERRORS = [SocketError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError, IOError,
6
+ Net::ProtocolError].freeze
7
+
5
8
  def initialize(config = VpLogin.configuration)
6
9
  @config = config
7
10
  end
@@ -17,6 +20,9 @@ module VpLogin
17
20
  headers.each { |key, value| request[key] = value }
18
21
  request.body = body if body
19
22
 
23
+ Log.debug('http.request', config: @config, method: method.to_s.upcase, url: strip_query(url),
24
+ query_keys: query&.keys, body_bytes: body&.bytesize,
25
+ open_timeout: @config.open_timeout, read_timeout: @config.read_timeout)
20
26
  started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
21
27
  response = Net::HTTP.start(uri.host, uri.port,
22
28
  use_ssl: uri.scheme == 'https',
@@ -26,8 +32,15 @@ module VpLogin
26
32
  end
27
33
  log(method, url, response.code, started)
28
34
  response
35
+ rescue *NETWORK_ERRORS => e
36
+ log(method, url, e.class.name, started) if started
37
+ Log.warn('http.unreachable', config: @config, method: method.to_s.upcase, url: strip_query(url),
38
+ error: e.class.name, message: e.message)
39
+ raise Unavailable, "vpLogin unreachable (#{strip_query(url)}): #{e.class}"
29
40
  rescue StandardError => e
30
41
  log(method, url, e.class.name, started) if started
42
+ Log.error('http.failed', config: @config, method: method.to_s.upcase, url: strip_query(url),
43
+ error: e.class.name, message: e.message)
31
44
  raise
32
45
  end
33
46
 
@@ -50,10 +63,35 @@ module VpLogin
50
63
  def json!(response, url)
51
64
  status = response.code.to_i
52
65
  # Never put the body in the message: token and admin responses carry secrets.
53
- raise HttpError.new(status, response.body, url: strip_query(url)) unless (200..299).cover?(status)
66
+ unless (200..299).cover?(status)
67
+ log_error_response(status, response, url)
68
+ raise HttpError.new(status, response.body, url: strip_query(url))
69
+ end
54
70
  return nil if status == 204 || response.body.to_s.strip.empty?
55
71
 
56
72
  JSON.parse(response.body)
73
+ rescue JSON::ParserError => e
74
+ Log.error('http.invalid_json', config: @config, url: strip_query(url), status:,
75
+ content_type: response['content-type'], body_bytes: response.body.to_s.bytesize,
76
+ message: e.message[0, 120])
77
+ raise
78
+ end
79
+
80
+ # Error bodies (OAuth `error`, admin API `detail`/field errors) carry no secrets, but only their
81
+ # error fields are logged, never the whole body.
82
+ ERROR_FIELDS = %w[error error_description detail non_field_errors code].freeze
83
+
84
+ def log_error_response(status, response, url)
85
+ parsed = begin
86
+ JSON.parse(response.body.to_s)
87
+ rescue JSON::ParserError
88
+ nil
89
+ end
90
+ details = parsed.is_a?(Hash) ? parsed.slice(*ERROR_FIELDS) : {}
91
+ Log.warn('http.error_response', config: @config, url: strip_query(url), status:,
92
+ body_bytes: response.body.to_s.bytesize,
93
+ error_fields: parsed.is_a?(Hash) ? parsed.keys.first(10) : nil,
94
+ **details.transform_keys(&:to_sym).transform_values { |v| v.to_s[0, 200] })
57
95
  end
58
96
 
59
97
  # Method, path and outcome only: queries carry emails and codes, bodies carry tokens.
@@ -0,0 +1,115 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # One-line, greppable log entries: `[VpLogin] <event> key=value key=value`.
5
+ #
6
+ # VpLogin::Log.debug('oidc.start', state: Log.fingerprint(state), prompt:)
7
+ #
8
+ # Never pass tokens, authorization/handoff codes, PKCE verifiers, passwords, password hashes or
9
+ # the API token. For a secret that must be correlated across lines use `fingerprint`; for an
10
+ # email use `mask_email`.
11
+ #
12
+ # Debug entries go to `logger.debug`, so they only show when the app's logger is at debug level.
13
+ # `config.debug_logging = true` (or VPLOGIN_DEBUG=true) writes them at info instead, to trace
14
+ # logins in an environment whose logger is at info.
15
+ #
16
+ # Passing `exception:` also reports it to the error tracker (Sentry when it's initialized, else
17
+ # Rails.error; see Configuration#error_reporter), tagged with the event and the same context.
18
+ # `report: false` logs it without reporting (expected, user-caused failures); `report: true` with
19
+ # no exception reports the event as a message. Reporting never raises into the app.
20
+ module Log
21
+ LEVELS = %i[debug info warn error].freeze
22
+
23
+ class << self
24
+ LEVELS.each do |level|
25
+ define_method(level) do |event, config: VpLogin.configuration, exception: nil, report: nil, **context|
26
+ context = { error: exception.class.name, message: exception.message }.merge(context) if exception
27
+ write(level, event, config, context)
28
+ deliver(event, exception, level, config, context) if report.nil? ? exception : report
29
+ nil
30
+ end
31
+ end
32
+
33
+ # Stable short id for a secret (state, handoff code, token client): the same value always
34
+ # gives the same 8 characters, which can't be turned back into the value.
35
+ def fingerprint(value)
36
+ return nil if value.nil? || value.to_s.empty?
37
+
38
+ Digest::SHA256.hexdigest(value.to_s)[0, 8]
39
+ end
40
+
41
+ # "jane@example.test" -> "ja**@example.test"
42
+ def mask_email(email)
43
+ return nil if email.nil?
44
+
45
+ local, domain = email.to_s.strip.split('@', 2)
46
+ return '[invalid]' if domain.nil? || local.to_s.empty?
47
+
48
+ visible = local[0, [local.length - 1, 2].min]
49
+ "#{visible}#{'*' * [local.length - visible.length, 2].max}@#{domain}"
50
+ end
51
+
52
+ def format(event, context)
53
+ pairs = context.filter_map do |key, value|
54
+ next if value.nil?
55
+
56
+ "#{key}=#{format_value(value)}"
57
+ end
58
+ ["[VpLogin] #{event}", *pairs].join(' ')
59
+ end
60
+
61
+ private
62
+
63
+ def deliver(event, exception, level, config, context)
64
+ reporter = config.error_reporter
65
+ return if reporter == false
66
+
67
+ context = context.merge(event:)
68
+ if reporter
69
+ reporter.call(exception || event, context)
70
+ elsif sentry?
71
+ sentry_report(event, exception, level, context)
72
+ elsif defined?(::Rails) && ::Rails.respond_to?(:error) && exception
73
+ ::Rails.error.report(exception, handled: true, severity: level == :warn ? :warning : :error,
74
+ context: { vplogin: context }, source: 'vplogin')
75
+ end
76
+ rescue StandardError => e
77
+ write(:warn, 'log.report_failed', config, { event:, error: e.class.name, message: e.message })
78
+ end
79
+
80
+ def sentry?
81
+ defined?(::Sentry) && ::Sentry.respond_to?(:initialized?) && ::Sentry.initialized?
82
+ end
83
+
84
+ def sentry_report(event, exception, level, context)
85
+ ::Sentry.with_scope do |scope|
86
+ scope.set_tags(vplogin_event: event)
87
+ scope.set_context('vplogin', context.transform_values { |v| v.is_a?(Exception) ? v.message : v })
88
+ scope.set_level(level == :warn ? :warning : :error)
89
+ exception ? ::Sentry.capture_exception(exception) : ::Sentry.capture_message("[VpLogin] #{event}")
90
+ end
91
+ end
92
+
93
+ def write(level, event, config, context)
94
+ logger = config.logger
95
+ return if logger.nil?
96
+
97
+ level = :info if level == :debug && config.debug_logging
98
+ logger.public_send(level) { format(event, context) }
99
+ rescue StandardError
100
+ nil # logging must never break a login
101
+ end
102
+
103
+ def format_value(value)
104
+ case value
105
+ when String then value.match?(/[\s"=]/) || value.empty? ? value.inspect : value
106
+ when Symbol, Numeric, true, false then value.to_s
107
+ when Array then "[#{value.map { |v| format_value(v) }.join(',')}]"
108
+ when Hash then "{#{value.map { |k, v| "#{k}:#{format_value(v)}" }.join(',')}}"
109
+ when Exception then "#{value.class}(#{value.message})".inspect
110
+ else value.to_s.inspect
111
+ end
112
+ end
113
+ end
114
+ end
115
+ end
data/lib/vplogin/oidc.rb CHANGED
@@ -30,8 +30,14 @@ module VpLogin
30
30
  # app_challenge: PKCE challenge from a native app; verify then requires its verifier.
31
31
  def start(data: {}, login_hint: nil, prompt: nil, state_prefix: nil, app_challenge: nil, extra_params: {})
32
32
  config.require!(:client_id, :redirect_uri)
33
- raise ArgumentError, 'invalid state_prefix' if state_prefix && !state_prefix.to_s.match?(PREFIX_FORMAT)
34
- raise ArgumentError, "invalid prompt #{prompt.inspect}" if prompt && !PROMPTS.include?(prompt.to_s)
33
+ if state_prefix && !state_prefix.to_s.match?(PREFIX_FORMAT)
34
+ Log.error('oidc.start.invalid_state_prefix', config:, state_prefix: state_prefix.to_s[0, 70])
35
+ raise ArgumentError, 'invalid state_prefix'
36
+ end
37
+ if prompt && !PROMPTS.include?(prompt.to_s)
38
+ Log.error('oidc.start.invalid_prompt', config:, prompt: prompt.to_s[0, 30])
39
+ raise ArgumentError, "invalid prompt #{prompt.inspect}"
40
+ end
35
41
 
36
42
  state = [state_prefix, SecureRandom.hex(16)].compact.join('_')
37
43
  nonce = SecureRandom.hex(16)
@@ -55,7 +61,14 @@ module VpLogin
55
61
  query[:prompt] = prompt if prompt
56
62
  query.merge!(extra_params)
57
63
 
58
- Start.new(url: "#{@discovery['authorization_endpoint']}?#{URI.encode_www_form(query)}", state:)
64
+ authorize_url = "#{@discovery['authorization_endpoint']}?#{URI.encode_www_form(query)}"
65
+ Log.info('oidc.start', config:, state: Log.fingerprint(state), state_prefix:,
66
+ login_hint: Log.mask_email(login_hint), prompt:, app_challenge: !app_challenge.nil?,
67
+ data_keys: data.respond_to?(:keys) ? data.keys : nil, scope: config.scopes,
68
+ redirect_uri: config.redirect_uri, extra_params: extra_params.keys)
69
+ Log.debug('oidc.start.authorize_endpoint', config:, url: @discovery['authorization_endpoint'])
70
+
71
+ Start.new(url: authorize_url, state:)
59
72
  end
60
73
 
61
74
  def self.state_prefix(state)
@@ -69,29 +82,57 @@ module VpLogin
69
82
  end
70
83
 
71
84
  def callback(state:, code:, error: nil, error_description: nil)
85
+ Log.debug('oidc.callback', config:, state: Log.fingerprint(state), state_prefix: self.class.state_prefix(state),
86
+ code: !code.to_s.empty?, error:)
72
87
  attempt = @store.take_attempt(state.to_s)
73
- raise AuthorizationDenied.new(error, error_description) if error
74
- raise InvalidAttempt, 'unknown or expired state' if attempt.nil?
75
- raise InvalidAttempt, 'callback carried no code' if code.to_s.empty?
88
+ if error
89
+ Log.warn('oidc.callback.denied', config:, state: Log.fingerprint(state), error:,
90
+ error_description: error_description.to_s[0, 200], attempt_found: !attempt.nil?)
91
+ raise AuthorizationDenied.new(error, error_description)
92
+ end
93
+ if attempt.nil?
94
+ Log.warn('oidc.callback.unknown_state', config:, state: Log.fingerprint(state),
95
+ hint: 'expired (state_ttl), reused, or cache not shared between processes',
96
+ state_ttl: config.state_ttl)
97
+ raise InvalidAttempt, 'unknown or expired state'
98
+ end
99
+ if code.to_s.empty?
100
+ Log.warn('oidc.callback.no_code', config:, state: Log.fingerprint(state))
101
+ raise InvalidAttempt, 'callback carried no code'
102
+ end
76
103
 
77
- Callback.new(handoff_code: @store.write_handoff(attempt.merge(code: code.to_s)), attempt:)
104
+ handoff_code = @store.write_handoff(attempt.merge(code: code.to_s))
105
+ Log.info('oidc.callback.ok', config:, state: Log.fingerprint(state), handoff: Log.fingerprint(handoff_code),
106
+ login_hint: Log.mask_email(attempt[:login_hint]), app_challenge: !attempt[:app_challenge].nil?)
107
+ Callback.new(handoff_code:, attempt:)
78
108
  end
79
109
 
80
110
  # Consumes the handoff code. Any failure after this point needs a fresh login.
81
111
  def redeem(handoff_code, app_verifier: nil)
112
+ Log.debug('oidc.redeem', config:, handoff: Log.fingerprint(handoff_code), app_verifier: !app_verifier.to_s.empty?)
82
113
  attempt = @store.take_handoff(handoff_code.to_s)
83
- raise InvalidAttempt, 'unknown or expired handoff code' if attempt.nil?
114
+ if attempt.nil?
115
+ Log.warn('oidc.redeem.unknown_handoff', config:, handoff: Log.fingerprint(handoff_code),
116
+ hint: 'expired (handoff_ttl), reused, or cache not shared between processes',
117
+ handoff_ttl: config.handoff_ttl)
118
+ raise InvalidAttempt, 'unknown or expired handoff code'
119
+ end
84
120
 
85
121
  if attempt[:app_challenge] && !Pkce.verifier_matches?(attempt[:app_challenge], app_verifier)
122
+ Log.warn('oidc.redeem.app_verifier_mismatch', config:, handoff: Log.fingerprint(handoff_code),
123
+ app_verifier: !app_verifier.to_s.empty?)
86
124
  raise InvalidAttempt, 'app PKCE verifier did not match'
87
125
  end
88
126
 
127
+ Log.debug('oidc.redeem.ok', config:, handoff: Log.fingerprint(handoff_code),
128
+ login_hint: Log.mask_email(attempt[:login_hint]))
89
129
  attempt
90
130
  end
91
131
 
92
132
  def exchange(code:, code_verifier:, nonce:)
93
133
  config.require!(:client_id, :client_secret, :redirect_uri)
94
134
 
135
+ Log.debug('oidc.exchange', config:, token_endpoint: @discovery['token_endpoint'], redirect_uri: config.redirect_uri)
95
136
  tokens = @http.post_form!(@discovery['token_endpoint'], {
96
137
  grant_type: 'authorization_code',
97
138
  code:,
@@ -101,11 +142,26 @@ module VpLogin
101
142
  code_verifier:
102
143
  })
103
144
 
145
+ Log.debug('oidc.exchange.ok', config:, fields: tokens.respond_to?(:keys) ? tokens.keys : nil,
146
+ token_type: tokens.is_a?(Hash) ? tokens['token_type'] : nil,
147
+ expires_in: tokens.is_a?(Hash) ? tokens['expires_in'] : nil)
104
148
  verify_id_token(tokens && tokens['id_token'], nonce:)
149
+ rescue HttpError => e
150
+ Log.warn('oidc.exchange.failed', config:, status: e.status,
151
+ hint: e.status == 400 ? 'code expired/reused, redirect_uri or PKCE verifier mismatch' : nil)
152
+ raise
105
153
  end
106
154
 
107
155
  def verify_id_token(id_token, nonce:)
108
- raise InvalidToken, 'token response had no id_token' if id_token.to_s.empty?
156
+ if id_token.to_s.empty?
157
+ Log.error('oidc.id_token.missing', config:)
158
+ raise InvalidToken, 'token response had no id_token'
159
+ end
160
+
161
+ header = unverified_header(id_token)
162
+ Log.debug('oidc.id_token.verify', config:, alg: header['alg'], kid: header['kid'],
163
+ allowed_algs: config.id_token_algorithms, issuer: @discovery['issuer'],
164
+ audience: config.client_id, leeway: config.clock_skew)
109
165
 
110
166
  payload, = JWT.decode(
111
167
  id_token, nil, true,
@@ -118,23 +174,44 @@ module VpLogin
118
174
  )
119
175
 
120
176
  # Ties the token to this login attempt; without it a token from another attempt could be replayed.
121
- raise InvalidToken, 'nonce mismatch' unless OpenSSL.secure_compare(payload['nonce'].to_s, nonce.to_s)
177
+ unless OpenSSL.secure_compare(payload['nonce'].to_s, nonce.to_s)
178
+ Log.warn('oidc.id_token.nonce_mismatch', config:, token_nonce: !payload['nonce'].to_s.empty?)
179
+ raise InvalidToken, 'nonce mismatch'
180
+ end
122
181
 
123
182
  if payload['aud'].is_a?(Array) && payload['aud'].size > 1 && payload['azp'] != config.client_id
183
+ Log.warn('oidc.id_token.azp_mismatch', config:, aud: payload['aud'], azp: payload['azp'])
124
184
  raise InvalidToken, 'azp does not match client_id'
125
185
  end
126
186
 
127
- Claims.new(payload)
187
+ Claims.new(payload).tap do |claims|
188
+ Log.info('oidc.id_token.ok', config:, sub: claims.sub, email: Log.mask_email(claims.email),
189
+ amr: claims.amr, mfa: claims.mfa?, sid: !claims['sid'].to_s.empty?,
190
+ iat: payload['iat'], exp: payload['exp'], claims: payload.keys)
191
+ end
128
192
  rescue JWT::DecodeError => e
193
+ Log.warn('oidc.id_token.invalid', config:, error: e.class.name, message: e.message,
194
+ alg: header && header['alg'], kid: header && header['kid'],
195
+ server_time: Time.now.to_i)
129
196
  raise InvalidToken, e.message
130
197
  end
131
198
 
132
199
  private
133
200
 
201
+ # Header only, for logging alg/kid; the token itself is verified by JWT.decode.
202
+ def unverified_header(id_token)
203
+ _payload, header = JWT.decode(id_token.to_s, nil, false)
204
+ header.is_a?(Hash) ? header : {}
205
+ rescue JWT::DecodeError
206
+ {}
207
+ end
208
+
134
209
  # jwt 2.x passes `invalidate: true` on an unknown kid; 3.x also passes `kid_not_found: true`.
135
210
  def jwks_loader
136
211
  lambda do |options|
137
- @discovery.jwks(refresh: options[:invalidate] || options[:kid_not_found])
212
+ refresh = options[:invalidate] || options[:kid_not_found]
213
+ Log.info('oidc.id_token.unknown_kid', config:) if refresh
214
+ @discovery.jwks(refresh:)
138
215
  end
139
216
  end
140
217
  end
@@ -18,23 +18,40 @@ module VpLogin
18
18
 
19
19
  url = "#{@config.admin_base_url}/flows/executor/#{URI.encode_www_form_component(@flow)}/?query="
20
20
 
21
- cookie = cookies(@http.perform(:get, url))
22
- return false if cookie.empty?
21
+ masked = Log.mask_email(email)
22
+ Log.debug('password_check.start', config: @config, flow: @flow, email: masked)
23
+
24
+ start = @http.perform(:get, url)
25
+ cookie = cookies(start)
26
+ if cookie.empty?
27
+ Log.warn('password_check.no_session_cookie', config: @config, flow: @flow, status: start.code)
28
+ return false
29
+ end
23
30
 
24
31
  response = post(url, { uid_field: email }, cookie)
32
+ Log.debug('password_check.identified', config: @config, status: response.code,
33
+ component: parse(response.body)['component'])
25
34
  cookie = cookies(response).then { |fresh| fresh.empty? ? cookie : fresh }
26
35
 
27
- body = parse(post(url, { password: }, cookie).body)
36
+ final = post(url, { password: }, cookie)
37
+ body = parse(final.body)
28
38
  errors = body['response_errors']
29
- return false unless errors.nil? || (errors.respond_to?(:empty?) && errors.empty?)
39
+ unless errors.nil? || (errors.respond_to?(:empty?) && errors.empty?)
40
+ Log.info('password_check.rejected', config: @config, email: masked, status: final.code,
41
+ error_fields: errors.respond_to?(:keys) ? errors.keys : nil)
42
+ return false
43
+ end
30
44
 
31
45
  # Only a completed flow means the password matched. Access denied (lockout), an error
32
46
  # screen, or a stage added later must not read as success.
33
- body['component'].to_s == SUCCESS_COMPONENT
47
+ (body['component'].to_s == SUCCESS_COMPONENT).tap do |valid|
48
+ Log.info('password_check.result', config: @config, email: masked, valid:, status: final.code,
49
+ component: body['component'])
50
+ end
34
51
  rescue ConfigurationError
35
52
  raise
36
53
  rescue StandardError => e
37
- @config.logger.error("[VpLogin::PasswordCheck] #{e.class}: #{e.message}")
54
+ Log.error('password_check.failed', config: @config, exception: e, flow: @flow)
38
55
  false
39
56
  end
40
57
 
@@ -6,5 +6,9 @@ module VpLogin
6
6
  require 'action_dispatch/routing/mapper'
7
7
  ActionDispatch::Routing::Mapper.include(VpLogin::Routes)
8
8
  end
9
+
10
+ rake_tasks do
11
+ load File.expand_path('tasks.rake', __dir__)
12
+ end
9
13
  end
10
14
  end