# frozen_string_literal: true require_relative "jwt_test_helper" module NulogySSO module TestUtilities # This provides a simple mock implementation of Auth0 endpoints, via mockserver class Auth0Mock def initialize( engine_path: "/nulogy_sso", mockserver_host: ENV.fetch("NULOGY_SSO_MOCKSERVER_HOST"), mockserver_port: ENV.fetch("NULOGY_SSO_MOCKSERVER_PORT") ) @jwt_test_helper = NulogySSO::TestUtilities::JwtTestHelper.new @engine_path = engine_path @mockserver_host = mockserver_host @mockserver_port = mockserver_port end def setup_jwks mockserver_expectation( httpRequest: { method: "GET", path: "/.well-known/jwks.json" }, httpResponse: { body: jwt_test_helper.jwks_json } ) end def setup(email:, redirect_path:, status_code: 200) mockserver_reset redirect_query_params = { code: "FAKE_CODE", origin: "#{capybara_current_host}#{redirect_path}" }.to_query mockserver_expectation( httpRequest: { method: "GET", path: "/authorize" }, httpResponse: { statusCode: 302, headers: { Location: ["#{capybara_current_host}#{engine_path}/verify_authentication_code?#{redirect_query_params}"] } } ) setup_jwks mockserver_expectation( httpRequest: { method: "POST", path: "/oauth/token" }, httpResponse: { statusCode: status_code, body: signed_jwt_response(email) } ) end def mockserver_reset uri = URI(mockserver_url("reset")) req = Net::HTTP::Put.new(uri) Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end end private attr_reader :jwt_test_helper, :engine_path def mockserver_expectation(body) uri = URI(mockserver_url("expectation")) req = Net::HTTP::Put.new(uri, "Content-Type" => "application/json") req.body = body.to_json Net::HTTP.start(uri.hostname, uri.port) do |http| http.request(req) end end def mockserver_url(path = "") "http://#{@mockserver_host}:#{@mockserver_port}/mockserver/#{path}" end def signed_jwt_response(email, overrides = {}) jwt = jwt_test_helper.jwt(email, overrides) { access_token: jwt }.to_json end def capybara_current_host @capybara_current_host ||= "http://#{Capybara.current_session.server.host}:#{Capybara.current_session.server.port}" end end end end