Module: Pindo::CertHelper

Included in:
Pindo::Command::Deploy::Cert, Pindo::Command::Utils::Renewcert
Defined in:
lib/pindo/module/cert/certhelper.rb

Instance Method Summary collapse

Instance Method Details

#get_cert_info(cer_certificate) ⇒ Object



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
# File 'lib/pindo/module/cert/certhelper.rb', line 14

def get_cert_info(cer_certificate)
  # can receive a certificate path or the file data
  begin
    if File.exist?(cer_certificate)
      cer_certificate = File.binread(cer_certificate)
    end
  rescue ArgumentError
    # cert strings have null bytes; suppressing output
  end

  cert = OpenSSL::X509::Certificate.new(cer_certificate)

  # openssl output:
  # subject= /UID={User ID}/CN={Certificate Name}/OU={Certificate User}/O={Organisation}/C={Country}
  cert_info = cert.subject.to_s.gsub(/\s*subject=\s*/, "").tr("/", "\n")
  out_array = cert_info.split("\n")
  openssl_keys_to_readable_keys = {
       'UID' => 'User ID',
       'CN' => 'Common Name',
       'OU' => 'Organisation Unit',
       'O' => 'Organisation',
       'C' => 'Country',
       'notBefore' => 'Start Datetime',
       'notAfter' => 'End Datetime'
   }

  return out_array.map { |x| x.split(/=+/) if x.include?("=") }
                  .compact
                  .map { |k, v| [openssl_keys_to_readable_keys.fetch(k, k), v] }
                  .push([openssl_keys_to_readable_keys.fetch("notBefore"), cert.not_before])
                  .push([openssl_keys_to_readable_keys.fetch("notAfter"), cert.not_after])
rescue => ex
  raise Informative, "get_cert_info: #{ex}"
  return {}
end

#install_certs(cert_url: nil, certs_dir: nil, cert_type: nil, platform_type: nil) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/pindo/module/cert/certhelper.rb', line 65

def install_certs(cert_url:nil, certs_dir:nil, cert_type:nil, platform_type:nil)

  cert_git_dir = cert_type.downcase
  if platform_type.downcase.eql?("macos")
    if cert_type.downcase.include?("development")
      cert_git_dir = "development"
    elsif cert_type.downcase.eql?("appstore")
      cert_git_dir = "distribution"
    else
      cert_git_dir = "developer_id_application"
    end
  else
    if !cert_type.downcase.include?("development")
      cert_git_dir = "distribution"
    end
  end

  certs = Dir[File.join(certs_dir, "certs", cert_git_dir.to_s, "*.cer")]
  keys = Dir[File.join(certs_dir, "certs", cert_git_dir.to_s, "*.p12")]      

  if certs.count == 0 || keys.count == 0
    raise Informative, "No certificates found in #{certs_dir}"
  else
      output_dir = Dir.mktmpdir
      
      decrypt_password = AESHelper.fetch_password(keychain_name:cert_url)
      Funlog.instance.fancyinfo_start("正在安装证书...")

      cert_path = AESHelper.decrypt_specific_file(src_file: certs.first, password:decrypt_password, output_dir: output_dir)
      if cert_path.nil? || cert_path.empty? || !File.exist?(cert_path)
        AESHelper.delete_password(keychain_name:cert_url)
        raise Informative, "证书解析失败,密码错误!"
      end

      key_path = AESHelper.decrypt_specific_file(src_file: keys.first, password:decrypt_password, output_dir: output_dir)
      if key_path.nil? || key_path.empty? || !File.exist?(key_path)
        AESHelper.delete_password(keychain_name:cert_url)
        raise Informative, "证书解析失败,密码错误!"
      end

      unless is_cert_valid?(cert_path)
         raise Informative, "证书已经过期,请重新生产新证书!"
      end


      if isMac?

        keychain_name = "login.keychain"
        if FastlaneCore::CertChecker.installed?(cert_path, in_keychain: nil)
          Funlog.instance.fancyinfo_success("证书#{File.basename(cert_path)}已安装,无需重复安装!")
        else

          cert_password = Pindoconfig.instance.cert_key_password
          keychain = 'login.keychain'
          keychain_path = FastlaneCore::Helper.keychain_path(keychain)

          KeychainHelper.import_file(cert_path, keychain_path, keychain_password: cert_password, certificate_password:'' )
          KeychainHelper.import_file(key_path, keychain_path, keychain_password: cert_password, certificate_password: '')

          Funlog.instance.fancyinfo_success("证书'#{File.basename(cert_path)}'安装完成!")

        end
      else
        Funlog.instance.fancyinfo_error("非Mac电脑不支持安装证书!")
      end

  end

  def install_provisionfiles(cert_url:nil, certs_dir:nil, bundle_id_map:nil, cert_type:nil, platform_type:nil)

        cert_sub_dir = cert_type.downcase
        provision_start_name = "Development"
        provision_extension_name = ".mobileprovision"

        if platform_type.downcase.include?("macos")
          provision_extension_name = ".provisionprofile"

          if cert_type.downcase.include?("development")
            provision_start_name = "Development"
            cert_sub_dir = cert_type.downcase
          elsif cert_type.downcase.eql?("appstore")
            provision_start_name = "AppStore"
            cert_sub_dir = "appstore" 
          else
            provision_start_name = "Direct"
            cert_sub_dir = "developer_id"
          end
        else
          provision_extension_name = ".mobileprovision"
          if cert_type.downcase.include?("development")
            provision_start_name = "Development"
            cert_sub_dir = cert_type.downcase
          elsif cert_type.downcase.include?("adhoc")
            provision_start_name = "Adhoc"
            cert_sub_dir = "adhoc"
          else
            provision_start_name = "AppStore"
            cert_sub_dir = "appstore"
          end
        end


        Funlog.instance.fancyinfo_start("正在安装#{provision_start_name}  #{platform_type} Provisioning Profiles...")

        un_exist_files = []
        provisioning_info_array = []
        bundle_id_map.each do |type, bundle_id_temp|
            profile_filename = File.join(certs_dir, "profiles", cert_sub_dir, [provision_start_name.to_s, bundle_id_temp].join('_') + provision_extension_name) 
              unless File.exist?(profile_filename)
                un_exist_files << profile_filename 
                next
              end
              # puts "正在安装 #{bundle_id_temp}..."
              decrypt_password = AESHelper.fetch_password(keychain_name:cert_url)
              output_dir = Dir.mktmpdir
              file_decrypt = AESHelper.decrypt_specific_file(src_file: profile_filename, password:decrypt_password, output_dir: output_dir)
              destpath = Provisioninghelper.install(file_decrypt)
              parsed_data = Provisioninghelper.parse(destpath)

              provisioning_info = {}
              provisioning_info['type'] = type
              provisioning_info['bundle_id'] = bundle_id_temp
              provisioning_info['profile_name'] = parsed_data['Name']
              provisioning_info['profile_path'] = destpath


              cert_info = get_cert_info(parsed_data["DeveloperCertificates"].first.string).to_h
              provisioning_info['signing_identity'] = cert_info["Common Name"]
              provisioning_info['team_id'] = parsed_data["TeamIdentifier"].first

              # puts JSON.pretty_generate(provisioning_info)
              provisioning_info_array << provisioning_info
        end

        Funlog.instance.fancyinfo_success("#{provision_start_name} #{platform_type} Provisioning Profiles文件安装完成!")

        if un_exist_files.size > 0
          Funlog.instance.fancyinfo_error("证书 #{provision_start_name}  #{platform_type} Provisioning Profiles文件不存在!")
          raise Informative, "The following profiles do not exist: #{un_exist_files.join(', ')}"
        end

        return provisioning_info_array
        
  end


end

#install_provisionfiles(cert_url: nil, certs_dir: nil, bundle_id_map: nil, cert_type: nil, platform_type: nil) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/pindo/module/cert/certhelper.rb', line 133

def install_provisionfiles(cert_url:nil, certs_dir:nil, bundle_id_map:nil, cert_type:nil, platform_type:nil)

      cert_sub_dir = cert_type.downcase
      provision_start_name = "Development"
      provision_extension_name = ".mobileprovision"

      if platform_type.downcase.include?("macos")
        provision_extension_name = ".provisionprofile"

        if cert_type.downcase.include?("development")
          provision_start_name = "Development"
          cert_sub_dir = cert_type.downcase
        elsif cert_type.downcase.eql?("appstore")
          provision_start_name = "AppStore"
          cert_sub_dir = "appstore" 
        else
          provision_start_name = "Direct"
          cert_sub_dir = "developer_id"
        end
      else
        provision_extension_name = ".mobileprovision"
        if cert_type.downcase.include?("development")
          provision_start_name = "Development"
          cert_sub_dir = cert_type.downcase
        elsif cert_type.downcase.include?("adhoc")
          provision_start_name = "Adhoc"
          cert_sub_dir = "adhoc"
        else
          provision_start_name = "AppStore"
          cert_sub_dir = "appstore"
        end
      end


      Funlog.instance.fancyinfo_start("正在安装#{provision_start_name}  #{platform_type} Provisioning Profiles...")

      un_exist_files = []
      provisioning_info_array = []
      bundle_id_map.each do |type, bundle_id_temp|
          profile_filename = File.join(certs_dir, "profiles", cert_sub_dir, [provision_start_name.to_s, bundle_id_temp].join('_') + provision_extension_name) 
            unless File.exist?(profile_filename)
              un_exist_files << profile_filename 
              next
            end
            # puts "正在安装 #{bundle_id_temp}..."
            decrypt_password = AESHelper.fetch_password(keychain_name:cert_url)
            output_dir = Dir.mktmpdir
            file_decrypt = AESHelper.decrypt_specific_file(src_file: profile_filename, password:decrypt_password, output_dir: output_dir)
            destpath = Provisioninghelper.install(file_decrypt)
            parsed_data = Provisioninghelper.parse(destpath)

            provisioning_info = {}
            provisioning_info['type'] = type
            provisioning_info['bundle_id'] = bundle_id_temp
            provisioning_info['profile_name'] = parsed_data['Name']
            provisioning_info['profile_path'] = destpath


            cert_info = get_cert_info(parsed_data["DeveloperCertificates"].first.string).to_h
            provisioning_info['signing_identity'] = cert_info["Common Name"]
            provisioning_info['team_id'] = parsed_data["TeamIdentifier"].first

            # puts JSON.pretty_generate(provisioning_info)
            provisioning_info_array << provisioning_info
      end

      Funlog.instance.fancyinfo_success("#{provision_start_name} #{platform_type} Provisioning Profiles文件安装完成!")

      if un_exist_files.size > 0
        Funlog.instance.fancyinfo_error("证书 #{provision_start_name}  #{platform_type} Provisioning Profiles文件不存在!")
        raise Informative, "The following profiles do not exist: #{un_exist_files.join(', ')}"
      end

      return provisioning_info_array
      
end

#is_cert_valid?(cer_certificate_path) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
# File 'lib/pindo/module/cert/certhelper.rb', line 55

def is_cert_valid?(cer_certificate_path)
  cert = OpenSSL::X509::Certificate.new(File.binread(cer_certificate_path))
  now = Time.now.utc
  return (now <=> cert.not_after) == -1
end

#isMac?Boolean

Returns:

  • (Boolean)


61
62
63
# File 'lib/pindo/module/cert/certhelper.rb', line 61

def isMac?
  (/darwin/ =~ RUBY_PLATFORM) != nil
end

#select_cert_or_key(paths:) ⇒ Object



50
51
52
53
# File 'lib/pindo/module/cert/certhelper.rb', line 50

def select_cert_or_key(paths:)
  cert_id_path = ENV['MATCH_CERTIFICATE_ID'] ? paths.find { |path| path.include?(ENV['MATCH_CERTIFICATE_ID']) } : nil
  cert_id_path || paths.last
end