Class: Pod::Command::Allowlist

Inherits:
Pod::Command show all
Defined in:
lib/cocoapods-allowlist/command/allowlist.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv) ⇒ Allowlist



28
29
30
31
32
33
34
35
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 28

def initialize(argv)
  @allowlist_url = argv ? argv.option('config', ConfigURL::ALLOWLIST_SSH) : ConfigURL::ALLOWLIST_SSH
  @pospec_path = argv ? argv.option('podspec') : nil
  @fail_on_error = argv ? argv.flag?('fail-on-error') : false
  @outfile = argv ? argv.option('outfile') : nil
  @failure = false
  super
end

Class Method Details

.optionsObject



20
21
22
23
24
25
26
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 20

def self.options
  [ ['--config=CONFIG', 'Config file or URL for the blacklist'],
    ['--podspec=PODSPEC', 'Podspec file to be lint'],
    ['--fail-on-error', 'Raise an exception in case of error'],
    ['--outfile=PATH', 'Output the linter results to a file']
  ].concat(super)
end

Instance Method Details

#get_podspec_specificationsObject



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 151

def get_podspec_specifications
  if @pospec_path
    return [Pod::Specification.from_file(@pospec_path)]
  end
  # 1 Arg = Search .podspec in current directory
  # 2 Arg = Search .podspec in parent and sub directories. Some projects have Podfile into a subdirectory ("Example"), and run "pod install" from there.
  # 3 Arg = Search .podspec in all directories
  # 4 Arg = Search .podspec in parent and sub directories. Search is executed from children folder.
  podspec_search_paths = ["./*.podspec", "../*.podspec", "./**/*.podspec", "../**/*.podspec"]
  podspec_search_paths.each do |regex|
    pod_specs = Dir.glob(regex)
    if pod_specs.count != 0
      return pod_specs.map { |path|  Pod::Specification.from_file(path) }
    end
  end
end

#is_excluded?(spec_name) ⇒ Boolean

Check if a specification name matches any excluded pattern Supports both exact matches and wildcard patterns (using *)



211
212
213
214
215
216
217
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 211

def is_excluded?(spec_name)
  return false unless @excluded_list

  @excluded_list.any? do |excluded|
    spec_name.match?(/^#{Regexp.escape(excluded.name)}/)
  end
end

#load_excludedObject

Load a list of pods excluded from the validations, wrapped in ValidationExcluded.



193
194
195
196
197
198
199
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 193

def load_excluded
  path = File.expand_path("../../exclude/excluded.json", __FILE__)
  Pod::UI.notice "Path for excluded list is @:#{path}"
  file = File.read(path)
  @excluded_list = parse_excluded(file)
  @excluded_list_loaded = true
end

#parse_excluded(list) ⇒ Object

Aux function to populate the ValidationExcluded models from the JSON data.



202
203
204
205
206
207
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 202

def parse_excluded(list)
  json = JSON.parse(list)
  return json.map { |excluded|
      ValidationExcluded.new(excluded['name'], excluded['rules'])
  }
end

#prepare_outfileObject



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 180

def prepare_outfile
  if @outfile == nil
    return
  end

  if File.exist?(@outfile)
    FileUtils.rm(@outfile)
  elsif File.dirname(@outfile)
    FileUtils.mkdir_p(File.dirname(@outfile))
  end
end

#runObject



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 41

def run
  prepare_outfile
  allowlist = AllowlistResolver.instance.get_allowlist(@allowlist_url)
  load_excluded()
  specifications = get_podspec_specifications

  if specifications == nil || specifications.empty?
      UI.puts "No Podspec found".yellow
      return
  end

  specifications.map do |specification|
    unless is_excluded?(specification.name)
      Pod::UI.notice "#{specification.name} validating"
      validate_dependencies(JSON.parse(specification.to_json), allowlist)
    end
  end

  show_result_message
end

#show_error_message(message) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 168

def show_error_message(message)
  unless @outfile == nil
    IO.write(@outfile, "#{message}\n", mode: 'a')
  end

  if @fail_on_error
    UI.puts message.red
  else
    UI.puts message.yellow
  end
end

#show_result_messageObject



62
63
64
65
66
67
68
69
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 62

def show_result_message
  return unless @failure
  message = "Please check your dependencies.\nYou can see the allowed dependencies at #{ConfigURL::ALLOWLIST_URL}"
  show_error_message(message)
  if @fail_on_error
    raise Informative.new()
  end
end

#validate!Object



37
38
39
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 37

def validate!
  help! "A allowlist file or URL is needed." unless @allowlist_url
end

#validate_dependencies(podspec, allowlist, parentName = nil) ⇒ Object

Checks the dependencies the project contains are in the allowlist



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
# File 'lib/cocoapods-allowlist/command/allowlist.rb', line 72

def validate_dependencies(podspec, allowlist, parentName = nil)
  pod_name = parentName ? "#{parentName}/#{podspec['name']}" : podspec['name']
  UI.puts "Verifying dependencies in #{pod_name}".green

  dependencies = podspec["dependencies"] ? podspec["dependencies"] : []
  not_allowed = []
  alert_allowed = []

  dependencies.each do |name, versions|
    # Skip subspec dependency
    next if parentName && name.start_with?("#{parentName}/")

    if versions.length != 1
      not_allowed.push("#{name} (#{versions.join(", ")}) Reason: A specific version must be defined for every dependency (just one). " +
      "Suggestion: find this dependency in your Podspec and add the version listed in the allowlist.")
      next
    end

    allowedDependency = allowlist.select { |item|
      (/^#{item.name}/ =~ name) && (!item.version || versions.grep(/#{item.version}/).any?) && (item.target == 'production')
    }

    allowedDependency.each { |dependency|

      # Checks the granularity 
      if dependency.allows_granular_projects != nil
        granular_projects = dependency.allows_granular_projects.select { |granular_project|
          granular_project == pod_name
        }

        if granular_projects.empty?
          not_allowed.push("#{name} Reason: Granular dependency not allowed for this project.")
          next
        end
      end
    
      # Checks if any of the allowed dependencies are expired, if so, fail with error
      if dependency.expired?
        not_allowed.push("#{name} Reason: Expired version. Please check the allowlist.")
      end

      # Check if any of the allowed dependencies are close to expiring, if so, fail with error
      if dependency.expiring?
        alert_allowed.push("#{name} Reason: Version will expire in #{dependency.expires}. Please check your dependencies.")
      end

    }
    
    if allowedDependency.empty?
      not_allowed.push("#{name} (#{versions.join(", ")}) Reason: Specified version hasn't match any allowlisted version or Pod name is not valid")
      next
    end
  end

  if not_allowed.any?
    severity = @fail_on_error ? "Error" : "Warning"
    show_error_message(" #{severity}: Found dependencies not allowed:")
    not_allowed.each {|dependency| show_error_message("  - #{dependency}")}
    @failure = true
  else
    UI.puts " OK".green
  end


  if alert_allowed.any?          
    show_error_message(" Warning: Found dependencies allowed that contain warnings:")
    alert_allowed.each {|dependency| show_error_message("  - #{dependency}")}
  else
    UI.puts " OK".green
  end

  # Validate subspecs dependencies
  if podspec["subspecs"]
    podspec["subspecs"].each do |subspec|
      validate_dependencies(subspec, allowlist, pod_name)
    end
  end
end