diff --git a/app/controllers/api/v1/registrant/auth_controller.rb b/app/controllers/api/v1/registrant/auth_controller.rb new file mode 100644 index 000000000..5be48f558 --- /dev/null +++ b/app/controllers/api/v1/registrant/auth_controller.rb @@ -0,0 +1,54 @@ +require 'rails5_api_controller_backport' +require 'auth_token/auth_token_creator' + +module Api + module V1 + module Registrant + class AuthController < ActionController::API + before_action :check_ip_whitelist + + rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception| + error = {} + error[parameter_missing_exception.param] = ['parameter is required'] + response = { errors: [error] } + render json: response, status: :unprocessable_entity + end + + def eid + user = RegistrantUser.find_or_create_by_api_data(eid_params) + token = create_token(user) + + if token + render json: token + else + render json: { error: 'Cannot create generate session token' } + end + end + + private + + def eid_params + required_params = %i[ident first_name last_name] + required_params.each_with_object(params) do |key, obj| + obj.require(key) + end + + params.permit(required_params) + end + + def create_token(user) + token_creator = AuthTokenCreator.create_with_defaults(user) + hash = token_creator.token_in_hash + hash + end + + def check_ip_whitelist + allowed_ips = ENV['registrant_api_auth_allowed_ips'].to_s.split(',').map(&:strip) + return if allowed_ips.include?(request.ip) || Rails.env.development? + + render json: { errors: ['Not authorized'] }, status: :unauthorized + end + end + end + end +end diff --git a/app/controllers/api/v1/registrant/base_controller.rb b/app/controllers/api/v1/registrant/base_controller.rb new file mode 100644 index 000000000..bc5fa21d7 --- /dev/null +++ b/app/controllers/api/v1/registrant/base_controller.rb @@ -0,0 +1,38 @@ +require 'rails5_api_controller_backport' +require 'auth_token/auth_token_decryptor' + +module Api + module V1 + module Registrant + class BaseController < ActionController::API + before_action :authenticate + + rescue_from(ActionController::ParameterMissing) do |parameter_missing_exception| + error = {} + error[parameter_missing_exception.param] = ['parameter is required'] + response = { errors: [error] } + render json: response, status: :unprocessable_entity + end + + private + + def bearer_token + pattern = /^Bearer / + header = request.headers['Authorization'] + header.gsub(pattern, '') if header&.match(pattern) + end + + def authenticate + decryptor = AuthTokenDecryptor.create_with_defaults(bearer_token) + decryptor.decrypt_token + + if decryptor.valid? + sign_in decryptor.user + else + render json: { errors: ['Not authorized'] }, status: :unauthorized + end + end + end + end + end +end diff --git a/app/controllers/api/v1/registrant/domains_controller.rb b/app/controllers/api/v1/registrant/domains_controller.rb new file mode 100644 index 000000000..fdfc6872c --- /dev/null +++ b/app/controllers/api/v1/registrant/domains_controller.rb @@ -0,0 +1,20 @@ +require 'rails5_api_controller_backport' +require 'auth_token/auth_token_decryptor' + +module Api + module V1 + module Registrant + class DomainsController < BaseController + def index + registrant = ::Registrant.find_by(ident: current_user.registrant_ident) + if registrant + domains = Domain.where(registrant_id: registrant.id) + render json: domains + else + render json: [] + end + end + end + end + end +end diff --git a/app/models/registrant_user.rb b/app/models/registrant_user.rb index 12cae0d82..889f2ca4c 100644 --- a/app/models/registrant_user.rb +++ b/app/models/registrant_user.rb @@ -30,34 +30,56 @@ class RegistrantUser < User return false if issuer_organization != ACCEPTED_ISSUER idc_data.force_encoding('UTF-8') + user_data = {} # handling here new and old mode if idc_data.starts_with?("/") - identity_code = idc_data.scan(/serialNumber=(\d+)/).flatten.first - country = idc_data.scan(/^\/C=(.{2})/).flatten.first - first_name = idc_data.scan(%r{/GN=(.+)/serialNumber}).flatten.first - last_name = idc_data.scan(%r{/SN=(.+)/GN}).flatten.first + user_data[:ident] = idc_data.scan(/serialNumber=(\d+)/).flatten.first + user_data[:country_code] = idc_data.scan(/^\/C=(.{2})/).flatten.first + user_data[:first_name] = idc_data.scan(%r{/GN=(.+)/serialNumber}).flatten.first + user_data[:last_name] = idc_data.scan(%r{/SN=(.+)/GN}).flatten.first else parse_str = "," + idc_data - identity_code = parse_str.scan(/,serialNumber=(\d+)/).flatten.first - country = parse_str.scan(/,C=(.{2})/).flatten.first - first_name = parse_str.scan(/,GN=([^,]+)/).flatten.first - last_name = parse_str.scan(/,SN=([^,]+)/).flatten.first + user_data[:ident] = parse_str.scan(/,serialNumber=(\d+)/).flatten.first + user_data[:country_code] = parse_str.scan(/,C=(.{2})/).flatten.first + user_data[:first_name] = parse_str.scan(/,GN=([^,]+)/).flatten.first + user_data[:last_name] = parse_str.scan(/,SN=([^,]+)/).flatten.first end - u = where(registrant_ident: "#{country}-#{identity_code}").first_or_create - u.username = "#{first_name} #{last_name}" - u.save + find_or_create_by_user_data(user_data) + end - u + def find_or_create_by_api_data(user_data = {}) + return false unless user_data[:ident] + return false unless user_data[:first_name] + return false unless user_data[:last_name] + + user_data.each_value { |v| v.upcase! if v.is_a?(String) } + user_data[:country_code] ||= 'EE' + + find_or_create_by_user_data(user_data) end def find_or_create_by_mid_data(response) - u = where(registrant_ident: "#{response.user_country}-#{response.user_id_code}").first_or_create - u.username = "#{response.user_givenname} #{response.user_surname}" - u.save + user_data = { first_name: response.user_givenname, last_name: response.user_surname, + ident: response.user_id_code, country_code: response.user_country } - u + find_or_create_by_user_data(user_data) + end + + private + + def find_or_create_by_user_data(user_data = {}) + return unless user_data[:first_name] + return unless user_data[:last_name] + return unless user_data[:ident] + return unless user_data[:country_code] + + user = find_or_create_by(registrant_ident: "#{user_data[:country_code]}-#{user_data[:ident]}") + user.username = "#{user_data[:first_name]} #{user_data[:last_name]}" + user.save + + user end end end diff --git a/config/application-example.yml b/config/application-example.yml index 7785aafb5..b9917e69e 100644 --- a/config/application-example.yml +++ b/config/application-example.yml @@ -96,6 +96,8 @@ arireg_host: 'http://demo-ariregxml.rik.ee:81/' sk_digi_doc_service_endpoint: 'https://tsp.demo.sk.ee' sk_digi_doc_service_name: 'Testimine' +# Registrant API +registrant_api_auth_allowed_ips: '127.0.0.1, 0.0.0.0' #ips, separated with commas # # MISC diff --git a/config/application.rb b/config/application.rb index 400e72124..1420d3cd3 100644 --- a/config/application.rb +++ b/config/application.rb @@ -36,7 +36,7 @@ module DomainNameRegistry config.i18n.default_locale = :en config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb') - config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] + # config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')] # Autoload all model subdirs config.autoload_paths += Dir[Rails.root.join('app', 'models', '**/')] diff --git a/config/routes.rb b/config/routes.rb index 8f50d5587..3ae18a7cd 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -18,6 +18,16 @@ Rails.application.routes.draw do mount Repp::API => '/' + namespace :api do + namespace :v1 do + namespace :registrant do + post 'auth/eid', to: 'auth#eid' + + resources :domains, only: [:index] + end + end + end + # REGISTRAR ROUTES namespace :registrar do resource :dashboard diff --git a/lib/auth_token/auth_token_creator.rb b/lib/auth_token/auth_token_creator.rb new file mode 100644 index 000000000..9fff8e5cd --- /dev/null +++ b/lib/auth_token/auth_token_creator.rb @@ -0,0 +1,41 @@ +class AuthTokenCreator + DEFAULT_VALIDITY = 2.hours + + attr_reader :user + attr_reader :key + attr_reader :expires_at + + def self.create_with_defaults(user) + new(user, Rails.application.config.secret_key_base, Time.now + DEFAULT_VALIDITY) + end + + def initialize(user, key, expires_at) + @user = user + @key = key + @expires_at = expires_at.utc.strftime('%F %T %Z') + end + + def hashable + { + user_ident: user.registrant_ident, + user_username: user.username, + expires_at: expires_at, + }.to_json + end + + def encrypted_token + encryptor = OpenSSL::Cipher::AES.new(256, :CBC) + encryptor.encrypt + encryptor.key = key + encrypted_bytes = encryptor.update(hashable) + encryptor.final + Base64.urlsafe_encode64(encrypted_bytes) + end + + def token_in_hash + { + access_token: encrypted_token, + expires_at: expires_at, + type: 'Bearer', + } + end +end diff --git a/lib/auth_token/auth_token_decryptor.rb b/lib/auth_token/auth_token_decryptor.rb new file mode 100644 index 000000000..be6bd99cd --- /dev/null +++ b/lib/auth_token/auth_token_decryptor.rb @@ -0,0 +1,43 @@ +class AuthTokenDecryptor + attr_reader :decrypted_data + attr_reader :token + attr_reader :key + attr_reader :user + + def self.create_with_defaults(token) + new(token, Rails.application.config.secret_key_base) + end + + def initialize(token, key) + @token = token + @key = key + end + + def decrypt_token + decipher = OpenSSL::Cipher::AES.new(256, :CBC) + decipher.decrypt + decipher.key = key + + base64_decoded = Base64.urlsafe_decode64(token.to_s) + plain = decipher.update(base64_decoded) + decipher.final + + @decrypted_data = JSON.parse(plain, symbolize_names: true) + rescue OpenSSL::Cipher::CipherError, ArgumentError + false + end + + def valid? + decrypted_data && valid_user? && still_valid? + end + + private + + def valid_user? + @user = RegistrantUser.find_by(registrant_ident: decrypted_data[:user_ident]) + @user&.username == decrypted_data[:user_username] + end + + def still_valid? + decrypted_data[:expires_at] > Time.now + end +end diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml index b20bd8a83..5fd2dc925 100644 --- a/test/fixtures/users.yml +++ b/test/fixtures/users.yml @@ -26,3 +26,4 @@ admin: registrant: type: RegistrantUser registrant_ident: US-1234 + username: Registrant User diff --git a/test/integration/api/registrant/registrant_api_authentication_test.rb b/test/integration/api/registrant/registrant_api_authentication_test.rb new file mode 100644 index 000000000..14ef1c879 --- /dev/null +++ b/test/integration/api/registrant/registrant_api_authentication_test.rb @@ -0,0 +1,58 @@ +require 'test_helper' + +class RegistrantApiAuthenticationTest < ActionDispatch::IntegrationTest + def setup + super + + @user_hash = {ident: '37010100049', first_name: 'Adam', last_name: 'Baker'} + @existing_user = RegistrantUser.find_or_create_by_api_data(@user_hash) + end + + def teardown + super + + end + + def test_request_creates_user_when_one_does_not_exist + params = { + ident: '30110100103', + first_name: 'John', + last_name: 'Smith', + } + + post '/api/v1/registrant/auth/eid', params + assert(User.find_by(registrant_ident: 'EE-30110100103')) + + json = JSON.parse(response.body, symbolize_names: true) + assert_equal([:access_token, :expires_at, :type], json.keys) + end + + def test_request_returns_existing_user + assert_no_changes User.count do + post '/api/v1/registrant/auth/eid', @user_hash + end + end + + def test_request_returns_401_from_a_not_whitelisted_ip + params = { foo: :bar, test: :test } + @original_whitelist_ip = ENV['registrant_api_auth_allowed_ips'] + ENV['registrant_api_auth_allowed_ips'] = '1.2.3.4' + + post '/api/v1/registrant/auth/eid', params + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({ errors: ['Not authorized'] }, json_body) + + ENV['registrant_api_auth_allowed_ips'] = @original_whitelist_ip + end + + def test_request_documented_parameters_are_required + params = { foo: :bar, test: :test } + + post '/api/v1/registrant/auth/eid', params + json = JSON.parse(response.body, symbolize_names: true) + assert_equal({ errors: [{ ident: ['parameter is required'] }] }, json) + assert_equal(422, response.status) + end +end diff --git a/test/integration/api/registrant/registrant_api_domains_test.rb b/test/integration/api/registrant/registrant_api_domains_test.rb new file mode 100644 index 000000000..2d0b83903 --- /dev/null +++ b/test/integration/api/registrant/registrant_api_domains_test.rb @@ -0,0 +1,32 @@ +require 'test_helper' +require 'auth_token/auth_token_creator' + +class RegistrantApiDomainsTest < ActionDispatch::IntegrationTest + def setup + super + + @user = users(:registrant) + @auth_headers = { 'HTTP_AUTHORIZATION' => auth_token } + end + + def test_root_returns_domain_list + get '/api/v1/registrant/domains', {}, @auth_headers + assert_equal(200, response.status) + end + + def test_root_returns_401_without_authorization + get '/api/v1/registrant/domains', {}, {} + assert_equal(401, response.status) + json_body = JSON.parse(response.body, symbolize_names: true) + + assert_equal({ errors: ['Not authorized'] }, json_body) + end + + private + + def auth_token + token_creator = AuthTokenCreator.create_with_defaults(@user) + hash = token_creator.token_in_hash + "Bearer #{hash[:access_token]}" + end +end diff --git a/test/lib/auth_token/auth_token_creator_test.rb b/test/lib/auth_token/auth_token_creator_test.rb new file mode 100644 index 000000000..9d4cdd2c6 --- /dev/null +++ b/test/lib/auth_token/auth_token_creator_test.rb @@ -0,0 +1,53 @@ +require 'test_helper' +require 'openssl' +require_relative '../../../lib/auth_token/auth_token_creator' + +class AuthTokenCreatorTest < ActiveSupport::TestCase + def setup + super + + @user = users(:registrant) + time = Time.zone.parse('2010-07-05 00:30:00 +0000') + @random_bytes = SecureRandom.random_bytes(64) + @token_creator = AuthTokenCreator.new(@user, @random_bytes, time) + end + + def test_hashable_is_constructed_as_expected + expected_hashable = { user_ident: 'US-1234', user_username: 'Registrant User', + expires_at: '2010-07-05 00:30:00 UTC' }.to_json + + assert_equal(expected_hashable, @token_creator.hashable) + end + + def test_encrypted_token_is_decryptable + encryptor = OpenSSL::Cipher::AES.new(256, :CBC) + encryptor.decrypt + encryptor.key = @random_bytes + + base64_decoded = Base64.urlsafe_decode64(@token_creator.encrypted_token) + result = encryptor.update(base64_decoded) + encryptor.final + + hashable = { user_ident: 'US-1234', user_username: 'Registrant User', + expires_at: '2010-07-05 00:30:00 UTC' }.to_json + + assert_equal(hashable, result) + end + + def test_token_in_json_returns_expected_values + @token_creator.stub(:encrypted_token, 'super_secure_token') do + token = @token_creator.token_in_hash + assert_equal('2010-07-05 00:30:00 UTC', token[:expires_at]) + assert_equal('Bearer', token[:type]) + end + end + + def test_create_with_defaults_injects_values + travel_to Time.zone.parse('2010-07-05 00:30:00 +0000') + + token_creator_with_defaults = AuthTokenCreator.create_with_defaults(@user) + assert_equal(Rails.application.config.secret_key_base, token_creator_with_defaults.key) + assert_equal('2010-07-05 02:30:00 UTC', token_creator_with_defaults.expires_at) + + travel_back + end +end diff --git a/test/lib/auth_token/auth_token_decryptor_test.rb b/test/lib/auth_token/auth_token_decryptor_test.rb new file mode 100644 index 000000000..49ca2b820 --- /dev/null +++ b/test/lib/auth_token/auth_token_decryptor_test.rb @@ -0,0 +1,82 @@ +require 'test_helper' +require_relative '../../../lib/auth_token/auth_token_decryptor' +require_relative '../../../lib/auth_token/auth_token_creator' + +class AuthTokenDecryptorTest < ActiveSupport::TestCase + def setup + super + + travel_to Time.parse("2010-07-05 00:15:00 UTC") + @user = users(:registrant) + + # For testing purposes, the token needs to be random and long enough, hence: + @key = "b8+PtSq1+iXzUVnGEqciKsITNR0KmLl7uPiSTHbteqCoEBdbMLUl3GXlIDWD\nDZp1hIgKWnIMPNEgbuCa/7qccA==\n" + @faulty_key = "FALSE+iXzUVnGEqciKsITNR0KmLl7uPiSTHbteqCoEBdbMLUl3GXlIDWD\nDZp1hIgKWnIMPNEgbuCa/7qccA==\n" + + # this token corresponds to: + # {:user_ident=>"US-1234", :user_username=>"Registrant User", :expires_at=>"2010-07-05 02:15:00 UTC"} + @access_token = "q27NWIsKD5snWj9vZzJ0RcOYvgocEyu7H9yCaDjfmGi54sogovpBeALMPWTZHMcdFQzSiq6b4cI0p5tO0_5UEOHic2jRzNW7mkhi-bn-Y2Wlnw7jhMpxw6VwJR8QEoDzjkcNxnKBN6OKF4nssa60ZQ==" + end + + def teardown + super + + travel_back + end + + def test_decrypt_token_returns_a_hash_when_token_is_valid + decryptor = AuthTokenDecryptor.new(@access_token, @key) + + assert(decryptor.decrypt_token.is_a?(Hash)) + end + + def test_decrypt_token_return_false_when_token_is_invalid + faulty_decryptor = AuthTokenDecryptor.new(@access_token, @faulty_key) + refute(faulty_decryptor.decrypt_token) + end + + def test_decrypt_token_return_false_when_token_is_nil + faulty_decryptor = AuthTokenDecryptor.new(nil, @key) + refute(faulty_decryptor.decrypt_token) + end + + def test_valid_returns_true_for_valid_token + decryptor = AuthTokenDecryptor.new(@access_token, @key) + decryptor.decrypt_token + + assert(decryptor.valid?) + end + + def test_valid_returns_false_for_invalid_token + faulty_decryptor = AuthTokenDecryptor.new(@access_token, @faulty_key) + faulty_decryptor.decrypt_token + + refute(faulty_decryptor.valid?) + end + + def test_valid_returns_false_for_expired_token + travel_to Time.parse("2010-07-05 10:15:00 UTC") + + decryptor = AuthTokenDecryptor.new(@access_token, @key) + decryptor.decrypt_token + + refute(decryptor.valid?) + end + + def test_returns_false_for_non_existing_user + # This token was created from an admin user and @key. Decrypted, it corresponds to: + # {:user_ident=>nil, :user_username=>"test", :expires_at=>"2010-07-05 00:15:00 UTC"} + other_token = "rMkjgpyRcj2xOnHVwvvQ5RAS0yQepUSrw3XM5BrwM4TMH-h-TBeLve9InC_zaPneMMnCs0NHQHt1EpH95A2Yhdk6Ge6HQ-4gN5L0THDywCO2vHKGucPxbd6g6wOSaOnR" + + decryptor = AuthTokenDecryptor.new(other_token, @key) + decryptor.decrypt_token + + refute(decryptor.valid?) + end + + def test_create_with_defaults_injects_values + decryptor = AuthTokenDecryptor.create_with_defaults(@access_token) + + assert_equal(Rails.application.config.secret_key_base, decryptor.key) + end +end diff --git a/test/models/registrant_user_test.rb b/test/models/registrant_user_test.rb new file mode 100644 index 000000000..86ab5591a --- /dev/null +++ b/test/models/registrant_user_test.rb @@ -0,0 +1,62 @@ +class RegistrantUserTest < ActiveSupport::TestCase + def setup + super + end + + def teardown + super + end + + def test_find_or_create_by_api_data_creates_a_user + user_data = { + ident: '37710100070', + first_name: 'JOHN', + last_name: 'SMITH' + } + + RegistrantUser.find_or_create_by_api_data(user_data) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + + def test_find_or_create_by_api_data_creates_a_user_after_upcasing_input + user_data = { + ident: '37710100070', + first_name: 'John', + last_name: 'Smith' + } + + RegistrantUser.find_or_create_by_api_data(user_data) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + + def test_find_or_create_by_mid_data_creates_a_user + user_data = OpenStruct.new(user_country: 'EE', user_id_code: '37710100070', + user_givenname: 'JOHN', user_surname: 'SMITH') + + RegistrantUser.find_or_create_by_mid_data(user_data) + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + + def test_find_or_create_by_idc_with_legacy_header_creates_a_user + header = '/C=EE/O=ESTEID/OU=authentication/CN=SMITH,JOHN,37710100070/SN=SMITH/GN=JOHN/serialNumber=37710100070' + + RegistrantUser.find_or_create_by_idc_data(header, RegistrantUser::ACCEPTED_ISSUER) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end + + def test_find_or_create_by_idc_with_rfc2253_header_creates_a_user + header = 'serialNumber=37710100070,GN=JOHN,SN=SMITH,CN=SMITH\\,JOHN\\,37710100070,OU=authentication,O=ESTEID,C=EE' + + RegistrantUser.find_or_create_by_idc_data(header, RegistrantUser::ACCEPTED_ISSUER) + + user = User.find_by(registrant_ident: 'EE-37710100070') + assert_equal('JOHN SMITH', user.username) + end +end