Module: BranchIOCLI::Helper::IOSHelper

Includes:
Methods
Included in:
BranchHelper
Defined in:
lib/branch_io_cli/helper/ios_helper.rb

Constant Summary collapse

"applinks"
ASSOCIATED_DOMAINS =
"com.apple.developer.associated-domains"
CODE_SIGN_ENTITLEMENTS =
"CODE_SIGN_ENTITLEMENTS"
DEVELOPMENT_TEAM =
"DEVELOPMENT_TEAM"
PRODUCT_BUNDLE_IDENTIFIER =
"PRODUCT_BUNDLE_IDENTIFIER"
RELEASE_CONFIGURATION =
"Release"

Instance Method Summary collapse

Methods included from Methods

#clear, #confirm, #sh

Instance Method Details



76
77
78
79
80
81
82
83
84
85
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 76

def add_branch_universal_link_domains_to_info_plist(domains)
  # Add all supplied domains unless all are app.link domains.
  return if domains.all? { |d| d =~ /app\.link$/ }

  config.xcodeproj.build_configurations.each do |c|
    update_info_plist_setting c.name do |info_plist|
      info_plist["branch_universal_link_domains"] = domains
    end
  end
end

#add_custom_build_settingObject



35
36
37
38
39
40
41
42
43
44
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 35

def add_custom_build_setting
  return unless config.setting

  config.target.build_configurations.each do |c|
    key = uses_test_key?(c) ? config.keys[:test] : config.keys[:live]
    # Reuse the same key if both not present
    key ||= uses_test_key?(c) ? config.keys[:live] : config.keys[:test]
    c.build_settings[config.setting] = key
  end
end

#add_keys_to_info_plist(keys) ⇒ Object



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
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 46

def add_keys_to_info_plist(keys)
  if has_multiple_info_plists?
    config.xcodeproj.build_configurations.each do |c|
      update_info_plist_setting c.name do |info_plist|
        if keys.count > 1 && !config.setting
          # Use test key in debug configs and live key in release configs
          info_plist["branch_key"] = c.debug? ? keys[:test] : keys[:live]
        elsif config.setting
          info_plist["branch_key"] = "$(#{config.setting})"
        else
          info_plist["branch_key"] = keys[:live] ? keys[:live] : keys[:test]
        end
      end
    end
  else
    update_info_plist_setting RELEASE_CONFIGURATION do |info_plist|
      # add/overwrite Branch key(s)
      if keys.count > 1 && !config.setting
        info_plist["branch_key"] = keys
      elsif config.setting
        info_plist["branch_key"] = "$(#{config.setting})"
      elsif keys[:live]
        info_plist["branch_key"] = keys[:live]
      else
        info_plist["branch_key"] = keys[:test]
      end
    end
  end
end


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
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 133

def add_universal_links_to_project(domains, remove_existing, configuration = RELEASE_CONFIGURATION)
  project = config.xcodeproj
  target = config.target

  relative_entitlements_path = target.expanded_build_setting CODE_SIGN_ENTITLEMENTS, configuration
  project_parent = File.dirname project.path

  if relative_entitlements_path.nil?
    relative_entitlements_path = File.join target.name, "#{target.name}.entitlements"
    entitlements_path = File.expand_path relative_entitlements_path, project_parent

    # Add CODE_SIGN_ENTITLEMENTS setting to each configuration
    target.build_configuration_list.set_setting CODE_SIGN_ENTITLEMENTS, relative_entitlements_path

    # Add the file to the project
    project.new_file relative_entitlements_path

    entitlements = {}
    current_domains = []

    add_change project.path
    new_path = entitlements_path
  else
    entitlements_path = File.expand_path relative_entitlements_path, project_parent
    # Raises
    entitlements = File.open(entitlements_path) { |f| Plist.parse_xml f }
    raise "Failed to parse entitlements file #{entitlements_path}" if entitlements.nil?

    if remove_existing
      current_domains = []
    else
      current_domains = entitlements[ASSOCIATED_DOMAINS]
    end
  end

  current_domains += domains.map { |d| "#{APPLINKS}:#{d}" }
  all_domains = current_domains.uniq

  entitlements[ASSOCIATED_DOMAINS] = all_domains

  Plist::Emit.save_plist entitlements, entitlements_path
  add_change entitlements_path

  new_path
end

#app_ids_from_aasa_file(domain) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 230

def app_ids_from_aasa_file(domain)
  data = contents_of_aasa_file domain
  # errors reported in the method above
  return nil if data.nil?

  # raises
  file = JSON.parse data

  applinks = file[APPLINKS]
  @errors << "[#{domain}] No #{APPLINKS} found in AASA file" and return if applinks.nil?

  details = applinks["details"]
  @errors << "[#{domain}] No details found for #{APPLINKS} in AASA file" and return if details.nil?

  identifiers = details.map { |d| d["appID"] }.uniq
  @errors << "[#{domain}] No appID found in AASA file" and return if identifiers.count <= 0
  identifiers
rescue JSON::ParserError => e
  @errors << "[#{domain}] Failed to parse AASA file: #{e.message}"
  nil
end

#configObject



20
21
22
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 20

def config
  Configuration::Configuration.current
end

#contents_of_aasa_file(domain) ⇒ Object



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 252

def contents_of_aasa_file(domain)
  uris = [
    URI("https://#{domain}/.well-known/apple-app-site-association"),
    URI("https://#{domain}/apple-app-site-association")
    # URI("http://#{domain}/.well-known/apple-app-site-association"),
    # URI("http://#{domain}/apple-app-site-association")
  ]

  data = nil

  uris.each do |uri|
    break unless data.nil?

    Net::HTTP.start uri.host, uri.port, use_ssl: uri.scheme == "https" do |http|
      request = Net::HTTP::Get.new uri
      response = http.request request

      # Better to use Net::HTTPRedirection and Net::HTTPSuccess here, but
      # having difficulty with the unit tests.
      if (300..399).cover?(response.code.to_i)
        say "#{uri} cannot result in a redirect. Ignoring."
        next
      elsif response.code.to_i != 200
        # Try the next URI.
        say "Could not retrieve #{uri}: #{response.code} #{response.message}. Ignoring."
        next
      end

      content_type = response["Content-type"]
      @errors << "[#{domain}] AASA Response does not contain a Content-type header" and next if content_type.nil?

      case content_type
      when %r{application/pkcs7-mime}
        # Verify/decrypt PKCS7 (non-Branch domains)
        cert_store = OpenSSL::X509::Store.new
        signature = OpenSSL::PKCS7.new response.body
        # raises
        signature.verify nil, cert_store, nil, OpenSSL::PKCS7::NOVERIFY
        data = signature.data
      else
        @error << "[#{domain}] Unsigned AASA files must be served via HTTPS" and next if uri.scheme == "http"
        data = response.body
      end

      say "GET #{uri}: #{response.code} #{response.message} (Content-type:#{content_type}) ✅"
    end
  end

  @errors << "[#{domain}] Failed to retrieve AASA file" and return nil if data.nil?

  data
rescue IOError, SocketError => e
  @errors << "[#{domain}] Socket error: #{e.message}"
  nil
rescue OpenSSL::PKCS7::PKCS7Error => e
  @errors << "[#{domain}] Failed to verify signed AASA file: #{e.message}"
  nil
end

#domains_from_project(configuration = RELEASE_CONFIGURATION) ⇒ Object



393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 393

def domains_from_project(configuration = RELEASE_CONFIGURATION)
  project = config.xcodeproj
  target = config.target

  relative_entitlements_path = target.expanded_build_setting CODE_SIGN_ENTITLEMENTS, configuration
  return [] if relative_entitlements_path.nil?

  project_parent = File.dirname project.path
  entitlements_path = File.expand_path relative_entitlements_path, project_parent

  # Raises
  entitlements = File.open(entitlements_path) { |f| Plist.parse_xml f }
  raise "Failed to parse entitlements file #{entitlements_path}" if entitlements.nil?

  associated_domains = entitlements[ASSOCIATED_DOMAINS]
  return [] if associated_domains.nil?

  associated_domains.select { |d| d =~ /^applinks:/ }.map { |d| d.sub(/^applinks:/, "") }
end

#ensure_uri_scheme_in_info_plistObject



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
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 87

def ensure_uri_scheme_in_info_plist
  uri_scheme = config.uri_scheme

  # No URI scheme specified. Do nothing.
  return if uri_scheme.nil?

  config.xcodeproj.build_configurations.each do |c|
    update_info_plist_setting c.name do |info_plist|
      url_types = info_plist["CFBundleURLTypes"] || []
      uri_schemes = url_types.inject([]) { |schemes, t| schemes + t["CFBundleURLSchemes"] }

      # Already present. Don't mess with the identifier.
      next if uri_schemes.include? uri_scheme

      # Not found. Add. Don't worry about the CFBundleURLName (reverse-DNS identifier)
      # TODO: Should we prompt here to add or let them change the Dashboard? If there's already
      # a URI scheme in the app, seems likely they'd want to use it. They may have just made
      # a typo at the CLI or in the Dashboard.
      url_types << {
        "CFBundleURLSchemes" => [uri_scheme]
      }
      info_plist["CFBundleURLTypes"] = url_types
    end
  end
end

#has_multiple_info_plists?Boolean

Returns:

  • (Boolean)


24
25
26
27
28
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 24

def has_multiple_info_plists?
  config.xcodeproj.build_configurations.inject([]) do |files, c|
    files + [config.target.expanded_build_setting("INFOPLIST_FILE", c.name)]
  end.uniq.count > 1
end

#report_app_id_mismatch(domain, app_id, identifiers) ⇒ Object



330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 330

def report_app_id_mismatch(domain, app_id, identifiers)
  error_string = "[#{domain}] appID mismatch. Project #{reportable_app_id app_id}\n"
  if identifiers.count <= 20
    error_string << " Apps from AASA:\n"
    identifiers.each do |identifier|
      reportable = reportable_app_id identifier
      error_string << "  #{reportable}\n"
    end
  else
    error_string << " Please check your settings in the Branch Dashboard (https://dashboard.branch.io)"
  end

  @errors << error_string
end

#reportable_app_id(identifier) ⇒ Object



184
185
186
187
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 184

def reportable_app_id(identifier)
  team, bundle = team_and_bundle_from_app_id identifier
  "Signing team: #{team.inspect}, Bundle identifier: #{bundle.inspect}"
end

#target_from_project(project, target_name) ⇒ Object



378
379
380
381
382
383
384
385
386
387
388
389
390
391
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 378

def target_from_project(project, target_name)
  if target_name
    target = project.targets.find { |t| t.name == target_name }
    raise "Target #{target} not found" if target.nil?
  elsif config.respond_to?(:scheme) && project.targets.map(&:name).include?(config.scheme)
    # Return a target with the same name as the scheme, if there is one.
    target = project.targets.find { |t| t.name == config.scheme }
  else
    # find the first application target
    target = project.targets.find { |t| t.name == File.basename(project.path, '.xcodeproj') } ||
             project.targets.select { |t| !t.extension_target_type? && !t.test_target_type? }.first
  end
  target
end

#team_and_bundle_from_app_id(identifier) ⇒ Object



179
180
181
182
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 179

def team_and_bundle_from_app_id(identifier)
  matches = /^(.*?)\.(.*)$/.match identifier
  matches[1, 2]
end

#update_info_plist_setting(configuration = RELEASE_CONFIGURATION) {|info_plist| ... } ⇒ Object

Yields:

  • (info_plist)


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 113

def update_info_plist_setting(configuration = RELEASE_CONFIGURATION, &b)
  # find the Info.plist paths for this configuration
  info_plist_path = config.target.expanded_build_setting "INFOPLIST_FILE", configuration

  raise "Info.plist not found for configuration #{configuration}" if info_plist_path.nil?

  project_parent = File.dirname config.xcodeproj_path

  info_plist_path = File.expand_path info_plist_path, project_parent

  # try to open and parse the Info.plist (raises)
  info_plist = File.open(info_plist_path) { |f| Plist.parse_xml f }
  raise "Failed to parse #{info_plist_path}" if info_plist.nil?

  yield info_plist

  Plist::Emit.save_plist info_plist, info_plist_path
  add_change info_plist_path
end

#update_team_and_bundle_ids(team, bundle) ⇒ Object



365
366
367
368
369
370
371
372
373
374
375
376
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 365

def update_team_and_bundle_ids(team, bundle)
  target = config.target

  target.build_configuration_list.set_setting PRODUCT_BUNDLE_IDENTIFIER, bundle
  target.build_configuration_list.set_setting DEVELOPMENT_TEAM, team

  # also update the team in the first test target
  target = project.targets.find(&:test_target_type?)
  return if target.nil?

  target.build_configuration_list.set_setting DEVELOPMENT_TEAM, team
end

#update_team_and_bundle_ids_from_aasa_file(domain) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 189

def update_team_and_bundle_ids_from_aasa_file(domain)
  # raises
  identifiers = app_ids_from_aasa_file domain
  raise "Multiple appIDs found in AASA file" if identifiers.count > 1

  identifier = identifiers[0]
  team, bundle = team_and_bundle_from_app_id identifier

  update_team_and_bundle_ids team, bundle
  add_change config.xcodeproj_path
end

#uses_test_key?(build_configuration) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 30

def uses_test_key?(build_configuration)
  return build_configuration.debug? unless config.setting && config.test_configurations
  config.test_configurations.include? build_configuration.name
end

#validate_project_domains(expected, configuration = RELEASE_CONFIGURATION) ⇒ Object



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 345

def validate_project_domains(expected, configuration = RELEASE_CONFIGURATION)
  @errors = []
  project_domains = domains_from_project configuration
  valid = expected.count == project_domains.count
  if valid
    sorted = expected.sort
    project_domains.sort.each_with_index do |domain, index|
      valid = false and break unless sorted[index] == domain
    end
  end

  unless valid
    @errors << "Project domains do not match :domains parameter"
    @errors << "Project domains: #{project_domains}"
    @errors << ":domains parameter: #{expected}"
  end

  valid
end

#validate_team_and_bundle_ids(domain, configuration) ⇒ Object



311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 311

def validate_team_and_bundle_ids(domain, configuration)
  target = config.target

  product_bundle_identifier = target.expanded_build_setting PRODUCT_BUNDLE_IDENTIFIER, configuration
  development_team = target.expanded_build_setting DEVELOPMENT_TEAM, configuration

  identifiers = app_ids_from_aasa_file domain
  return false if identifiers.nil?

  app_id = "#{development_team}.#{product_bundle_identifier}"
  match_found = identifiers.include? app_id

  unless match_found
    report_app_id_mismatch domain, app_id, identifiers
  end

  match_found
end

#validate_team_and_bundle_ids_from_aasa_files(domains = [], remove_existing = false, configuration = RELEASE_CONFIGURATION) ⇒ Object



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
# File 'lib/branch_io_cli/helper/ios_helper.rb', line 201

def validate_team_and_bundle_ids_from_aasa_files(domains = [], remove_existing = false, configuration = RELEASE_CONFIGURATION)
  @errors = []
  valid = true

  # Include any domains already in the project.
  # Raises. Returns a non-nil array of strings.
  if remove_existing
    # Don't validate domains to be removed (#16)
    all_domains = domains
  else
    all_domains = (domains + domains_from_project(configuration)).uniq
  end

  if all_domains.empty?
    # Cannot get here from SetupBranchAction, since the domains passed in will never be empty.
    # If called from ValidateUniversalLinksAction, this is a failure, possibly caused by
    # failure to add applinks:.
    @errors << "No Universal Link domains in project. Be sure each Universal Link domain is prefixed with applinks:."
    return false
  end

  all_domains.each do |domain|
    domain_valid = validate_team_and_bundle_ids domain, configuration
    valid &&= domain_valid
    say "Valid Universal Link configuration for #{domain} ✅" if domain_valid
  end
  valid
end