api_recipes 2.10.3 → 3.0.0.beta1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,179 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ApiRecipes
4
+ module CLI
5
+ # Looks for what api_recipes 3.0 removed or changed. It reads files and
6
+ # never writes one. A result carries the file, the line, the kind and a fixed
7
+ # message: never the text of the line, which can hold a secret.
8
+ class Upgrade
9
+ Finding = Data.define(:file, :line, :kind, :message)
10
+
11
+ Rule = Data.define(:kind, :pattern, :message)
12
+
13
+ RULES = [
14
+ Rule.new(:breaks, /\.route\b/, 'endpoint.route was removed: use response.fill or endpoint.definition'),
15
+ Rule.new(:breaks, /RouteNameClashWithExistentMethod/,
16
+ 'this error class was removed: a name clash is now a warning'),
17
+ Rule.new(:breaks, /RouteAndResourceNamesClashError|MissingRouteAttribute|ProvidedObjectNotAsResponseData|NoConfigurationGivenForEndpoint/,
18
+ 'this error class was removed: nothing raised it, so the rescue clause can go'),
19
+ Rule.new(:breaks, /\.base_configs\b/, 'Api#base_configs was removed: use api.definition'),
20
+ Rule.new(:breaks, /ApiRecipes::Route\b/, 'ApiRecipes::Route was removed: a request is sent with run'),
21
+ Rule.new(:breaks, /ApiRecipes::Settings\b/,
22
+ 'ApiRecipes::Settings was removed: the defaults are listed in the README'),
23
+ Rule.new(:breaks, /\bconfiguration\.setup\b/,
24
+ 'configuration.setup was removed: configure loads the configuration'),
25
+ Rule.new(:breaks, /ApiRecipes\.print_urls/, 'use config.print_urls inside ApiRecipes.configure'),
26
+ Rule.new(:breaks, /_aprcps_|set_authorization_for_api|set_basic_auth_for_api|copy_global_authorizations_to_api/,
27
+ 'internal method removed'),
28
+ Rule.new(:check, /url_encode|CGI\.escape|encode_www_form_component/,
29
+ 'path parameters are now encoded by ApiRecipes: remove manual encoding of values passed to endpoints'),
30
+ Rule.new(:check, /\brescue\s*(=>.*)?$|rescue StandardError/,
31
+ 'a bare rescue now catches ApiRecipes errors too'),
32
+ Rule.new(:check, /\bfollow:/, 'credentials are no longer sent to another origin after a redirect'),
33
+ Rule.new(:check, /\bresponse\.request\b/,
34
+ 'response.request was removed, because the request holds the credentials: ' \
35
+ 'read response.uri, or response.original_response'),
36
+ Rule.new(:check, /\.(deep_merge|deep_symbolize_keys|deep_stringify_keys|symbolize_keys|stringify_keys|extract_options!|assert_valid_keys)\b/,
37
+ 'this method came from api_recipes 2.x unless ActiveSupport is loaded: ' \
38
+ 'define it or add ActiveSupport')
39
+ ].freeze
40
+
41
+ SILENT_CHANGES = [
42
+ 'path parameters encoded by hand: %2F would become %252F, remove the encoding',
43
+ 'a / inside a path parameter to cover several segments: use *name or two placeholders',
44
+ 'debug logs or print_urls output read from STDOUT: set log_to and log_level',
45
+ 'a bare rescue around a call: it now catches the errors of the gem too',
46
+ 'credentials assigned on a class or an instance: they now take effect',
47
+ 'the response body read from the message of a verify_with error: read it from error.response',
48
+ 'a block passed to run whose return value is used: it is now the Response',
49
+ 'apis_configs assigned after the files to discard them: do not assign the files',
50
+ 'a nested endpoint without options under a parent with verify_with: it now inherits the verification',
51
+ 'an endpoint called with, definition, authorization, basic_auth or variables (on an api), or run, url, with or definition (on an endpoint): reach it with []; the warning at configuration reports it',
52
+ 'fill with private setters, or code that relies on swallowed errors: make the setters public, handle the errors',
53
+ 'follow: true together with a credential: the credential no longer follows to another host',
54
+ 'a class with its own host, protocol or port that relied on the global credential: set the credential on the class',
55
+ 'cookies set by a server during a redirect chain: they are no longer carried to the next hop',
56
+ 'api names that are methods of Kernel, such as :open or :format: they raise ApiNameClashError, use as:',
57
+ 'Endpoint#name, #params, #children, #api and Api#name, #configs, #object were removed: use definition (a search cannot tell them from other methods called like that)',
58
+ 'an object restored from a serialized form (Marshal, YAML) has no credential: assign it again',
59
+ 'response.uri leaves out the credential query parameter when the api declares auth type query',
60
+ 'a redirect to a host with non-ASCII characters needs the addressable gem: without it the request raises InvalidUrl',
61
+ 'a base_url with a placeholder in a configuration given as a Hash: it is now an error, use a variable',
62
+ 'response.request was removed, whatever the name of the variable that holds the response: the request holds the credentials, read response.uri or response.original_response',
63
+ 'response.to_s returns the body, as the http.rb response does: it was the default text of the object',
64
+ 'a credential that is not a String, such as a Symbol or a number: it raises InvalidCredential, convert it with to_s',
65
+ 'a {word} in a value of default_headers in a configuration given as a Hash: it is now a variable and must be declared',
66
+ 'respond_to? on a response now tells the truth: it answers true for the methods the response forwards and false for the others',
67
+ 'serializing an Api, an Endpoint or a Response raises TypeError: serialize response.data or response.body.to_s',
68
+ 'a class that includes ApiRecipes and uses a top-level constant named Error, Internals, VERSION or like a new error class of the gem (such as ConfigurationError or InvalidUrl): it now finds the gem\'s constant first, write ::Name in that class; Route and Settings no longer exist, so a top-level Route or Settings is found again'
69
+ ].freeze
70
+
71
+ # Problems met while reading, as "<file>: <reason>". They are not findings:
72
+ # the file could not be checked.
73
+ attr_reader :warnings
74
+
75
+ def initialize(paths, config: [], erb: false)
76
+ @paths = Array(paths)
77
+ @configs = Array(config)
78
+ @erb = erb
79
+ @warnings = []
80
+ end
81
+
82
+ def run
83
+ @warnings = []
84
+ findings = @paths.flat_map { |path| scan_path(path) }
85
+ findings + @configs.flat_map { |file| check_config(file) }
86
+ end
87
+
88
+ # Prints the results on out and the warnings on err. Returns the exit code.
89
+ def report(out, err)
90
+ findings = run
91
+ findings.each { |finding| out.puts format_finding(finding) }
92
+ out.puts
93
+ out.puts 'What this command cannot find'
94
+ SILENT_CHANGES.each { |change| out.puts " - #{change}" }
95
+ out.puts
96
+ @warnings.each { |warning| err.puts warning }
97
+ out.puts summary(findings.size) if findings.any? || @warnings.empty?
98
+ return 1 if findings.any?
99
+
100
+ @warnings.empty? ? 0 : 2
101
+ end
102
+
103
+ private
104
+
105
+ def summary(count)
106
+ case count
107
+ when 0 then 'Nothing to change'
108
+ when 1 then '1 finding'
109
+ else "#{count} findings"
110
+ end
111
+ end
112
+
113
+ def format_finding(finding)
114
+ where = finding.line ? "#{finding.file}:#{finding.line}" : finding.file
115
+ "#{where}: [#{finding.kind}] #{finding.message}"
116
+ end
117
+
118
+ def scan_path(path)
119
+ if File.directory?(path)
120
+ Dir.glob('**/*.rb', base: path).sort.flat_map do |relative|
121
+ file = File.join(path, relative)
122
+ File.directory?(file) ? [] : scan_file(file)
123
+ end
124
+ elsif File.exist?(path)
125
+ scan_file(path)
126
+ else
127
+ @warnings << "#{path}: no such file or directory"
128
+ []
129
+ end
130
+ end
131
+
132
+ def scan_file(file)
133
+ text = read_ruby(file)
134
+ return [] unless text
135
+
136
+ found = []
137
+ text.each_line(chomp: true).with_index(1) do |line, number|
138
+ RULES.each do |rule|
139
+ found << Finding.new(file: file, line: number, kind: rule.kind, message: rule.message) if rule.pattern.match?(line)
140
+ end
141
+ end
142
+ found
143
+ end
144
+
145
+ # Returns the text, or nil after recording why the file was not checked.
146
+ def read_ruby(file)
147
+ bytes = File.binread(file)
148
+ if bytes.include?("\0")
149
+ @warnings << "#{file}: binary file, not checked"
150
+ return nil
151
+ end
152
+ text = bytes.force_encoding(Encoding::UTF_8)
153
+ return text if text.valid_encoding?
154
+
155
+ @warnings << "#{file}: not valid UTF-8, not checked"
156
+ nil
157
+ rescue SystemCallError => e
158
+ @warnings << "#{file}: cannot read (#{e.class.name.split('::').last})"
159
+ nil
160
+ end
161
+
162
+ def check_config(file)
163
+ apis = Configuration.new.read_recipe_file(file, erb: @erb)
164
+ Internals::Compiler.compile_all(apis)
165
+ []
166
+ rescue RecipeFileError => e
167
+ e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
168
+ rescue ConfigurationError => e
169
+ e.errors.map { |problem| config_finding(file, problem) }
170
+ rescue StandardError, ScriptError => e
171
+ [config_finding(file, "could not be evaluated (#{e.class})")]
172
+ end
173
+
174
+ def config_finding(file, message)
175
+ Finding.new(file: file, line: nil, kind: :config, message: message)
176
+ end
177
+ end
178
+ end
179
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'optparse'
4
+ require 'api_recipes'
5
+ require 'api_recipes/version'
6
+ require 'api_recipes/cli/upgrade'
7
+
8
+ module ApiRecipes
9
+ # The api_recipes command. It is not loaded by `require 'api_recipes'`.
10
+ module CLI
11
+ USAGE = <<~TEXT
12
+ Usage: api_recipes COMMAND [options]
13
+
14
+ Commands:
15
+ upgrade [--config FILE]... [--erb] [PATH]...
16
+ Looks in the Ruby files under each PATH for what changed in api_recipes 3.0
17
+ and checks each configuration FILE with the 3.0 rules. It never changes a file.
18
+ A file that contains ERB is evaluated only with --erb: this runs the code in it.
19
+ Exits with 1 if it finds something, 2 if it could not read something, 0 otherwise.
20
+
21
+ Options:
22
+ --version print the version
23
+ --help print this help
24
+ TEXT
25
+
26
+ class << self
27
+ # Returns the exit code.
28
+ def run(argv, out: $stdout, err: $stderr)
29
+ command, *args = argv
30
+ case command
31
+ when '--version', '-v'
32
+ out.puts ApiRecipes::VERSION
33
+ 0
34
+ when '--help', '-h'
35
+ out.puts USAGE
36
+ 0
37
+ when 'upgrade'
38
+ upgrade(args, out, err)
39
+ when nil
40
+ err.puts USAGE
41
+ 2
42
+ else
43
+ err.puts "unknown command: #{command}"
44
+ err.puts USAGE
45
+ 2
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ def upgrade(args, out, err)
52
+ configs = []
53
+ erb = false
54
+ parser = OptionParser.new
55
+ parser.on('--config FILE') { |file| configs << file }
56
+ parser.on('--erb') { erb = true }
57
+ paths = parser.parse(args)
58
+ if paths.empty? && configs.empty?
59
+ err.puts 'upgrade needs a directory or a file to scan, or --config FILE'
60
+ return 2
61
+ end
62
+
63
+ Upgrade.new(paths, config: configs, erb: erb).report(out, err)
64
+ rescue OptionParser::ParseError => e
65
+ err.puts e.message
66
+ 2
67
+ end
68
+ end
69
+ end
70
+ end
@@ -1,74 +1,215 @@
1
+ # frozen_string_literal: true
2
+
1
3
  require 'yaml'
2
4
  require 'erb'
3
5
  require 'logger'
6
+ require 'pathname'
4
7
 
5
8
  module ApiRecipes
6
9
  class Configuration
7
10
 
8
- attr_accessor :log_to, :log_level, :print_urls, :apis_files_paths
11
+ attr_accessor :upgrade_warnings
12
+ attr_reader :log_to, :log_level, :print_urls
13
+ attr_reader :variables
14
+
15
+ def initialize
16
+ @sources = []
17
+ @apis_configs = {}
18
+ @apis_files_paths = []
19
+ @variables = {}
20
+ @print_urls = false
21
+ @upgrade_warnings = true
22
+ end
23
+
24
+ # configure works on a copy: what a setter or the caller can change in
25
+ # place (the list of sources, and the Hashes, Arrays and Strings of
26
+ # apis_configs, apis_files_paths and variables at every depth) is copied,
27
+ # so the original stays as it was. The logger of the application is shared.
28
+ def initialize_copy(source)
29
+ super
30
+ @default_logger = nil
31
+ @sources = @sources.dup
32
+ @apis_configs = deep_copy(@apis_configs)
33
+ @apis_files_paths = deep_copy(@apis_files_paths)
34
+ @variables = deep_copy(@variables)
35
+ end
36
+
37
+ # The descriptions of the apis and the variables can hold secrets (header
38
+ # values, tenant names): only the names of the apis are shown.
39
+ def inspect
40
+ "#<#{self.class.name} apis_configs: #{@apis_configs.keys.inspect} " \
41
+ "apis_files_paths: #{@apis_files_paths.size} print_urls: #{@print_urls.inspect}>"
42
+ end
43
+
44
+ def to_s = inspect
45
+
46
+ def pretty_print(queue) = queue.text(inspect)
9
47
 
10
48
  def apis_configs=(configs = {})
11
49
  raise ArgumentError, 'apis_configs must be an Hash' unless configs.is_a? Hash
12
50
 
13
- @apis_configs = configs.deep_symbolize_keys
51
+ @apis_configs = Internals::Compiler.normalize(configs, :options_map)
52
+ record_source(:hash)
14
53
  end
15
54
 
16
- def apis_configs
17
- unless @apis_configs
18
- @apis_configs = {}
19
- end
20
- @apis_configs
21
- end
55
+ attr_reader :apis_configs, :apis_files_paths
22
56
 
23
57
  def apis_files_paths=(paths = [])
24
58
  raise ArgumentError, 'apis_files_paths must be an Array' unless paths.is_a? Array
25
59
 
26
60
  @apis_files_paths = paths
27
- @apis_files_paths.each do |file_path|
28
- template = ERB.new File.read File.expand_path(file_path)
29
- data = begin
30
- YAML.load(template.result(binding), aliases: true)
31
- rescue ArgumentError
32
- YAML.load(template.result binding)
33
- end.deep_symbolize_keys
34
- # Merge file contents into apis_configs
35
- data.each do |api, params|
36
- if apis_configs[api]
37
- logger.debug "File at #{file_path} overrides config for '#{api}' API"
38
- end
39
- apis_configs[api] = params
61
+ record_source(:files)
62
+ end
63
+
64
+ def variables=(variables)
65
+ raise ArgumentError, 'variables must be an Hash' unless variables.is_a? Hash
66
+
67
+ @variables = variables
68
+ end
69
+
70
+ # Applies the sources in the order they were assigned and returns the
71
+ # apis as { name => description }. A later source replaces whole apis.
72
+ def load
73
+ apis = {}
74
+ @sources.each do |kind|
75
+ if kind == :hash
76
+ apis.merge!(@apis_configs)
77
+ else
78
+ @apis_files_paths.each { |path| merge_file(apis, path) }
40
79
  end
41
80
  end
81
+ apis
42
82
  end
43
83
 
44
- def apis_files_paths
45
- unless @apis_files_paths
46
- @apis_files_paths = []
47
- end
48
- @apis_files_paths
84
+ # Reads one file with the rules of apis_files_paths and returns the apis as
85
+ # { name => description }. ERB is evaluated only with erb: true; without it a
86
+ # file that contains ERB is refused and nothing in it is run.
87
+ def read_recipe_file(path, erb: true)
88
+ read_file(path, erb: erb)
49
89
  end
50
90
 
51
91
  def logger=(logger)
52
92
  @logger = logger
53
93
  end
54
94
 
95
+ # The logger of the application, or one that writes to log_to or STDERR at
96
+ # warn level: normal use prints nothing, the warnings show.
55
97
  def logger
56
- unless @logger
57
- log = ::Logger.new(log_to || STDOUT)
58
- log.level = normalize_log_level
59
- log.progname = 'ApiRecipes'
60
- @logger = log
61
- end
98
+ @logger || (@default_logger ||= default_logger)
99
+ end
100
+
101
+ # The default logger is built from the options as they are when it is
102
+ # first needed, so changing one of them drops it.
103
+ def log_to=(target)
104
+ @default_logger = nil
105
+ @log_to = target
106
+ end
62
107
 
63
- @logger
108
+ def log_level=(level)
109
+ @default_logger = nil
110
+ @log_level = level
64
111
  end
65
112
 
66
- def setup
67
- ApiRecipes._aprcps_define_global_apis
113
+ def print_urls=(value)
114
+ @default_logger = nil
115
+ @print_urls = value
68
116
  end
69
117
 
70
118
  private
71
119
 
120
+ # @private
121
+ def record_source(kind)
122
+ @sources.delete(kind)
123
+ @sources << kind
124
+ end
125
+
126
+ # @private
127
+ def merge_file(apis, path)
128
+ read_file(path).each do |api, params|
129
+ logger.debug "File at #{path} overrides config for '#{api}' API" if apis.key?(api)
130
+ apis[api] = params
131
+ end
132
+ end
133
+
134
+ # @private
135
+ def read_file(path, erb: true)
136
+ unless (path.is_a?(String) || path.is_a?(Pathname)) && !path.to_s.include?("\0")
137
+ raise ConfigurationError.new(['apis_files_paths: every path must be a String or a Pathname, without null bytes'])
138
+ end
139
+
140
+ full_path = File.expand_path(path)
141
+ if shared_recipe?(full_path)
142
+ raise RecipeFileError.new(path, 'shared recipe files (.recipe.yml) are not supported by this version')
143
+ end
144
+
145
+ text = read_text(path, full_path)
146
+ if erb
147
+ text = ERB.new(text).result
148
+ elsif text.include?('<%')
149
+ raise RecipeFileError.new(path, 'contains ERB: run again with --erb to evaluate it ' \
150
+ '(this executes the code in the file)')
151
+ end
152
+ data = begin
153
+ YAML.safe_load(text, permitted_classes: [Symbol], aliases: true)
154
+ rescue Psych::Exception => e
155
+ raise RecipeFileError.new(path, "invalid YAML: #{e.message}")
156
+ end
157
+ raise RecipeFileError.new(path, 'file is empty') if data.nil?
158
+ raise RecipeFileError.new(path, 'must contain a mapping of api names') unless data.is_a?(Hash)
159
+
160
+ Internals::Compiler.normalize(data, :options_map)
161
+ end
162
+
163
+ # @private
164
+ def read_text(path, full_path)
165
+ text = File.read(full_path, encoding: 'UTF-8')
166
+ raise RecipeFileError.new(path, 'file is not valid UTF-8') unless text.valid_encoding?
167
+
168
+ text
169
+ rescue Errno::ENOENT
170
+ raise RecipeFileError.new(path, 'file not found')
171
+ rescue SystemCallError => e
172
+ raise RecipeFileError.new(path, "cannot read file (#{e.class.name.split('::').last})")
173
+ end
174
+
175
+ # @private
176
+ def shared_recipe?(full_path)
177
+ names = [full_path]
178
+ names << File.realpath(full_path) if File.exist?(full_path)
179
+ names.any? { |name| name.downcase.end_with?('.recipe.yml') }
180
+ end
181
+
182
+ # @private
183
+ # A copy of value whose Hashes, Arrays and unfrozen Strings are new
184
+ # objects; any other object is the same. A Hash or Array met twice, or
185
+ # that contains itself, is copied once.
186
+ def deep_copy(value, memo = {}.compare_by_identity)
187
+ case value
188
+ when Hash
189
+ return memo[value] if memo.key?(value)
190
+
191
+ copy = memo[value] = {}
192
+ value.each { |key, item| copy[deep_copy(key, memo)] = deep_copy(item, memo) }
193
+ copy
194
+ when Array
195
+ return memo[value] if memo.key?(value)
196
+
197
+ copy = memo[value] = []
198
+ value.each { |item| copy << deep_copy(item, memo) }
199
+ copy
200
+ when String then value.frozen? ? value : value.dup
201
+ else value
202
+ end
203
+ end
204
+
205
+ # @private
206
+ def default_logger
207
+ log = ::Logger.new(log_to || $stderr)
208
+ log.level = normalize_log_level
209
+ log.progname = 'ApiRecipes'
210
+ log
211
+ end
212
+
72
213
  # @private
73
214
  def normalize_log_level
74
215
  case @log_level
@@ -78,8 +219,16 @@ module ApiRecipes
78
219
  when :error, ::Logger::ERROR, 'error' then ::Logger::ERROR
79
220
  when :fatal, ::Logger::FATAL, 'fatal' then ::Logger::FATAL
80
221
  else
81
- ENV['LOG_LEVEL'] || Logger::DEBUG
222
+ env_log_level || (print_urls ? ::Logger::INFO : ::Logger::WARN)
82
223
  end
83
224
  end
225
+
226
+ # @private
227
+ # The level named by LOG_LEVEL in any letter case, or nil: a value that is
228
+ # not a level is ignored.
229
+ def env_log_level
230
+ name = ENV['LOG_LEVEL'].to_s.strip.downcase
231
+ %w[debug info warn error fatal].index(name)
232
+ end
84
233
  end
85
234
  end