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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c4ae09a37c684fabb1ad0785244543d06f2dedd5677c082326e98cf4dfaca76b
4
- data.tar.gz: 95ffa6c00de23343793deca3cc8d22c3205ba6686d41f35727b7aa8290ea8444
3
+ metadata.gz: b836163c97c3a2b8140dd3cd4bbf6b53f79b3b48d43ab9170b0547ecb0a1a695
4
+ data.tar.gz: 359b8a9ad53488d797cca7f0b76b3bf7a62b9a2e3a9a7dd7aa7904ea801085b5
5
5
  SHA512:
6
- metadata.gz: 8e30bffd9319f637b6e780e52858edb1becc44029e2a9d40e62c4d9a4d3405a63db236c260ef205e07952ea6f3813d72a2ee06a95b62ea0eb03ee3abc922b077
7
- data.tar.gz: 6742ac424b91f9fb5f03cd2d023d0461874e61f818314a3e7aaca18c84bb64b6c8e3bc1e337497034f7970e3b3aa980136e8084be024ad838bd6cbcfffd82c76
6
+ metadata.gz: 34f619fcf66267b02ca0d5cc9bd071436231860fc2dedfb80c3fec603d2ced223873f53b01b827a672f5413d03c30b26fdfe7094b580452702e9e7978551eb81
7
+ data.tar.gz: a73b9ca76ad6aa48ffea152ad7d541459b74d23300957d11b4a3e970b67b625d69e578e4c9c05ecc6d4f5a8e972f1cf9f7bb3a17cfc92bee36d0188674dc95d3
data/README.md CHANGED
@@ -6,7 +6,7 @@ ID-token checks, Rails login endpoints, and the vpLogin admin API. Used by volo-
6
6
  ## Install
7
7
 
8
8
  ```ruby
9
- gem 'vp-login', '~> 0.3', require: 'vplogin'
9
+ gem 'vp-login', '~> 0.4', require: 'vplogin'
10
10
  ```
11
11
 
12
12
  It needs Ruby >= 3.1 and jwt 2.5–3.x; the controller needs Rails >= 7. It's published on
@@ -68,8 +68,26 @@ end
68
68
  user.vplogin_provision_later # on invite: create the vpLogin identity
69
69
  ```
70
70
 
71
- Both run as ActiveJob jobs on `config.job_queue`. Override `vplogin_name` /
72
- `vplogin_password_set?` on the model where the defaults don't fit.
71
+ Both run as ActiveJob jobs on `config.job_queue`.
72
+
73
+ ### Migrating existing users
74
+
75
+ ```bash
76
+ DRY_RUN=true bin/rails vplogin:migrate_users # count only
77
+ bin/rails vplogin:migrate_users # one provisioning job per user (IDS=1,2 to limit)
78
+ bin/rails vplogin:migration_status # identity + password / no password / missing
79
+ ```
80
+
81
+ Safe to re-run. A password or MFA device the person already has in vpLogin is never overwritten.
82
+ Model hooks for where the defaults don't fit:
83
+
84
+ | Hook | Default |
85
+ |---|---|
86
+ | `self.vplogin_migration_scope` | `all` |
87
+ | `vplogin_name` | `full_name`, `name`, then email |
88
+ | `vplogin_password_set?` | `false`: no password imported |
89
+ | `vplogin_mfa_devices` | `nil`, or `{ totp_secret_base32:, phone_number:, email_device: }` |
90
+ | `vplogin_identity_linked(pk)` | no-op; store the vpLogin user id here |
73
91
 
74
92
  ## Without the controller
75
93
 
@@ -96,6 +114,23 @@ admin.revoke_sessions_for!(email:) # every device
96
114
 
97
115
  Errors are `VpLogin::Error` subclasses with a `#code`.
98
116
 
117
+ ## Logging
118
+
119
+ Every step logs one line to `config.logger` (default `Rails.logger`), such as
120
+ `[VpLogin] oidc.callback.unknown_state state=1a2b3c4d hint="expired (state_ttl), ..."`.
121
+ Grep for `[VpLogin]`. The step-by-step trace is at debug level. Set `VPLOGIN_DEBUG=true`
122
+ (or `c.debug_logging = true`) to write it at info without changing the app's log level.
123
+ Tokens, codes, verifiers, passwords and the API token are never logged. State and handoff codes
124
+ appear only as 8-character fingerprints, so one login can be followed across requests, and
125
+ emails are masked (`ja**@example.test`).
126
+
127
+ The gem catches some errors itself, so they never reach the app. It reports those to Sentry
128
+ (when `Sentry` is initialized, otherwise `Rails.error`) with a `vplogin_event` tag and the log
129
+ context: vpLogin down or misconfigured, invalid ID tokens, failed sign-out session end, password
130
+ check and enqueue failures. An expired, cancelled or mismatched login is only logged. Reporting
131
+ never raises. To turn it off, set `c.error_reporter = false`; to use your own reporter, set
132
+ `c.error_reporter = ->(error, context) { ... }`.
133
+
99
134
  ## Releasing
100
135
 
101
136
  Bump `lib/vplogin/version.rb`, tag `vX.Y.Z`, then
data/lib/vplogin/admin.rb CHANGED
@@ -19,10 +19,16 @@ module VpLogin
19
19
 
20
20
  # vpLogin requires a unique username; the email is used for it. Returns nil if it already exists.
21
21
  def create_user!(email:, name:)
22
- request!(:post, '/core/users/', { username: email, name:, email:, is_active: true })
22
+ request!(:post, '/core/users/', { username: email, name:, email:, is_active: true }).tap do |identity|
23
+ log(:info, 'admin.user_created', email: Log.mask_email(email), pk: pk_of(identity))
24
+ end
23
25
  rescue HttpError => e
24
- raise unless e.status == 400 && e.body.to_s.include?('unique')
26
+ unless e.status == 400 && e.body.to_s.include?('unique')
27
+ log(:error, 'admin.user_create_failed', email: Log.mask_email(email), status: e.status)
28
+ raise
29
+ end
25
30
 
31
+ log(:info, 'admin.user_exists', email: Log.mask_email(email))
26
32
  nil
27
33
  end
28
34
 
@@ -36,9 +42,14 @@ module VpLogin
36
42
  # first - a retry after a failed link then finds the identity instead of losing it.
37
43
  # An email-factor failure doesn't stop provisioning; it comes back as `mfa_error`.
38
44
  def provision_user!(email:, name:, group: nil, email_mfa: false)
45
+ log(:debug, 'admin.provision', email: Log.mask_email(email), group:, email_mfa:)
39
46
  created = create_user!(email:, name:)
40
47
  identity = created || find_user(email:)
41
- raise ProvisioningError, "vpLogin reports #{email} exists but it could not be found" if identity.nil?
48
+ if identity.nil?
49
+ log(:error, 'admin.provision.not_found_after_exists', email: Log.mask_email(email),
50
+ hint: 'username differs from email, or user is filtered out')
51
+ raise ProvisioningError, "vpLogin reports #{email} exists but it could not be found"
52
+ end
42
53
 
43
54
  yield identity, !created.nil? if block_given?
44
55
  add_user_to_group!(identity['pk'], group_name: group) if group
@@ -47,17 +58,22 @@ module VpLogin
47
58
  if email_mfa && created
48
59
  begin
49
60
  import_mfa_devices!(identity['pk'], email_device: true)
50
- rescue HttpError => e
51
- logger.error("[VpLogin::Admin] email MFA factor for #{identity['pk']} failed: #{e.message}")
61
+ rescue HttpError, Unavailable => e
62
+ log(:error, 'admin.provision.email_mfa_failed', exception: e, pk: identity['pk'])
52
63
  mfa_error = e
53
64
  end
54
65
  end
55
66
 
67
+ log(:info, 'admin.provisioned', pk: identity['pk'], email: Log.mask_email(email), created: !created.nil?,
68
+ group:, email_mfa: email_mfa && created ? mfa_error.nil? : nil,
69
+ has_usable_password: identity['has_usable_password'], is_active: identity['is_active'])
56
70
  Provisioned.new(identity:, created: !created.nil?, mfa_error:)
57
71
  end
58
72
 
59
73
  def find_user(email:)
60
- results(get('/core/users/', username: email)).first
74
+ users = results(get('/core/users/', username: email))
75
+ log(:debug, 'admin.find_user', email: Log.mask_email(email), matches: users.size, pk: pk_of(users.first))
76
+ users.first
61
77
  end
62
78
 
63
79
  def find_user_by_id(user_id)
@@ -66,15 +82,23 @@ module VpLogin
66
82
 
67
83
  # Exact, case-insensitive email matches. Re-checked locally rather than trusting the filter.
68
84
  def identities_for(email:)
69
- results(get('/core/users/', email:)).select { |u| u['email'].to_s.casecmp?(email.to_s) }
85
+ all = results(get('/core/users/', email:))
86
+ all.select { |u| u['email'].to_s.casecmp?(email.to_s) }.tap do |matches|
87
+ log(:debug, 'admin.identities_for', email: Log.mask_email(email), returned: all.size,
88
+ matches: matches.map { |u| u['pk'] })
89
+ end
70
90
  end
71
91
 
72
92
  def set_password!(user_id, password:)
73
- request!(:post, "/core/users/#{Integer(user_id)}/set_password/", { password: })
93
+ request!(:post, "/core/users/#{Integer(user_id)}/set_password/", { password: }).tap do
94
+ log(:info, 'admin.password_set', pk: user_id)
95
+ end
74
96
  end
75
97
 
76
98
  def set_password_hash!(user_id, password_hash:)
77
- request!(:post, "/core/users/#{Integer(user_id)}/set_password_hash/", { password: password_hash })
99
+ request!(:post, "/core/users/#{Integer(user_id)}/set_password_hash/", { password: password_hash }).tap do
100
+ log(:info, 'admin.password_hash_set', pk: user_id, scheme: password_hash.to_s.split('$', 2).first)
101
+ end
78
102
  end
79
103
 
80
104
  # Copies a Devise (bcrypt) password hash onto the identity with this email, so a password
@@ -82,7 +106,10 @@ module VpLogin
82
106
  # Returns false when vpLogin has no identity for the email.
83
107
  def sync_bcrypt_password!(email:, bcrypt_hash:)
84
108
  identity = find_user(email:)
85
- return false if identity.nil?
109
+ if identity.nil?
110
+ log(:warn, 'admin.password_sync.no_identity', email: Log.mask_email(email))
111
+ return false
112
+ end
86
113
 
87
114
  set_password_hash!(identity['pk'], password_hash: "bcrypt$#{bcrypt_hash}")
88
115
  true
@@ -90,9 +117,11 @@ module VpLogin
90
117
 
91
118
  # Fails open (true) when vpLogin can't be read, so a transient error doesn't hide password login.
92
119
  def password_set?(user_id)
93
- find_user_by_id(user_id)['has_usable_password'] != false
94
- rescue HttpError => e
95
- logger.error("[VpLogin::Admin] could not read password state for #{user_id}: #{e.message}")
120
+ (find_user_by_id(user_id)['has_usable_password'] != false).tap do |set|
121
+ log(:debug, 'admin.password_set?', pk: user_id, result: set)
122
+ end
123
+ rescue HttpError, Unavailable => e
124
+ log(:error, 'admin.password_state_unreadable', exception: e, pk: user_id, fallback: true)
96
125
  true
97
126
  end
98
127
 
@@ -106,6 +135,7 @@ module VpLogin
106
135
  end
107
136
 
108
137
  def merge_user_attributes!(user_id, changes)
138
+ log(:debug, 'admin.merge_attributes', pk: user_id, keys: changes.keys)
109
139
  replace_user_attributes!(user_id, user_attributes(user_id).merge(changes.transform_keys(&:to_s)))
110
140
  end
111
141
 
@@ -113,20 +143,28 @@ module VpLogin
113
143
 
114
144
  def import_mfa_devices!(user_id, phone_number: nil, totp_secret_base32: nil, email_device: false)
115
145
  payload = { email_device:, phone_number:, totp_secret_base32: }.compact
146
+ log(:debug, 'admin.import_mfa_devices', pk: user_id, email_device:, phone: !phone_number.nil?,
147
+ totp: !totp_secret_base32.nil?)
116
148
  response = request!(:post, "/core/users/#{Integer(user_id)}/import_mfa_devices/", payload)
117
- response.is_a?(Hash) ? response['created'] : []
149
+ (response.is_a?(Hash) ? response['created'] : []).tap do |created|
150
+ log(:info, 'admin.mfa_devices_imported', pk: user_id, created:)
151
+ end
118
152
  end
119
153
 
120
154
  def mfa_devices(user_id)
121
- results(get('/authenticators/admin/all/', user: Integer(user_id))).map do |device|
155
+ devices = results(get('/authenticators/admin/all/', user: Integer(user_id))).map do |device|
122
156
  { id: device['pk'], type: device['type'], endpoint: DEVICE_ENDPOINTS[device['type']] }
123
157
  end
158
+ log(:debug, 'admin.mfa_devices', pk: user_id, types: devices.map { |d| d[:endpoint] || d[:type] })
159
+ devices
124
160
  end
125
161
 
126
162
  def delete_mfa_device!(endpoint:, device_id:)
127
163
  raise ArgumentError, "unknown device endpoint #{endpoint.inspect}" unless DEVICE_ENDPOINTS.value?(endpoint)
128
164
 
129
- request!(:delete, "/authenticators/admin/#{endpoint}/#{Integer(device_id)}/")
165
+ request!(:delete, "/authenticators/admin/#{endpoint}/#{Integer(device_id)}/").tap do
166
+ log(:info, 'admin.mfa_device_deleted', endpoint:, device_id:)
167
+ end
130
168
  end
131
169
 
132
170
  # Groups (tenant links)
@@ -143,18 +181,30 @@ module VpLogin
143
181
  group = find_group(name: group_name) || create_group!(group_name)
144
182
 
145
183
  # Every member would inherit these; a tenant group must never carry them.
146
- raise GroupPermissionsCompromised.new(group: group_name, user_id:) if group['is_superuser'] || !Array(group['roles']).empty?
147
- return true if Array(group['users']).include?(Integer(user_id))
184
+ if group['is_superuser'] || !Array(group['roles']).empty?
185
+ log(:error, 'admin.group_compromised', group: group_name, group_pk: group['pk'],
186
+ is_superuser: group['is_superuser'], roles: Array(group['roles']).size, pk: user_id)
187
+ raise GroupPermissionsCompromised.new(group: group_name, user_id:)
188
+ end
189
+ if Array(group['users']).include?(Integer(user_id))
190
+ log(:debug, 'admin.group_already_member', group: group_name, group_pk: group['pk'], pk: user_id)
191
+ return true
192
+ end
148
193
 
149
194
  request!(:post, "/core/groups/#{group['pk']}/add_user/", { pk: Integer(user_id) })
195
+ log(:info, 'admin.group_user_added', group: group_name, group_pk: group['pk'], pk: user_id)
150
196
  true
151
197
  end
152
198
 
153
199
  def remove_user_from_group!(user_id, group_name:)
154
200
  group = find_group(name: group_name)
155
- return false if group.nil?
201
+ if group.nil?
202
+ log(:warn, 'admin.group_not_found', group: group_name, pk: user_id)
203
+ return false
204
+ end
156
205
 
157
206
  request!(:post, "/core/groups/#{group['pk']}/remove_user/", { pk: Integer(user_id) })
207
+ log(:info, 'admin.group_user_removed', group: group_name, group_pk: group['pk'], pk: user_id)
158
208
  true
159
209
  end
160
210
 
@@ -164,34 +214,45 @@ module VpLogin
164
214
  # session in the instance. Rows are re-checked against the identity's pk for the same reason.
165
215
  def sessions(email:)
166
216
  identities_for(email:).flat_map do |identity|
167
- results(get('/core/authenticated_sessions/', user__username: identity['username']))
168
- .select { |row| row['user'] == identity['pk'] }
217
+ rows = results(get('/core/authenticated_sessions/', user__username: identity['username']))
218
+ rows.select { |row| row['user'] == identity['pk'] }.tap do |own|
219
+ log(:debug, 'admin.sessions', pk: identity['pk'], returned: rows.size, matching: own.size)
220
+ end
169
221
  end
170
222
  end
171
223
 
172
224
  def revoke_session!(session_uuid)
173
- request!(:delete, "/core/authenticated_sessions/#{URI.encode_www_form_component(session_uuid.to_s)}/")
225
+ request!(:delete, "/core/authenticated_sessions/#{URI.encode_www_form_component(session_uuid.to_s)}/").tap do
226
+ log(:info, 'admin.session_revoked', session: Log.fingerprint(session_uuid))
227
+ end
174
228
  end
175
229
 
176
230
  # Ends only the session an ID token's `sid` names - one browser, not every device. Needs the
177
231
  # vpLogin `end_session` user action. Returns whether a live session was found and ended.
178
232
  def end_session!(user_id, sid:)
179
233
  response = request!(:post, "/core/users/#{Integer(user_id)}/end_session/", { sid: sid.to_s })
180
- response.is_a?(Hash) && response['ended'] == true
234
+ (response.is_a?(Hash) && response['ended'] == true).tap do |ended|
235
+ log(:info, 'admin.end_session', pk: user_id, sid: Log.fingerprint(sid), ended:)
236
+ end
181
237
  end
182
238
 
183
239
  def revoke_sessions_for!(email:)
184
- sessions(email:).each { |row| revoke_session!(row['uuid'] || row['pk']) }
240
+ sessions(email:).each { |row| revoke_session!(row['uuid'] || row['pk']) }.tap do |rows|
241
+ log(:info, 'admin.sessions_revoked', email: Log.mask_email(email), count: rows.size)
242
+ end
185
243
  end
186
244
 
187
245
  private
188
246
 
189
247
  # Concurrent callers can both miss find_group and race to create it.
190
248
  def create_group!(name)
191
- request!(:post, '/core/groups/', { name:, is_superuser: false })
249
+ request!(:post, '/core/groups/', { name:, is_superuser: false }).tap do |group|
250
+ log(:info, 'admin.group_created', group: name, group_pk: group.is_a?(Hash) ? group['pk'] : nil)
251
+ end
192
252
  rescue HttpError => e
193
253
  raise unless e.status == 400 && e.body.to_s.include?('already exists')
194
254
 
255
+ log(:info, 'admin.group_create_raced', group: name)
195
256
  find_group(name:) || raise
196
257
  end
197
258
 
@@ -218,6 +279,12 @@ module VpLogin
218
279
  { 'Authorization' => "Bearer #{@config.api_token}" }
219
280
  end
220
281
 
221
- def logger = @config.logger
282
+ def log(level, event, **context)
283
+ Log.public_send(level, event, config: @config, **context)
284
+ end
285
+
286
+ def pk_of(identity)
287
+ identity.is_a?(Hash) ? identity['pk'] : nil
288
+ end
222
289
  end
223
290
  end
@@ -44,8 +44,19 @@ module VpLogin
44
44
  # sets it (or VPLOGIN_PROVISION_EMAIL_MFA=true); otherwise MFA is left to vpLogin's flow.
45
45
  attr_writer :provision_email_mfa
46
46
 
47
+ # Write VpLogin's debug entries at info level, to trace logins without putting the whole app's
48
+ # logger at debug. Off unless set (or VPLOGIN_DEBUG=true). See VpLogin::Log.
49
+ attr_writer :debug_logging
50
+
47
51
  attr_writer :cache, :logger, :cache_namespace
48
52
 
53
+ # Where errors VpLogin handles itself (and so never reach the app) are reported:
54
+ # nil (default) - Sentry when it's initialized, else Rails.error
55
+ # false - nowhere, log only
56
+ # ->(error, context) { ... } - your own; `error` is the exception, or the event name when
57
+ # there is none; `context` is the log context (no secrets)
58
+ attr_accessor :error_reporter
59
+
49
60
  def initialize
50
61
  @scopes = 'openid email profile vp_auth_source'
51
62
  @frontend_callback_path = '/vplogin-login'
@@ -68,6 +79,12 @@ module VpLogin
68
79
  ENV.fetch('VPLOGIN_PROVISION_EMAIL_MFA', '').strip.casecmp?('true')
69
80
  end
70
81
 
82
+ def debug_logging
83
+ return @debug_logging unless @debug_logging.nil?
84
+
85
+ ENV.fetch('VPLOGIN_DEBUG', '').strip.casecmp?('true')
86
+ end
87
+
71
88
  # Per client_id by default, so apps sharing one cache never read each other's login state.
72
89
  def cache_namespace
73
90
  @cache_namespace || ['vplogin', client_id].compact.join(':')
@@ -102,6 +119,7 @@ module VpLogin
102
119
  missing = keys.select { |key| public_send(key).to_s.strip.empty? }
103
120
  return if missing.empty?
104
121
 
122
+ Log.error('config.missing', config: self, keys: missing)
105
123
  raise ConfigurationError, "VpLogin is missing configuration: #{missing.join(', ')}"
106
124
  end
107
125
 
@@ -15,14 +15,21 @@ module VpLogin
15
15
  #
16
16
  # Optional hooks (defaults below): vplogin_frontend_url, vplogin_handoff_url, vplogin_state_data,
17
17
  # vplogin_state_prefix, vplogin_login_hint, vplogin_prompt, vplogin_before_verify,
18
- # vplogin_user_not_found, vplogin_callback_failed, vplogin_verify_failed. Any hook may
18
+ # vplogin_user_not_found, vplogin_start_failed, vplogin_callback_failed, vplogin_verify_failed.
19
+ #
20
+ # Missing configuration or an unreachable vpLogin never raises out of an action: login and the
21
+ # callback send the browser back to the frontend login page with `sso_error=<code>`, XHR calls
22
+ # get a 503 JSON error. Any hook may
19
23
  # render/redirect; the action stops if it has.
20
24
  module Controller
21
25
  EMAIL_FORMAT = /\A[^@\s]+@[^@\s]+\z/
22
26
 
23
27
  def vplogin_start
28
+ vplogin_log(:debug, 'controller.start', format: request.format.to_s, browser: vplogin_browser_navigation?,
29
+ email_param: params[:email].present?, prompt_param: params[:prompt].presence,
30
+ app_challenge: params[:app_challenge].present?)
24
31
  data = vplogin_state_data
25
- return if performed?
32
+ return vplogin_log(:info, 'controller.start.halted_by_hook', hook: 'vplogin_state_data') if performed?
26
33
 
27
34
  start = vplogin_oidc.start(
28
35
  data:,
@@ -33,38 +40,55 @@ module VpLogin
33
40
  )
34
41
 
35
42
  if vplogin_browser_navigation?
43
+ vplogin_log(:debug, 'controller.start.redirect', state: VpLogin::Log.fingerprint(start.state))
36
44
  redirect_to start.url, allow_other_host: true
37
45
  else
46
+ vplogin_log(:debug, 'controller.start.json', state: VpLogin::Log.fingerprint(start.state))
38
47
  render json: { url: start.url }
39
48
  end
49
+ rescue VpLogin::Error => e
50
+ vplogin_start_failed(e)
40
51
  end
41
52
 
42
53
  def vplogin_callback
54
+ vplogin_log(:debug, 'controller.callback', state: VpLogin::Log.fingerprint(params[:state]),
55
+ code: params[:code].present?, error: params[:error].presence)
43
56
  result = vplogin_oidc.callback(
44
57
  state: params[:state], code: params[:code],
45
58
  error: params[:error].presence, error_description: params[:error_description].presence
46
59
  )
47
- redirect_to vplogin_handoff_url(result.handoff_code, result.attempt[:data] || {}), allow_other_host: true
60
+ handoff_url = vplogin_handoff_url(result.handoff_code, result.attempt[:data] || {})
61
+ vplogin_log(:debug, 'controller.callback.redirect', handoff: VpLogin::Log.fingerprint(result.handoff_code),
62
+ to: handoff_url.to_s.split('?').first)
63
+ redirect_to handoff_url, allow_other_host: true
48
64
  rescue VpLogin::Error => e
49
65
  vplogin_callback_failed(e, VpLogin::Oidc.state_prefix(params[:state]))
50
66
  end
51
67
 
52
68
  def vplogin_verify
69
+ vplogin_log(:debug, 'controller.verify', handoff: VpLogin::Log.fingerprint(params[:code]),
70
+ app_verifier: params[:app_verifier].present?)
53
71
  attempt = vplogin_oidc.redeem(params[:code], app_verifier: params[:app_verifier])
54
72
  data = attempt[:data] || {}
55
73
 
56
74
  vplogin_before_verify(data)
57
- return if performed?
75
+ return vplogin_log(:info, 'controller.verify.halted_by_hook', hook: 'vplogin_before_verify') if performed?
58
76
 
59
77
  claims = vplogin_oidc.exchange(code: attempt[:code], code_verifier: attempt[:code_verifier], nonce: attempt[:nonce])
60
78
  if attempt[:login_hint] && !claims.email_matches?(attempt[:login_hint])
79
+ vplogin_log(:warn, 'controller.verify.identity_mismatch', login_hint: VpLogin::Log.mask_email(attempt[:login_hint]),
80
+ email: VpLogin::Log.mask_email(claims.email), sub: claims.sub)
61
81
  raise VpLogin::IdentityMismatch, 'signed-in identity does not match login_hint'
62
82
  end
63
83
 
64
84
  user = vplogin_resolve_user(claims, data)
65
- return if performed?
66
- return vplogin_user_not_found(claims, data) if user.nil?
85
+ return vplogin_log(:info, 'controller.verify.halted_by_hook', hook: 'vplogin_resolve_user') if performed?
86
+ if user.nil?
87
+ vplogin_log(:warn, 'controller.verify.user_not_found', email: VpLogin::Log.mask_email(claims.email), sub: claims.sub)
88
+ return vplogin_user_not_found(claims, data)
89
+ end
67
90
 
91
+ vplogin_log(:info, 'controller.verify.sign_in', user_id: user.try(:id), sub: claims.sub, mfa: claims.mfa?)
68
92
  vplogin_sign_in(user, claims, data)
69
93
  rescue VpLogin::Error => e
70
94
  vplogin_verify_failed(e)
@@ -112,10 +136,19 @@ module VpLogin
112
136
  vplogin_render_error('No account found for this login.', 'USER_NOT_FOUND', :unauthorized, email: claims.email)
113
137
  end
114
138
 
139
+ def vplogin_start_failed(error)
140
+ vplogin_log(:error, 'controller.start.failed', exception: error, code: error.code)
141
+ login_page = vplogin_browser_navigation? && vplogin_frontend_page(VpLogin.configuration.frontend_login_path, sso_error: error.code)
142
+ return redirect_to(login_page, allow_other_host: true) if login_page
143
+
144
+ vplogin_render_error('Login with Volopay is unavailable right now', error.code, :service_unavailable)
145
+ end
146
+
115
147
  # The callback is a browser navigation from vpLogin, so with a frontend configured a failure
116
148
  # goes back to its login page instead of rendering JSON at the user.
117
149
  def vplogin_callback_failed(error, _state_prefix)
118
- VpLogin.configuration.logger.info("[VpLogin] callback failed: #{error.class}: #{error.message}")
150
+ vplogin_log(:warn, 'controller.callback.failed', exception: error, report: vplogin_report?(error), code: error.code,
151
+ redirect_to_frontend: !vplogin_frontend_url.to_s.empty?)
119
152
  login_page = vplogin_frontend_page(VpLogin.configuration.frontend_login_path, sso_error: error.code)
120
153
  return redirect_to(login_page, allow_other_host: true) if login_page
121
154
 
@@ -123,10 +156,26 @@ module VpLogin
123
156
  end
124
157
 
125
158
  def vplogin_verify_failed(error)
126
- VpLogin.configuration.logger.warn("[VpLogin] verify failed: #{error.class}: #{error.message}")
159
+ vplogin_log(:warn, 'controller.verify.failed', exception: error, report: vplogin_report?(error), code: error.code,
160
+ outage: vplogin_outage?(error))
161
+ if vplogin_outage?(error)
162
+ return vplogin_render_error('Login with Volopay is unavailable right now', error.code, :service_unavailable)
163
+ end
164
+
127
165
  vplogin_render_error('Login failed. Please try again', error.code, :unauthorized)
128
166
  end
129
167
 
168
+ # Sent to Sentry: vpLogin down or misconfigured, or an ID token that fails verification. Not a
169
+ # cancelled, expired or reused login, or a mismatched identity - those are the user's doing.
170
+ def vplogin_report?(error)
171
+ vplogin_outage?(error) || error.is_a?(VpLogin::InvalidToken) || error.is_a?(VpLogin::HttpError)
172
+ end
173
+
174
+ def vplogin_outage?(error)
175
+ error.is_a?(VpLogin::Unavailable) || error.is_a?(VpLogin::ConfigurationError) ||
176
+ (error.is_a?(VpLogin::HttpError) && error.status.to_i >= 500)
177
+ end
178
+
130
179
  # Same envelope devise_token_auth uses for its own failures.
131
180
  def vplogin_render_error(message, code, status, **extra)
132
181
  render json: { success: false, errors: [message], code: }.merge(extra), status:
@@ -139,6 +188,11 @@ module VpLogin
139
188
  "#{base}#{path}?#{URI.encode_www_form(query)}"
140
189
  end
141
190
 
191
+ def vplogin_log(level, event, **context)
192
+ VpLogin::Log.public_send(level, event, controller: self.class.name, request_id: request.try(:request_id), **context)
193
+ nil
194
+ end
195
+
142
196
  # Accept rather than a param: a link in an email or a redirect has no say in what it sends.
143
197
  def vplogin_browser_navigation?
144
198
  request.format.html? || request.headers['Accept'].to_s.include?('text/html')
@@ -17,18 +17,29 @@ module VpLogin
17
17
 
18
18
  # Email is the join: `sub` from a hashed_user_id provider can't be matched to anything local.
19
19
  def vplogin_resolve_user(claims, _data)
20
- return nil if claims.email.to_s.empty?
20
+ if claims.email.to_s.empty?
21
+ vplogin_log(:warn, 'devise.resolve_user.no_email_claim', sub: claims.sub, claims: claims.raw.keys)
22
+ return nil
23
+ end
21
24
 
22
- vplogin_user_class.find_by(email: claims.email.downcase)
25
+ vplogin_user_class.find_by(email: claims.email.downcase).tap do |user|
26
+ vplogin_log(:debug, 'devise.resolve_user', model: vplogin_user_class.name,
27
+ email: VpLogin::Log.mask_email(claims.email), user_id: user.try(:id))
28
+ end
23
29
  end
24
30
 
25
31
  def vplogin_sign_in(user, claims, data)
26
32
  if user.respond_to?(:active_for_authentication?) && !user.active_for_authentication?
33
+ vplogin_log(:info, 'devise.sign_in.inactive', user_id: user.try(:id),
34
+ reason: user.try(:inactive_message))
27
35
  return vplogin_render_error('Your account is inactive. Please contact support.', 'ACCOUNT_INACTIVE', :unauthorized)
28
36
  end
29
37
 
30
38
  vplogin_before_sign_in(user, claims, data)
31
- return if performed?
39
+ if performed?
40
+ return vplogin_log(:info, 'devise.sign_in.halted_by_hook', hook: 'vplogin_before_sign_in', user_id: user.try(:id),
41
+ status: response.status)
42
+ end
32
43
 
33
44
  # As create_new_auth_token, plus the ID token's sid on the token, so DeviseTokenAuthLogout can
34
45
  # end this browser's vpLogin session on sign-out.
@@ -36,6 +47,9 @@ module VpLogin
36
47
  @vplogin_client = token.client
37
48
  headers = user.update_auth_headers(token.token, token.client)
38
49
  response.headers.merge!(headers.compact.transform_values(&:to_s))
50
+ vplogin_log(:info, 'devise.sign_in.ok', user_id: user.try(:id), client: VpLogin::Log.fingerprint(token.client),
51
+ sid: claims['sid'] ? VpLogin::Log.fingerprint(claims['sid']) : nil,
52
+ mfa: claims.mfa?, tokens: user.tokens.try(:size))
39
53
  render json: vplogin_session_response(user, claims, data)
40
54
  end
41
55
 
@@ -16,21 +16,38 @@ module VpLogin
16
16
  private
17
17
 
18
18
  def vplogin_end_session
19
- return if @resource.nil?
20
-
21
19
  config = VpLogin.configuration
22
- return unless config.admin_api?
20
+ return VpLogin::Log.debug('logout.skipped', reason: 'no signed-in resource') if @resource.nil?
21
+ return VpLogin::Log.debug('logout.skipped', reason: 'admin API not configured', user_id: @resource.try(:id)) unless config.admin_api?
23
22
 
24
23
  client = (defined?(@token) && @token.respond_to?(:client) && @token.client) || request.headers['client']
25
24
  entry = (@resource.tokens || {})[client.to_s] || {}
26
25
  sid = entry['vplogin_sid'] || entry[:vplogin_sid]
27
- return if sid.to_s.empty?
26
+ if sid.to_s.empty?
27
+ return VpLogin::Log.debug('logout.skipped', reason: 'token has no vplogin_sid', user_id: @resource.try(:id),
28
+ client: VpLogin::Log.fingerprint(client), token_found: !entry.empty?)
29
+ end
28
30
 
29
- admin = VpLogin::Admin.new
31
+ VpLogin::Log.debug('logout.end_session', user_id: @resource.try(:id), client: VpLogin::Log.fingerprint(client),
32
+ sid: VpLogin::Log.fingerprint(sid))
33
+ admin = VpLogin::Admin.new(config: vplogin_logout_config(config))
30
34
  identity = admin.find_user(email: @resource.email)
31
- admin.end_session!(identity['pk'], sid:) if identity
35
+ if identity
36
+ ended = admin.end_session!(identity['pk'], sid:)
37
+ VpLogin::Log.info('logout.done', user_id: @resource.try(:id), pk: identity['pk'], ended:)
38
+ else
39
+ VpLogin::Log.warn('logout.no_identity', user_id: @resource.try(:id), email: VpLogin::Log.mask_email(@resource.email))
40
+ end
32
41
  rescue StandardError => e
33
- config.logger.error("[VpLogin] ending the vpLogin session on sign-out failed: #{e.class}: #{e.message}")
42
+ VpLogin::Log.error('logout.failed', exception: e, user_id: @resource.try(:id))
43
+ end
44
+
45
+ # Short timeouts: a slow or down vpLogin must not hold up the user's sign-out.
46
+ def vplogin_logout_config(config)
47
+ config.dup.tap do |c|
48
+ c.open_timeout = [config.open_timeout, 2].min
49
+ c.read_timeout = [config.read_timeout, 5].min
50
+ end
34
51
  end
35
52
  end
36
53
  end