diff --git a/app/controllers/admin/repp_logs_controller.rb b/app/controllers/admin/repp_logs_controller.rb index 6b0c7efa4a..0e5540bad2 100644 --- a/app/controllers/admin/repp_logs_controller.rb +++ b/app/controllers/admin/repp_logs_controller.rb @@ -8,6 +8,7 @@ def index @q = ApiLog::ReppLog.ransack(PartialSearchFormatter.format(params[:q])) @q.sorts = 'id desc' if @q.sorts.empty? @result = @q.result + @result = @result.failed_identity_verifications if params[:failed_verifications] == '1' @repp_logs = @result if params[:q][:created_at_gteq].present? @repp_logs = @repp_logs.where("extract(epoch from created_at) >= extract(epoch from ?::timestamp)", @@ -18,7 +19,7 @@ def index Time.parse(params[:q][:created_at_lteq])) end @repp_logs = @repp_logs.page(params[:page]) - @count = @q.result.count + @count = @result.count @repp_logs = @repp_logs.per(params[:results_per_page]) if paginate? render_by_format('admin/repp_logs/index', 'repp_logs') diff --git a/app/controllers/repp/v1/api_users_controller.rb b/app/controllers/repp/v1/api_users_controller.rb index ac20ccef56..316c8ca432 100644 --- a/app/controllers/repp/v1/api_users_controller.rb +++ b/app/controllers/repp/v1/api_users_controller.rb @@ -95,12 +95,9 @@ def approve_verification subject: approve_verification_params[:subject] ) - unless action.call - handle_non_epp_errors(@api_user) - return - end + return render_success(data: { api_user: { id: @api_user.id } }) if action.call - render_success(data: { api_user: { id: @api_user.id } }) + render_verification_failure(action) end api :POST, '/repp/v1/api_users/reject_verification/:id' @@ -132,6 +129,21 @@ def approve_verification_params params.fetch(:api_user, {}).permit(:subject) end + # The response is stored in the REPP log, so it carries everything needed + # to find failed identity verifications there. + def render_verification_failure(action) + @response = { + message: action.failure_message, + data: { + verification_failed: true, + reason: action.failure_reason, + api_user: { id: @api_user.id, username: @api_user.username, + identity_code: @api_user.identity_code, subject: action.subject }, + }, + } + render(json: @response, status: :bad_request) + end + def serialized_users(users) users.map { |i| Serializers::Repp::ApiUser.new(i).to_json } end diff --git a/app/interactions/actions/api_user_approve_verification.rb b/app/interactions/actions/api_user_approve_verification.rb index 6fbc409ada..3876f78a05 100644 --- a/app/interactions/actions/api_user_approve_verification.rb +++ b/app/interactions/actions/api_user_approve_verification.rb @@ -5,7 +5,7 @@ module Actions class ApiUserApproveVerification SUB_PATTERN = /\A([A-Z]{2})([0-9A-Za-z]+)\z/ - attr_reader :api_user + attr_reader :api_user, :subject, :failure_reason def initialize(api_user, subject: nil) @api_user = api_user @@ -13,25 +13,35 @@ def initialize(api_user, subject: nil) end def call - unless api_user.verification_pending_at.present? - api_user.errors.add(:base, :not_pending_verification) - return false - end + return fail_with(:not_pending_verification) unless api_user.verification_pending_at.present? snapshot = (api_user.verification_snapshot || {}).with_indifferent_access # Pending snapshot comes from eeID result (OIDC +sub+). - subject = @subject || snapshot[:sub].to_s.strip.presence + @subject ||= snapshot[:sub].to_s.strip.presence + return fail_with(:missing_subject) if subject.blank? - if subject.blank? - api_user.errors.add(:base, :missing_subject) - return false + conflicting_user = find_conflicting_user + if conflicting_user + return fail_with(:subject_taken_by_user, subject: subject, username: conflicting_user.username) end - if subject_conflict?(subject) - api_user.errors.add(:subject, :taken) - return false - end + approve! + true + rescue ActiveRecord::RecordInvalid => e + reason = e.record.errors.full_messages.join(', ') + # The transaction rolled back; drop the in-memory subject and timestamps too. + api_user.reload + api_user.errors.clear + fail_with(:update_failed, reason: reason) + end + def failure_message + api_user.errors.full_messages.join(', ') + end + + private + + def approve! country_code = country_code_from_subject(subject) subject_attrs = { subject: subject } subject_attrs[:country_code] = country_code if country_code.present? @@ -45,20 +55,33 @@ def call verification_pending_at: nil ) end - true end - private + def fail_with(reason, **options) + api_user.errors.add(:base, reason, **options) + @failure_reason = reason + log_failure + false + end + + def log_failure + Rails.logger.warn( + '[ApiUserVerification] Manual approval failed: ' \ + "api_user_id=#{api_user.id} username=#{api_user.username} " \ + "registrar=#{api_user.registrar&.code} identity_code=#{api_user.identity_code.presence || '-'} " \ + "subject=#{subject || '-'} reason=#{failure_reason} message=#{failure_message.inspect}" + ) + end def country_code_from_subject(subject) match = subject.match(SUB_PATTERN) match&.[](1) end - def subject_conflict?(subject) + def find_conflicting_user ApiUser.where(registrar_id: api_user.registrar_id, subject: subject) .where.not(id: api_user.id) - .exists? + .first end end end diff --git a/app/models/api_log/repp_log.rb b/app/models/api_log/repp_log.rb index 540a9043ae..f763cb2acc 100644 --- a/app/models/api_log/repp_log.rb +++ b/app/models/api_log/repp_log.rb @@ -1,3 +1,26 @@ module ApiLog - class ReppLog < Db; end + class ReppLog < Db + IDENTITY_APPROVAL_PATH = '/repp/v1/api_users/approve_verification/'.freeze + + scope :failed_identity_verifications, lambda { + where('request_path LIKE ?', "#{IDENTITY_APPROVAL_PATH}%").where.not(response_code: '200') + } + + def failed_identity_verification? + request_path.to_s.start_with?(IDENTITY_APPROVAL_PATH) && response_code.to_s != '200' + end + + # Details from the REPP response of a failed manual identity approval. + def identity_verification_failure + return unless failed_identity_verification? + + body = JSON.parse(response.to_s) + body = {} unless body.is_a?(Hash) + user = body.dig('data', 'api_user') || {} + { message: body['message'].presence || "HTTP #{response_code}", + username: user['username'], identity_code: user['identity_code'], subject: user['subject'] } + rescue JSON::ParserError + { message: "HTTP #{response_code}" } + end + end end diff --git a/app/models/api_user.rb b/app/models/api_user.rb index 3142303c0d..066ca33929 100644 --- a/app/models/api_user.rb +++ b/app/models/api_user.rb @@ -14,7 +14,9 @@ def epp_code_map %i[base not_pending_verification], %i[identity_code taken], %i[subject taken], - %i[base missing_subject] + %i[base missing_subject], + %i[base subject_taken_by_user], + %i[base update_failed] ] } end diff --git a/app/views/admin/repp_logs/index.haml b/app/views/admin/repp_logs/index.haml index a3b6a22d1e..48dac26436 100644 --- a/app/views/admin/repp_logs/index.haml +++ b/app/views/admin/repp_logs/index.haml @@ -41,6 +41,12 @@   = link_to(t('.csv_btn'), admin_repp_logs_path(format: :csv, params: params.permit!), class: 'btn btn-default') = link_to(t('.reset_btn'), admin_repp_logs_path, class: 'btn btn-default') + .row + .col-md-3 + .checkbox + %label + = check_box_tag :failed_verifications, '1', params[:failed_verifications] == '1' + = t('.failed_verifications') %hr .row .col-md-12 @@ -63,7 +69,16 @@ %tbody - @repp_logs.each do |x| %tr - %td= link_to(x.request_path, admin_repp_log_path(x)) + %td + = link_to(x.request_path, admin_repp_log_path(x)) + - if (failure = x.identity_verification_failure) + %br + %span.label.label-danger= t('.verification_failed') + %div + - if failure[:username].present? + %strong= failure[:username] + = "(#{failure[:identity_code].presence || failure[:subject].presence || '-'})" + = failure[:message] %td= x.request_method %td= x.response_code %td= x.api_user_name diff --git a/config/locales/admin/repp_logs.en.yml b/config/locales/admin/repp_logs.en.yml index 978270df6b..4689b141d9 100644 --- a/config/locales/admin/repp_logs.en.yml +++ b/config/locales/admin/repp_logs.en.yml @@ -5,6 +5,8 @@ en: title: REPP log reset_btn: Reset csv_btn: CSV + failed_verifications: Failed identity verifications only + verification_failed: Identity verification failed show: title: REPP log diff --git a/config/locales/api_users.en.yml b/config/locales/api_users.en.yml index 879c515aa9..f9f396fc01 100644 --- a/config/locales/api_users.en.yml +++ b/config/locales/api_users.en.yml @@ -38,3 +38,5 @@ en: verification_error: Sending identification request failed not_pending_verification: No pending verification to approve or reject missing_subject: Login subject is required to approve verification + subject_taken_by_user: "Identity %{subject} is already linked to API user %{username} at this registrar" + update_failed: "Saving API user data failed: %{reason}" diff --git a/config/locales/api_users.et.yml b/config/locales/api_users.et.yml index f12850cc94..6d636fc7b1 100644 --- a/config/locales/api_users.et.yml +++ b/config/locales/api_users.et.yml @@ -38,3 +38,5 @@ et: verification_error: Identifitseerimistaotluse saatmine ebaõnnestus not_pending_verification: Kinnitamist ootavat identifitseerimist pole missing_subject: Sisselogimise identifikaator on kinnitamiseks kohustuslik + subject_taken_by_user: "Isik %{subject} on selle registripidaja juures juba seotud API kasutajaga %{username}" + update_failed: "API kasutaja andmete salvestamine ebaõnnestus: %{reason}" diff --git a/test/integration/admin_area/repp_logs_test.rb b/test/integration/admin_area/repp_logs_test.rb index 24ab665f40..59a5041150 100644 --- a/test/integration/admin_area/repp_logs_test.rb +++ b/test/integration/admin_area/repp_logs_test.rb @@ -21,6 +21,24 @@ def test_show_repp_log_page assert_text 'REPP log' end + def test_filters_and_marks_failed_identity_verifications + ApiLog::ReppLog.create!(request_path: '/repp/v1/contacts', request_method: 'GET', response_code: '200') + ApiLog::ReppLog.create!( + request_path: '/repp/v1/api_users/approve_verification/1', request_method: 'POST', + response_code: '400', api_user_name: 'approver', + response: { message: 'Identity EE1 is already linked to API user bob at this registrar', + data: { verification_failed: true, + api_user: { username: 'machine_user', identity_code: nil, subject: 'EE1' } } }.to_json + ) + + visit admin_repp_logs_path(failed_verifications: '1') + + assert_text 'Identity verification failed' + assert_text 'machine_user (EE1)' + assert_text 'already linked to API user bob' + assert_no_link '/repp/v1/contacts' + end + def test_download_repp_logs now = Time.zone.parse('2010-07-05 08:00') travel_to now diff --git a/test/integration/repp/v1/api_users/verification_state_flow_test.rb b/test/integration/repp/v1/api_users/verification_state_flow_test.rb index 6e9275d4de..5c501d9dc6 100644 --- a/test/integration/repp/v1/api_users/verification_state_flow_test.rb +++ b/test/integration/repp/v1/api_users/verification_state_flow_test.rb @@ -61,6 +61,47 @@ def test_registrar_approval_verifies_user_regardless_of_previous_login_state assert_response :ok end + def test_failed_approval_returns_reason_and_is_logged_as_failed_verification + @api_user.update_columns( + verified_at: nil, + verification_pending_at: Time.zone.now, + verification_snapshot: { 'sub' => 'EE5555' } + ) + @approver.update_columns(subject: 'EE5555') + + post "/repp/v1/api_users/approve_verification/#{@api_user.id}", headers: @approver_headers + json = JSON.parse(response.body, symbolize_names: true) + + assert_response :bad_request + assert_includes json[:message], @approver.username + assert json[:data][:verification_failed] + assert_equal 'subject_taken_by_user', json[:data][:reason] + assert_equal @api_user.username, json[:data][:api_user][:username] + assert_equal 'EE5555', json[:data][:api_user][:subject] + + log = ApiLog::ReppLog.failed_identity_verifications.order(:id).last + assert log.failed_identity_verification? + assert_equal @api_user.username, log.identity_verification_failure[:username] + assert_includes log.identity_verification_failure[:message], @approver.username + end + + def test_approval_with_invalid_user_data_returns_bad_request_instead_of_server_error + @api_user.update_columns( + verified_at: nil, + verification_pending_at: Time.zone.now, + verification_snapshot: { 'sub' => 'EE5555' }, + plain_text_password: '123' + ) + + post "/repp/v1/api_users/approve_verification/#{@api_user.id}", headers: @approver_headers + json = JSON.parse(response.body, symbolize_names: true) + + assert_response :bad_request + assert_equal 'update_failed', json[:data][:reason] + assert_match(/Password is too short/, json[:message]) + assert_nil @api_user.reload.verified_at + end + private def auth_headers_for(api_user) diff --git a/test/interactions/actions/api_user_approve_verification_test.rb b/test/interactions/actions/api_user_approve_verification_test.rb index 499b21a886..e03cdbee26 100644 --- a/test/interactions/actions/api_user_approve_verification_test.rb +++ b/test/interactions/actions/api_user_approve_verification_test.rb @@ -51,7 +51,37 @@ class Actions::ApiUserApproveVerificationTest < ActiveSupport::TestCase registrar: @api_user.registrar ) - assert_not Actions::ApiUserApproveVerification.new(@api_user).call - assert @api_user.errors.added?(:subject, :taken) + action = Actions::ApiUserApproveVerification.new(@api_user) + + assert_not action.call + assert_equal :subject_taken_by_user, action.failure_reason + assert @api_user.errors.added?(:base, :subject_taken_by_user, + subject: 'GBMANUAL123', username: users(:api_bestnames).username) + assert_includes action.failure_message, users(:api_bestnames).username + end + + test 'approve returns validation errors instead of raising when user data is invalid' do + @api_user.update_columns(plain_text_password: '123') + action = Actions::ApiUserApproveVerification.new(@api_user) + + assert_not action.call + assert_equal :update_failed, action.failure_reason + assert_equal 1, @api_user.errors.count + assert_match(/Saving API user data failed: Password is too short/, action.failure_message) + + @api_user.reload + assert_nil @api_user.verified_at + assert @api_user.verification_pending_at.present? + assert_not_equal 'GBMANUAL123', @api_user.subject + end + + test 'approve logs the failure reason' do + @api_user.update!(verification_snapshot: {}) + logged = [] + Rails.logger.stub(:warn, ->(msg) { logged << msg }) do + Actions::ApiUserApproveVerification.new(@api_user).call + end + + assert(logged.any? { |msg| msg.include?('Manual approval failed') && msg.include?('reason=missing_subject') }) end end diff --git a/test/models/api_log/repp_log_test.rb b/test/models/api_log/repp_log_test.rb new file mode 100644 index 0000000000..f59ce35d7a --- /dev/null +++ b/test/models/api_log/repp_log_test.rb @@ -0,0 +1,30 @@ +require 'test_helper' + +class ApiLog::ReppLogTest < ActiveSupport::TestCase + APPROVE_PATH = '/repp/v1/api_users/approve_verification/1'.freeze + + test 'detects failed identity approvals only' do + assert ApiLog::ReppLog.new(request_path: APPROVE_PATH, response_code: '400').failed_identity_verification? + assert_not ApiLog::ReppLog.new(request_path: APPROVE_PATH, response_code: '200').failed_identity_verification? + assert_not ApiLog::ReppLog.new(request_path: '/repp/v1/contacts', response_code: '400').failed_identity_verification? + end + + test 'extracts failure details from the response' do + response = { message: 'Identity EE1 is already linked to API user bob at this registrar', + data: { verification_failed: true, + api_user: { username: 'machine', identity_code: nil, subject: 'EE1' } } }.to_json + failure = ApiLog::ReppLog.new(request_path: APPROVE_PATH, response_code: '400', response: response) + .identity_verification_failure + + assert_equal 'machine', failure[:username] + assert_equal 'EE1', failure[:subject] + assert_includes failure[:message], 'bob' + end + + test 'falls back to the status code when the response has no details' do + failure = ApiLog::ReppLog.new(request_path: APPROVE_PATH, response_code: '500', response: 'null') + .identity_verification_failure + + assert_equal 'HTTP 500', failure[:message] + end +end