vp-login 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # VpLogin::Controller with the sign-in implemented for devise_token_auth: finds the user by the
5
+ # verified email in `config.user_model`, issues a token into the response headers, and renders
6
+ # `{ success: true, data: user.token_validation_response }`.
7
+ #
8
+ # App hooks:
9
+ # vplogin_before_sign_in(user, claims, data) -> refuse (render) or prepare the user; runs
10
+ # before any token is issued
11
+ # vplogin_session_response(user, claims, data) -> body of the success response; the issued
12
+ # token's client is `vplogin_client`
13
+ module DeviseTokenAuthController
14
+ include VpLogin::Controller
15
+
16
+ private
17
+
18
+ # Email is the join: `sub` from a hashed_user_id provider can't be matched to anything local.
19
+ def vplogin_resolve_user(claims, _data)
20
+ return nil if claims.email.to_s.empty?
21
+
22
+ vplogin_user_class.find_by(email: claims.email.downcase)
23
+ end
24
+
25
+ def vplogin_sign_in(user, claims, data)
26
+ if user.respond_to?(:active_for_authentication?) && !user.active_for_authentication?
27
+ return vplogin_render_error('Your account is inactive. Please contact support.', 'ACCOUNT_INACTIVE', :unauthorized)
28
+ end
29
+
30
+ vplogin_before_sign_in(user, claims, data)
31
+ return if performed?
32
+
33
+ # As create_new_auth_token, plus the ID token's sid on the token, so DeviseTokenAuthLogout can
34
+ # end this browser's vpLogin session on sign-out.
35
+ token = user.create_token(updated_at: Time.now, **{ vplogin_sid: claims['sid'] }.compact)
36
+ @vplogin_client = token.client
37
+ headers = user.update_auth_headers(token.token, token.client)
38
+ response.headers.merge!(headers.compact.transform_values(&:to_s))
39
+ render json: vplogin_session_response(user, claims, data)
40
+ end
41
+
42
+ def vplogin_before_sign_in(_user, _claims, _data) = nil
43
+
44
+ attr_reader :vplogin_client
45
+
46
+ def vplogin_session_response(user, _claims, _data)
47
+ { success: true, data: user.token_validation_response }
48
+ end
49
+
50
+ def vplogin_user_class
51
+ model = VpLogin.configuration.user_model
52
+ model.is_a?(String) ? model.constantize : model
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # Include in the app's devise_token_auth SessionsController. Signing out then also ends the
5
+ # vpLogin session of this browser - the one the signed-out token was issued from (its `sid`,
6
+ # stored by DeviseTokenAuthController). Other devices stay signed in.
7
+ #
8
+ # Needs the admin API (VPLOGIN_ADMIN_API_URL / VPLOGIN_API_TOKEN) and vpLogin's end_session user
9
+ # API; without them it does nothing. It never fails the Volopay-side sign-out.
10
+ module DeviseTokenAuthLogout
11
+ def self.included(base)
12
+ # Declared after devise_token_auth's own set_user_by_token, so @resource/@token are set.
13
+ base.before_action :vplogin_end_session, only: :destroy
14
+ end
15
+
16
+ private
17
+
18
+ def vplogin_end_session
19
+ return if @resource.nil?
20
+
21
+ config = VpLogin.configuration
22
+ return unless config.admin_api?
23
+
24
+ client = (defined?(@token) && @token.respond_to?(:client) && @token.client) || request.headers['client']
25
+ entry = (@resource.tokens || {})[client.to_s] || {}
26
+ sid = entry['vplogin_sid'] || entry[:vplogin_sid]
27
+ return if sid.to_s.empty?
28
+
29
+ admin = VpLogin::Admin.new
30
+ identity = admin.find_user(email: @resource.email)
31
+ admin.end_session!(identity['pk'], sid:) if identity
32
+ rescue StandardError => e
33
+ config.logger.error("[VpLogin] ending the vpLogin session on sign-out failed: #{e.class}: #{e.message}")
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_job'
4
+
5
+ module VpLogin
6
+ # Include in the app's Devise user model to keep its vpLogin identity in step:
7
+ #
8
+ # user.vplogin_provision_later # e.g. on invite: create (or find) the vpLogin identity
9
+ #
10
+ # and, automatically, any saved password change (set, change, reset) is copied to vpLogin as its
11
+ # bcrypt hash. Creates are not synced: an app's new-user password is typically a throwaway.
12
+ # Both run as ActiveJob jobs and do nothing without the admin API.
13
+ #
14
+ # Overridable:
15
+ # vplogin_name -> display name for a new identity (full_name / name / email)
16
+ # vplogin_password_set? -> true once the user chose their own password, so provisioning
17
+ # copies it too (default false)
18
+ module DeviseUser
19
+ def self.included(base)
20
+ base.after_commit :vplogin_sync_password, on: :update, if: :saved_change_to_encrypted_password?
21
+ end
22
+
23
+ # Enqueued after the surrounding transactions commit, so the job can find the user.
24
+ def vplogin_provision_later
25
+ return unless VpLogin.configuration.admin_api?
26
+
27
+ enqueue = -> { VpLogin::ProvisionJob.perform_later(self.class.name, id) }
28
+ if defined?(::ActiveRecord) && ::ActiveRecord.respond_to?(:after_all_transactions_commit)
29
+ ::ActiveRecord.after_all_transactions_commit(&enqueue)
30
+ else
31
+ enqueue.call
32
+ end
33
+ end
34
+
35
+ def vplogin_name
36
+ %i[full_name name].each do |attr|
37
+ value = respond_to?(attr) ? public_send(attr).to_s.strip : ''
38
+ return value unless value.empty?
39
+ end
40
+ email
41
+ end
42
+
43
+ def vplogin_password_set? = false
44
+
45
+ private
46
+
47
+ def vplogin_sync_password
48
+ return unless VpLogin.configuration.admin_api?
49
+
50
+ VpLogin::PasswordSyncJob.perform_later(self.class.name, id)
51
+ end
52
+ end
53
+
54
+ class UserJob < ActiveJob::Base
55
+ queue_as { VpLogin.configuration.job_queue }
56
+
57
+ retry_on VpLogin::HttpError, VpLogin::ProvisioningError, wait: ->(executions) { (executions**4) + 2 }, attempts: 5
58
+
59
+ private
60
+
61
+ def find_user(user_class_name, user_id)
62
+ return unless VpLogin.configuration.admin_api?
63
+
64
+ user_class_name.constantize.find_by(id: user_id)
65
+ end
66
+
67
+ def sync_password(admin, user)
68
+ return if user.encrypted_password.to_s.empty?
69
+
70
+ admin.sync_bcrypt_password!(email: user.email, bcrypt_hash: user.encrypted_password)
71
+ end
72
+ end
73
+
74
+ class ProvisionJob < UserJob
75
+ def perform(user_class_name, user_id)
76
+ user = find_user(user_class_name, user_id)
77
+ return if user.nil?
78
+
79
+ admin = VpLogin::Admin.new
80
+ result = admin.provision_user!(email: user.email, name: user.vplogin_name,
81
+ email_mfa: VpLogin.configuration.provision_email_mfa)
82
+ if result.mfa_error
83
+ VpLogin.configuration.logger.warn("[VpLogin] email MFA factor failed for #{user.email}: #{result.mfa_error.message}")
84
+ end
85
+ # A password chosen before the identity existed had nothing to sync to.
86
+ sync_password(admin, user) if user.vplogin_password_set?
87
+ end
88
+ end
89
+
90
+ class PasswordSyncJob < UserJob
91
+ def perform(user_class_name, user_id)
92
+ user = find_user(user_class_name, user_id)
93
+ sync_password(VpLogin::Admin.new, user) if user
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ class Discovery
5
+ def initialize(config = VpLogin.configuration, http = Http.new(config))
6
+ @config = config
7
+ @http = http
8
+ end
9
+
10
+ def document
11
+ @config.cache.fetch(key(:discovery), expires_in: @config.metadata_ttl) do
12
+ @http.get_json!(@config.discovery_url)
13
+ end
14
+ end
15
+
16
+ def [](name)
17
+ value = document[name.to_s]
18
+ raise ConfigurationError, "vpLogin discovery document has no #{name}" if value.to_s.empty?
19
+
20
+ value
21
+ end
22
+
23
+ # Refetching on an unknown `kid` handles key rotation. The cooldown stops a stream of tokens
24
+ # with made-up kids from turning into a stream of JWKS requests against vpLogin.
25
+ def jwks(refresh: false)
26
+ if refresh && refresh_allowed?
27
+ @config.cache.write(key(:jwks_refreshed_at), Time.now.to_i, expires_in: @config.jwks_refresh_cooldown)
28
+ @config.cache.delete(key(:jwks))
29
+ end
30
+
31
+ @config.cache.fetch(key(:jwks), expires_in: @config.metadata_ttl) do
32
+ @http.get_json!(self['jwks_uri'])
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ def refresh_allowed?
39
+ @config.cache.read(key(:jwks_refreshed_at)).nil?
40
+ end
41
+
42
+ # Per issuer, so apps (or tests) pointing at different vpLogin applications don't share entries.
43
+ def key(kind)
44
+ "#{@config.cache_namespace}:#{kind}:#{Digest::SHA256.hexdigest(@config.issuer_url.to_s)[0, 16]}"
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ class Error < StandardError
5
+ def code
6
+ 'VPLOGIN_ERROR'
7
+ end
8
+ end
9
+
10
+ class ConfigurationError < Error
11
+ def code = 'VPLOGIN_MISCONFIGURED'
12
+ end
13
+
14
+ class HttpError < Error
15
+ attr_reader :status, :body
16
+
17
+ def initialize(status, body, url: nil)
18
+ @status = status
19
+ @body = body
20
+ super("vpLogin HTTP #{status}#{" from #{url}" if url}")
21
+ end
22
+
23
+ def code = 'VPLOGIN_UNAVAILABLE'
24
+ end
25
+
26
+ # Unknown, expired or already-used state / handoff code, or an app PKCE verifier that doesn't match.
27
+ class InvalidAttempt < Error
28
+ def code = 'INVALID_LOGIN_ATTEMPT'
29
+ end
30
+
31
+ # vpLogin redirected back with `error=` (user cancelled, prompt=none had no session, ...).
32
+ class AuthorizationDenied < Error
33
+ attr_reader :error, :description
34
+
35
+ def initialize(error, description = nil)
36
+ @error = error
37
+ @description = description
38
+ super("vpLogin returned #{error}#{": #{description}" if description}")
39
+ end
40
+
41
+ def code = 'AUTHORIZATION_DENIED'
42
+ end
43
+
44
+ class InvalidToken < Error
45
+ def code = 'INVALID_ID_TOKEN'
46
+ end
47
+
48
+ # The identity that signed in is not the one the login was started for (login_hint).
49
+ class IdentityMismatch < Error
50
+ def code = 'IDENTITY_MISMATCH'
51
+ end
52
+
53
+ class ProvisioningError < Error
54
+ def code = 'VPLOGIN_PROVISIONING_FAILED'
55
+ end
56
+
57
+ class GroupPermissionsCompromised < Error
58
+ def initialize(group:, user_id:)
59
+ super("vpLogin group #{group.inspect} carries superuser/roles; refusing to add user #{user_id}")
60
+ end
61
+
62
+ def code = 'GROUP_PERMISSIONS_COMPROMISED'
63
+ end
64
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ class Http
5
+ def initialize(config = VpLogin.configuration)
6
+ @config = config
7
+ end
8
+
9
+ # Raw response, never raises on status. Used where the caller inspects cookies/bodies itself.
10
+ def perform(method, url, query: nil, body: nil, headers: {})
11
+ uri = URI.parse(url)
12
+ if query && !query.empty?
13
+ uri.query = [uri.query, URI.encode_www_form(query)].compact.reject(&:empty?).join('&')
14
+ end
15
+
16
+ request = request_class(method).new(uri)
17
+ headers.each { |key, value| request[key] = value }
18
+ request.body = body if body
19
+
20
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
21
+ response = Net::HTTP.start(uri.host, uri.port,
22
+ use_ssl: uri.scheme == 'https',
23
+ open_timeout: @config.open_timeout,
24
+ read_timeout: @config.read_timeout) do |http|
25
+ http.request(request)
26
+ end
27
+ log(method, url, response.code, started)
28
+ response
29
+ rescue StandardError => e
30
+ log(method, url, e.class.name, started) if started
31
+ raise
32
+ end
33
+
34
+ def get_json!(url, query: nil, headers: {})
35
+ json!(perform(:get, url, query:, headers:), url)
36
+ end
37
+
38
+ def post_form!(url, form, headers: {})
39
+ body = URI.encode_www_form(form)
40
+ json!(perform(:post, url, body:, headers: { 'Content-Type' => 'application/x-www-form-urlencoded' }.merge(headers)), url)
41
+ end
42
+
43
+ def send_json!(method, url, payload, headers: {})
44
+ body = payload.nil? ? nil : JSON.generate(payload)
45
+ json!(perform(method, url, body:, headers: { 'Content-Type' => 'application/json' }.merge(headers)), url)
46
+ end
47
+
48
+ private
49
+
50
+ def json!(response, url)
51
+ status = response.code.to_i
52
+ # Never put the body in the message: token and admin responses carry secrets.
53
+ raise HttpError.new(status, response.body, url: strip_query(url)) unless (200..299).cover?(status)
54
+ return nil if status == 204 || response.body.to_s.strip.empty?
55
+
56
+ JSON.parse(response.body)
57
+ end
58
+
59
+ # Method, path and outcome only: queries carry emails and codes, bodies carry tokens.
60
+ def log(method, url, outcome, started)
61
+ ms = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
62
+ @config.logger.info("[VpLogin] #{method.to_s.upcase} #{strip_query(url)} -> #{outcome} (#{ms}ms)")
63
+ end
64
+
65
+ def strip_query(url)
66
+ url.to_s.split('?').first
67
+ end
68
+
69
+ def request_class(method)
70
+ {
71
+ get: Net::HTTP::Get, post: Net::HTTP::Post, put: Net::HTTP::Put,
72
+ patch: Net::HTTP::Patch, delete: Net::HTTP::Delete
73
+ }.fetch(method)
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # Fallback for non-Rails use and tests. Process-local, so not suitable when the callback and
5
+ # verify requests can land on different processes - configure a shared cache there.
6
+ class MemoryCache
7
+ def initialize
8
+ @store = {}
9
+ @mutex = Mutex.new
10
+ end
11
+
12
+ def read(key)
13
+ @mutex.synchronize do
14
+ value, expires_at = @store[key]
15
+ return nil if value.nil?
16
+
17
+ if expires_at && expires_at <= now
18
+ @store.delete(key)
19
+ return nil
20
+ end
21
+ value
22
+ end
23
+ end
24
+
25
+ def write(key, value, expires_in: nil)
26
+ @mutex.synchronize { @store[key] = [value, expires_in && (now + expires_in.to_f)] }
27
+ true
28
+ end
29
+
30
+ def delete(key)
31
+ @mutex.synchronize { !@store.delete(key).nil? }
32
+ end
33
+
34
+ def fetch(key, expires_in: nil)
35
+ cached = read(key)
36
+ return cached unless cached.nil?
37
+
38
+ value = yield
39
+ write(key, value, expires_in:)
40
+ value
41
+ end
42
+
43
+ private
44
+
45
+ def now
46
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # Authorization-code + PKCE login against one vpLogin application.
5
+ #
6
+ # start -> authorize URL; stores nonce/verifier/app data against `state`
7
+ # callback -> consumes `state`, returns a one-time handoff code for the frontend
8
+ # redeem -> consumes the handoff code (and checks the app's PKCE verifier, if any)
9
+ # exchange -> redeems the authorization code and verifies the ID token
10
+ class Oidc
11
+ PROMPTS = %w[none login consent select_account].freeze
12
+ PREFIX_FORMAT = /\A[A-Za-z0-9-]{1,63}\z/
13
+
14
+ Start = Struct.new(:url, :state, keyword_init: true)
15
+ Callback = Struct.new(:handoff_code, :attempt, keyword_init: true)
16
+
17
+ attr_reader :config
18
+
19
+ def initialize(config: VpLogin.configuration, http: nil, store: nil, discovery: nil)
20
+ @config = config
21
+ @http = http || Http.new(config)
22
+ @store = store || StateStore.new(config)
23
+ @discovery = discovery || Discovery.new(config, @http)
24
+ end
25
+
26
+ # data: anything the app needs back after the round trip (tenant, platform, ...).
27
+ # Must be cache-serializable.
28
+ # state_prefix: readable before the cache lookup, so the callback can still route an
29
+ # expired/failed attempt (e.g. back to the right subdomain).
30
+ # app_challenge: PKCE challenge from a native app; verify then requires its verifier.
31
+ def start(data: {}, login_hint: nil, prompt: nil, state_prefix: nil, app_challenge: nil, extra_params: {})
32
+ config.require!(:client_id, :redirect_uri)
33
+ raise ArgumentError, 'invalid state_prefix' if state_prefix && !state_prefix.to_s.match?(PREFIX_FORMAT)
34
+ raise ArgumentError, "invalid prompt #{prompt.inspect}" if prompt && !PROMPTS.include?(prompt.to_s)
35
+
36
+ state = [state_prefix, SecureRandom.hex(16)].compact.join('_')
37
+ nonce = SecureRandom.hex(16)
38
+ code_verifier = Pkce.verifier
39
+
40
+ @store.write_attempt(state, {
41
+ nonce:, code_verifier:, data:, login_hint:, prompt:, app_challenge:
42
+ }.compact)
43
+
44
+ query = {
45
+ client_id: config.client_id,
46
+ redirect_uri: config.redirect_uri,
47
+ response_type: 'code',
48
+ scope: config.scopes,
49
+ state:,
50
+ nonce:,
51
+ code_challenge: Pkce.challenge(code_verifier),
52
+ code_challenge_method: 'S256'
53
+ }
54
+ query[:login_hint] = login_hint if login_hint
55
+ query[:prompt] = prompt if prompt
56
+ query.merge!(extra_params)
57
+
58
+ Start.new(url: "#{@discovery['authorization_endpoint']}?#{URI.encode_www_form(query)}", state:)
59
+ end
60
+
61
+ def self.state_prefix(state)
62
+ prefix, rest = state.to_s.split('_', 2)
63
+ rest.nil? ? nil : prefix
64
+ end
65
+
66
+ # The attempt stored for `state`, without consuming it (nil if unknown or expired).
67
+ def pending(state)
68
+ @store.read_attempt(state.to_s)
69
+ end
70
+
71
+ def callback(state:, code:, error: nil, error_description: nil)
72
+ attempt = @store.take_attempt(state.to_s)
73
+ raise AuthorizationDenied.new(error, error_description) if error
74
+ raise InvalidAttempt, 'unknown or expired state' if attempt.nil?
75
+ raise InvalidAttempt, 'callback carried no code' if code.to_s.empty?
76
+
77
+ Callback.new(handoff_code: @store.write_handoff(attempt.merge(code: code.to_s)), attempt:)
78
+ end
79
+
80
+ # Consumes the handoff code. Any failure after this point needs a fresh login.
81
+ def redeem(handoff_code, app_verifier: nil)
82
+ attempt = @store.take_handoff(handoff_code.to_s)
83
+ raise InvalidAttempt, 'unknown or expired handoff code' if attempt.nil?
84
+
85
+ if attempt[:app_challenge] && !Pkce.verifier_matches?(attempt[:app_challenge], app_verifier)
86
+ raise InvalidAttempt, 'app PKCE verifier did not match'
87
+ end
88
+
89
+ attempt
90
+ end
91
+
92
+ def exchange(code:, code_verifier:, nonce:)
93
+ config.require!(:client_id, :client_secret, :redirect_uri)
94
+
95
+ tokens = @http.post_form!(@discovery['token_endpoint'], {
96
+ grant_type: 'authorization_code',
97
+ code:,
98
+ redirect_uri: config.redirect_uri,
99
+ client_id: config.client_id,
100
+ client_secret: config.client_secret,
101
+ code_verifier:
102
+ })
103
+
104
+ verify_id_token(tokens && tokens['id_token'], nonce:)
105
+ end
106
+
107
+ def verify_id_token(id_token, nonce:)
108
+ raise InvalidToken, 'token response had no id_token' if id_token.to_s.empty?
109
+
110
+ payload, = JWT.decode(
111
+ id_token, nil, true,
112
+ algorithms: config.id_token_algorithms,
113
+ iss: @discovery['issuer'], verify_iss: true,
114
+ aud: config.client_id, verify_aud: true,
115
+ verify_expiration: true, verify_iat: true,
116
+ leeway: config.clock_skew,
117
+ jwks: jwks_loader
118
+ )
119
+
120
+ # Ties the token to this login attempt; without it a token from another attempt could be replayed.
121
+ raise InvalidToken, 'nonce mismatch' unless OpenSSL.secure_compare(payload['nonce'].to_s, nonce.to_s)
122
+
123
+ if payload['aud'].is_a?(Array) && payload['aud'].size > 1 && payload['azp'] != config.client_id
124
+ raise InvalidToken, 'azp does not match client_id'
125
+ end
126
+
127
+ Claims.new(payload)
128
+ rescue JWT::DecodeError => e
129
+ raise InvalidToken, e.message
130
+ end
131
+
132
+ private
133
+
134
+ # jwt 2.x passes `invalidate: true` on an unknown kid; 3.x also passes `kid_not_found: true`.
135
+ def jwks_loader
136
+ lambda do |options|
137
+ @discovery.jwks(refresh: options[:invalidate] || options[:kid_not_found])
138
+ end
139
+ end
140
+ end
141
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ # Checks a password against vpLogin by driving a dedicated identification+password flow through
5
+ # the flow executor API. Counts against vpLogin's reputation/lockout like a real login.
6
+ class PasswordCheck
7
+ SUCCESS_COMPONENT = 'xak-flow-redirect'
8
+
9
+ def initialize(config: VpLogin.configuration, http: nil, flow: nil)
10
+ @config = config
11
+ @http = http || Http.new(config)
12
+ @flow = flow || config.password_check_flow
13
+ end
14
+
15
+ def valid?(email:, password:)
16
+ @config.require!(:admin_api_url)
17
+ raise ConfigurationError, 'VpLogin is missing configuration: password_check_flow' if @flow.to_s.empty?
18
+
19
+ url = "#{@config.admin_base_url}/flows/executor/#{URI.encode_www_form_component(@flow)}/?query="
20
+
21
+ cookie = cookies(@http.perform(:get, url))
22
+ return false if cookie.empty?
23
+
24
+ response = post(url, { uid_field: email }, cookie)
25
+ cookie = cookies(response).then { |fresh| fresh.empty? ? cookie : fresh }
26
+
27
+ body = parse(post(url, { password: }, cookie).body)
28
+ errors = body['response_errors']
29
+ return false unless errors.nil? || (errors.respond_to?(:empty?) && errors.empty?)
30
+
31
+ # Only a completed flow means the password matched. Access denied (lockout), an error
32
+ # screen, or a stage added later must not read as success.
33
+ body['component'].to_s == SUCCESS_COMPONENT
34
+ rescue ConfigurationError
35
+ raise
36
+ rescue StandardError => e
37
+ @config.logger.error("[VpLogin::PasswordCheck] #{e.class}: #{e.message}")
38
+ false
39
+ end
40
+
41
+ private
42
+
43
+ def post(url, payload, cookie)
44
+ @http.perform(:post, url, body: JSON.generate(payload),
45
+ headers: { 'Content-Type' => 'application/json', 'Cookie' => cookie })
46
+ end
47
+
48
+ def cookies(response)
49
+ Array(response.get_fields('set-cookie')).map { |c| c.split(';').first }.join('; ')
50
+ end
51
+
52
+ def parse(body)
53
+ parsed = JSON.parse(body.to_s)
54
+ parsed.is_a?(Hash) ? parsed : {}
55
+ rescue JSON::ParserError
56
+ {}
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ module Pkce
5
+ module_function
6
+
7
+ def verifier
8
+ SecureRandom.urlsafe_base64(64)
9
+ end
10
+
11
+ def challenge(verifier)
12
+ Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
13
+ end
14
+
15
+ # Both digest encodings are accepted: crypto-js hands back hex by default, while the RFC
16
+ # uses unpadded base64url.
17
+ def verifier_matches?(challenge, verifier)
18
+ return false if challenge.to_s.empty? || verifier.to_s.empty?
19
+
20
+ digest = Digest::SHA256.digest(verifier.to_s)
21
+ [Digest.hexencode(digest), Base64.urlsafe_encode64(digest, padding: false)].any? do |form|
22
+ OpenSSL.secure_compare(form, challenge.to_s)
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ class Railtie < ::Rails::Railtie
5
+ initializer 'vplogin.routes' do
6
+ require 'action_dispatch/routing/mapper'
7
+ ActionDispatch::Routing::Mapper.include(VpLogin::Routes)
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VpLogin
4
+ module Routes
5
+ # Inside a `namespace`, `controller` is relative to it, as with any route.
6
+ def vplogin_routes(controller:, path: 'auth/vplogin', as: 'vplogin')
7
+ scope path, controller:, as: do
8
+ get 'login', action: :vplogin_start, as: :login
9
+ get 'callback', action: :vplogin_callback, as: :callback
10
+ post 'verify', action: :vplogin_verify, as: :verify
11
+ end
12
+ end
13
+ end
14
+ end