vp-login 0.4.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 +4 -4
- data/README.md +17 -0
- data/lib/vplogin/admin.rb +93 -26
- data/lib/vplogin/configuration.rb +18 -0
- data/lib/vplogin/controller.rb +62 -8
- data/lib/vplogin/devise_token_auth_controller.rb +17 -3
- data/lib/vplogin/devise_token_auth_logout.rb +24 -7
- data/lib/vplogin/devise_user.rb +71 -14
- data/lib/vplogin/discovery.rb +22 -6
- data/lib/vplogin/errors.rb +5 -0
- data/lib/vplogin/http.rb +39 -1
- data/lib/vplogin/log.rb +115 -0
- data/lib/vplogin/oidc.rb +89 -12
- data/lib/vplogin/password_check.rb +23 -6
- data/lib/vplogin/state_store.rb +23 -4
- data/lib/vplogin/tasks.rake +2 -0
- data/lib/vplogin/version.rb +1 -1
- data/lib/vplogin.rb +1 -0
- metadata +2 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: b836163c97c3a2b8140dd3cd4bbf6b53f79b3b48d43ab9170b0547ecb0a1a695
|
|
4
|
+
data.tar.gz: 359b8a9ad53488d797cca7f0b76b3bf7a62b9a2e3a9a7dd7aa7904ea801085b5
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 34f619fcf66267b02ca0d5cc9bd071436231860fc2dedfb80c3fec603d2ced223873f53b01b827a672f5413d03c30b26fdfe7094b580452702e9e7978551eb81
|
|
7
|
+
data.tar.gz: a73b9ca76ad6aa48ffea152ad7d541459b74d23300957d11b4a3e970b67b625d69e578e4c9c05ecc6d4f5a8e972f1cf9f7bb3a17cfc92bee36d0188674dc95d3
|
data/README.md
CHANGED
|
@@ -114,6 +114,23 @@ admin.revoke_sessions_for!(email:) # every device
|
|
|
114
114
|
|
|
115
115
|
Errors are `VpLogin::Error` subclasses with a `#code`.
|
|
116
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
|
+
|
|
117
134
|
## Releasing
|
|
118
135
|
|
|
119
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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))
|
|
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:))
|
|
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
|
-
|
|
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
|
-
|
|
95
|
-
|
|
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
|
-
|
|
147
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
data/lib/vplogin/controller.rb
CHANGED
|
@@ -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.
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
data/lib/vplogin/devise_user.rb
CHANGED
|
@@ -31,10 +31,14 @@ module VpLogin
|
|
|
31
31
|
end
|
|
32
32
|
|
|
33
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.
|
|
34
35
|
def vplogin_provision_later
|
|
35
|
-
|
|
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
|
|
36
40
|
|
|
37
|
-
enqueue = -> { VpLogin::ProvisionJob
|
|
41
|
+
enqueue = -> { vplogin_enqueue(VpLogin::ProvisionJob) }
|
|
38
42
|
if defined?(::ActiveRecord) && ::ActiveRecord.respond_to?(:after_all_transactions_commit)
|
|
39
43
|
::ActiveRecord.after_all_transactions_commit(&enqueue)
|
|
40
44
|
else
|
|
@@ -57,29 +61,63 @@ module VpLogin
|
|
|
57
61
|
private
|
|
58
62
|
|
|
59
63
|
def vplogin_sync_password
|
|
60
|
-
|
|
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
|
|
68
|
+
|
|
69
|
+
vplogin_enqueue(VpLogin::PasswordSyncJob)
|
|
70
|
+
end
|
|
61
71
|
|
|
62
|
-
|
|
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)
|
|
63
80
|
end
|
|
64
81
|
end
|
|
65
82
|
|
|
66
83
|
class UserJob < ActiveJob::Base
|
|
67
84
|
queue_as { VpLogin.configuration.job_queue }
|
|
68
85
|
|
|
69
|
-
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
|
|
70
100
|
|
|
71
101
|
private
|
|
72
102
|
|
|
73
103
|
def find_user(user_class_name, user_id)
|
|
74
|
-
|
|
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
|
|
75
107
|
|
|
76
|
-
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
|
|
77
111
|
end
|
|
78
112
|
|
|
79
113
|
def sync_password(admin, user)
|
|
80
|
-
|
|
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
|
|
81
117
|
|
|
82
|
-
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
|
|
83
121
|
end
|
|
84
122
|
end
|
|
85
123
|
|
|
@@ -96,29 +134,48 @@ module VpLogin
|
|
|
96
134
|
email_mfa: VpLogin.configuration.provision_email_mfa)
|
|
97
135
|
warn_mfa_error(user, result.mfa_error) if result.mfa_error
|
|
98
136
|
user.vplogin_identity_linked(result.pk)
|
|
137
|
+
VpLogin::Log.info('job.provision.linked', user_id: user.id, pk: result.pk, created: result.created)
|
|
99
138
|
|
|
100
|
-
|
|
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')
|
|
143
|
+
end
|
|
101
144
|
import_mfa(admin, user, result.pk)
|
|
102
145
|
end
|
|
103
146
|
|
|
104
147
|
private
|
|
105
148
|
|
|
106
149
|
def import_password(admin, user, result)
|
|
107
|
-
|
|
108
|
-
|
|
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
|
|
109
157
|
|
|
158
|
+
VpLogin::Log.debug('job.provision.password_import', user_id: user.id, pk: result.pk, created: result.created)
|
|
110
159
|
admin.set_password_hash!(result.pk, password_hash: "bcrypt$#{user.encrypted_password}")
|
|
111
160
|
end
|
|
112
161
|
|
|
113
162
|
def import_mfa(admin, user, pk)
|
|
114
163
|
devices = user.vplogin_mfa_devices.to_h.compact
|
|
115
|
-
|
|
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
|
|
116
171
|
|
|
172
|
+
VpLogin::Log.debug('job.provision.mfa_import', user_id: user.id, pk:, devices: devices.keys)
|
|
117
173
|
admin.import_mfa_devices!(pk, **devices)
|
|
118
174
|
end
|
|
119
175
|
|
|
120
176
|
def warn_mfa_error(user, error)
|
|
121
|
-
VpLogin.
|
|
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))
|
|
122
179
|
end
|
|
123
180
|
end
|
|
124
181
|
|
data/lib/vplogin/discovery.rb
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
27
|
-
|
|
28
|
-
|
|
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
|
|
data/lib/vplogin/errors.rb
CHANGED
|
@@ -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
|
-
|
|
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.
|
data/lib/vplogin/log.rb
ADDED
|
@@ -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
|
-
|
|
34
|
-
|
|
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
|
-
|
|
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
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
22
|
-
|
|
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
|
-
|
|
36
|
+
final = post(url, { password: }, cookie)
|
|
37
|
+
body = parse(final.body)
|
|
28
38
|
errors = body['response_errors']
|
|
29
|
-
|
|
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
|
-
|
|
54
|
+
Log.error('password_check.failed', config: @config, exception: e, flow: @flow)
|
|
38
55
|
false
|
|
39
56
|
end
|
|
40
57
|
|
data/lib/vplogin/state_store.rb
CHANGED
|
@@ -25,9 +25,11 @@ module VpLogin
|
|
|
25
25
|
|
|
26
26
|
# Without consuming it, for callers that must refuse before spending the state.
|
|
27
27
|
def read_attempt(state)
|
|
28
|
-
return
|
|
28
|
+
return invalid_id(:attempt, state) unless state.is_a?(String) && state.match?(ID_FORMAT)
|
|
29
29
|
|
|
30
|
-
@config.cache.read(key(:attempt, state))
|
|
30
|
+
@config.cache.read(key(:attempt, state)).tap do |value|
|
|
31
|
+
Log.debug('state.read', config: @config, kind: :attempt, id: Log.fingerprint(state), found: !value.nil?)
|
|
32
|
+
end
|
|
31
33
|
end
|
|
32
34
|
|
|
33
35
|
def write_handoff(attempt)
|
|
@@ -43,18 +45,35 @@ module VpLogin
|
|
|
43
45
|
private
|
|
44
46
|
|
|
45
47
|
def write(kind, id, value, ttl)
|
|
46
|
-
@config.cache.write(key(kind, id), value, expires_in: ttl)
|
|
48
|
+
written = @config.cache.write(key(kind, id), value, expires_in: ttl)
|
|
49
|
+
Log.debug('state.write', config: @config, kind:, id: Log.fingerprint(id), ttl:,
|
|
50
|
+
fields: value.respond_to?(:keys) ? value.keys : nil, cache: @config.cache.class.name)
|
|
51
|
+
# Rails cache stores return false when the write failed (e.g. Redis down, value unserializable).
|
|
52
|
+
Log.error('state.write_failed', config: @config, report: true, kind:, id: Log.fingerprint(id), cache: @config.cache.class.name) if written == false
|
|
53
|
+
written
|
|
47
54
|
end
|
|
48
55
|
|
|
56
|
+
# A miss is an expired, already-used or never-issued id - or a cache not shared between the
|
|
57
|
+
# process that wrote it and this one.
|
|
49
58
|
def take(kind, id)
|
|
50
|
-
return
|
|
59
|
+
return invalid_id(kind, id) unless id.is_a?(String) && id.match?(ID_FORMAT)
|
|
51
60
|
|
|
52
61
|
cache_key = key(kind, id)
|
|
53
62
|
value = @config.cache.read(cache_key)
|
|
54
63
|
@config.cache.delete(cache_key) unless value.nil?
|
|
64
|
+
if value.nil?
|
|
65
|
+
Log.warn('state.miss', config: @config, kind:, id: Log.fingerprint(id), cache: @config.cache.class.name)
|
|
66
|
+
else
|
|
67
|
+
Log.debug('state.take', config: @config, kind:, id: Log.fingerprint(id))
|
|
68
|
+
end
|
|
55
69
|
value
|
|
56
70
|
end
|
|
57
71
|
|
|
72
|
+
def invalid_id(kind, id)
|
|
73
|
+
Log.warn('state.invalid_id', config: @config, kind:, type: id.class.name, length: id.to_s.length)
|
|
74
|
+
nil
|
|
75
|
+
end
|
|
76
|
+
|
|
58
77
|
def key(kind, id)
|
|
59
78
|
"#{@config.cache_namespace}:#{kind}:#{id}"
|
|
60
79
|
end
|
data/lib/vplogin/tasks.rake
CHANGED
|
@@ -27,6 +27,7 @@ namespace :vplogin do
|
|
|
27
27
|
VpLogin::ProvisionJob.perform_later(user.class.name, user.id)
|
|
28
28
|
count += 1
|
|
29
29
|
end
|
|
30
|
+
VpLogin::Log.info('task.migrate_users.enqueued', count:, queue: VpLogin.configuration.job_queue)
|
|
30
31
|
puts "Enqueued #{count} VpLogin::ProvisionJob jobs on #{VpLogin.configuration.job_queue}"
|
|
31
32
|
end
|
|
32
33
|
|
|
@@ -49,6 +50,7 @@ namespace :vplogin do
|
|
|
49
50
|
end
|
|
50
51
|
rescue VpLogin::Error => e
|
|
51
52
|
counts[:errors] += 1
|
|
53
|
+
VpLogin::Log.error('task.migration_status.failed', exception: e, user_id: user.id)
|
|
52
54
|
warn "#{user.email}: #{e.class}: #{e.message}"
|
|
53
55
|
end
|
|
54
56
|
|
data/lib/vplogin/version.rb
CHANGED
data/lib/vplogin.rb
CHANGED
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: vp-login
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.4.
|
|
4
|
+
version: 0.4.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Volopay
|
|
@@ -119,6 +119,7 @@ files:
|
|
|
119
119
|
- lib/vplogin/discovery.rb
|
|
120
120
|
- lib/vplogin/errors.rb
|
|
121
121
|
- lib/vplogin/http.rb
|
|
122
|
+
- lib/vplogin/log.rb
|
|
122
123
|
- lib/vplogin/memory_cache.rb
|
|
123
124
|
- lib/vplogin/oidc.rb
|
|
124
125
|
- lib/vplogin/password_check.rb
|