Module: Pindo::CertHelper

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

Constant Summary collapse

@@password_cache =

密码缓存,避免重复获取相同URL的密码

{}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.clear_password_cacheObject

清除密码缓存



29
30
31
# File 'lib/pindo/module/cert/certhelper.rb', line 29

def self.clear_password_cache
  @@password_cache.clear
end

.clear_password_cache_for_url(cert_url) ⇒ Object

清除特定URL的密码缓存



34
35
36
# File 'lib/pindo/module/cert/certhelper.rb', line 34

def self.clear_password_cache_for_url(cert_url)
  @@password_cache.delete(cert_url)
end

.get_cached_password(cert_url) ⇒ Object

获取密码的辅助方法,使用缓存避免重复获取



17
18
19
20
21
22
23
24
25
26
# File 'lib/pindo/module/cert/certhelper.rb', line 17

def self.get_cached_password(cert_url)
  unless @@password_cache[cert_url]
    puts "\e[33m[DEBUG] 密码缓存中未找到,从Keychain获取: #{cert_url}\e[0m" if ENV['PINDO_DEBUG']
    @@password_cache[cert_url] = AESHelper.fetch_password(keychain_name: cert_url)
    puts "\e[32m[DEBUG] 密码已缓存: #{cert_url}\e[0m" if ENV['PINDO_DEBUG']
  else
    puts "\e[32m[DEBUG] 从密码缓存获取: #{cert_url}\e[0m" if ENV['PINDO_DEBUG']
  end
  @@password_cache[cert_url]
end

Instance Method Details

#get_cert_info(cer_certificate) ⇒ Object



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

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



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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/pindo/module/cert/certhelper.rb', line 89

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 = CertHelper.get_cached_password(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)
        # 清除内存中的密码缓存,避免重复使用错误密码
        @@password_cache.delete(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)
        # 清除内存中的密码缓存,避免重复使用错误密码
        @@password_cache.delete(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 = []
        
        # 在循环外获取密码,避免重复添加到Keychain
        decrypt_password = CertHelper.get_cached_password(cert_url)
        
        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}..."
              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



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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/pindo/module/cert/certhelper.rb', line 161

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 = []
      
      # 在循环外获取密码,避免重复添加到Keychain
      decrypt_password = CertHelper.get_cached_password(cert_url)
      
      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}..."
            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)


79
80
81
82
83
# File 'lib/pindo/module/cert/certhelper.rb', line 79

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)


85
86
87
# File 'lib/pindo/module/cert/certhelper.rb', line 85

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

#select_cert_or_key(paths:) ⇒ Object



74
75
76
77
# File 'lib/pindo/module/cert/certhelper.rb', line 74

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