summaryrefslogtreecommitdiff
path: root/lib/license/management/shell.rb
blob: 9053a3f330b8437e23e580ff2d624ce94b17e9b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# frozen_string_literal: true

module License
  module Management
    class Shell
      SPLIT_SCRIPT = "'BEGIN {x=0;} /BEGIN CERT/{x++} { print > \"custom.\" x \".crt\" }'"
      attr_reader :custom_certificate_path, :logger

      def initialize(logger: License::Management.logger, certificate: ENV['ADDITIONAL_CA_CERT_BUNDLE'])
        @logger = logger
        @custom_certificate_path = Pathname.new('/usr/local/share/ca-certificates/custom.crt')
        trust!(certificate)
      end

      def execute(command, env: {})
        expanded_command = expand(command)
        logger.debug(expanded_command)

        stdout, stderr, status = Open3.capture3(env, expanded_command)

        logger.debug(stdout) unless stdout.nil? || stdout.empty?
        logger.error(stderr) unless stderr.nil? || stderr.empty?
        [stdout, stderr, status]
      end

      def sh(command, env: {})
        execute("sh -c '#{expand(command)}'", env: env)
      end

      def custom_certificate_installed?
        present?(ENV['ADDITIONAL_CA_CERT_BUNDLE']) && custom_certificate_path.exist?
      end

      private

      def expand(command)
        Array(command).flatten.map(&:to_s).join(' ')
      end

      def trust!(certificate)
        return unless present?(certificate)

        custom_certificate_path.write(certificate)
        Dir.chdir custom_certificate_path.dirname do
          execute([:awk, SPLIT_SCRIPT, '<', custom_certificate_path])
          execute('update-ca-certificates -v')

          Dir.glob('custom.*.crt').each do |path|
            full_path = File.expand_path(path)
            execute([:openssl, :x509, '-in', full_path, '-text', '-noout'])
            keystore_path = "#{ENV['JAVA_HOME']}/jre/lib/security/cacerts"
            execute([
              :keytool,
              '-importcert',
              '-alias', Time.now.to_i,
              '-file', full_path,
              '-trustcacerts',
              '-noprompt',
              '-storepass', 'changeit',
              '-keystore', keystore_path
            ])
            execute([
              :keytool, '-list', '-v',
              '-storepass changeit',
              '-keystore', keystore_path
            ])
          end
        end
      end

      def present?(item)
        !item.nil? && !item.empty?
      end
    end
  end
end