Completed
Push — master ( 164aeb...fde2ba )
by Fike
45s
created

Validator.handler()   A

Complexity

Conditions 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
# frozen_string_literal: true
2
3
require 'tempfile'
4
require 'English'
5
6
require_relative 'ssh_keygen_handler'
7
require_relative 'exception/invalid_key_exception'
8
9
module AMA
10
  module Chef
11
    module SSHPrivateKeys
12
      # Validates provided key pair using ssh-keygen
13
      class Validator
14
        def initialize
15
          @handler = nil
16
        end
17
18
        # @param [AMA::Chef::SSHPrivateKeys::Model::KeyPair] pair
19
        def validate!(pair)
20
          unless pair.private_key
21
            message = "Provided key pair #{pair.id} is missing private key"
22
            raise_invalid_key_exception(message)
23
          end
24
          public_key = handler.generate_public_key(pair)
25
          unless pair.type == public_key.type
26
            message = "Key pair specified type #{pair.type}, but " \
27
              "#{public_key.type} was discovered"
28
            raise_invalid_key_exception(message)
29
          end
30
          return unless pair.public_key && pair.public_key != public_key.data
31
          message = [
32
            'Generated public key differs from ' \
33
              "provided public key `#{pair.id}`",
34
            "Provided: #{pair.public_key}",
35
            "Generated: #{public_key.data}"
36
          ]
37
          raise_invalid_key_exception(message.join(" #{$ORS}"))
38
        end
39
40
        private
41
42
        def handler
43
          return @handler if @handler
44
          binary = SSHKeygenHandler.locate_binary!
45
          @handler = SSHKeygenHandler.new(binary)
46
        end
47
48
        # @param [String] message
49
        def raise_invalid_key_exception(message)
50
          klass = AMA::Chef::SSHPrivateKeys::Exception::InvalidKeyException
51
          raise klass, message
52
        end
53
      end
54
    end
55
  end
56
end
57