api_recipes 3.0.0.beta3 → 3.0.0.beta4
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.
- checksums.yaml +4 -4
- data/README.md +194 -8
- data/UPGRADING.md +84 -26
- data/lib/api_recipes/cli/code.rb +153 -0
- data/lib/api_recipes/cli/convert/migration.rb +624 -0
- data/lib/api_recipes/cli/convert/snippet.rb +67 -0
- data/lib/api_recipes/cli/convert.rb +533 -0
- data/lib/api_recipes/cli/recipes/summary.rb +23 -4
- data/lib/api_recipes/cli/routes.rb +1 -1
- data/lib/api_recipes/cli/upgrade/project.rb +194 -0
- data/lib/api_recipes/cli/upgrade.rb +353 -24
- data/lib/api_recipes/cli.rb +94 -7
- data/lib/api_recipes/configuration.rb +18 -5
- data/lib/api_recipes/endpoint.rb +1 -1
- data/lib/api_recipes/internals/compiler.rb +28 -0
- data/lib/api_recipes/internals/context.rb +35 -6
- data/lib/api_recipes/internals/definition.rb +1 -1
- data/lib/api_recipes/internals/option_value.rb +92 -0
- data/lib/api_recipes/internals/request.rb +17 -6
- data/lib/api_recipes/version.rb +1 -1
- data/lib/api_recipes.rb +1 -0
- metadata +7 -1
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'yaml'
|
|
4
|
+
|
|
5
|
+
module ApiRecipes
|
|
6
|
+
module CLI
|
|
7
|
+
class Upgrade
|
|
8
|
+
# The project in a directory, as `api_recipes upgrade` without arguments
|
|
9
|
+
# sees it: its Ruby files, the files that describe an api and the names
|
|
10
|
+
# of its apis. It reads files and never runs one, and it does not follow
|
|
11
|
+
# a symbolic link.
|
|
12
|
+
class Project
|
|
13
|
+
# Top-level folders that hold no code of the project.
|
|
14
|
+
SKIPPED = %w[vendor node_modules tmp log coverage public storage].freeze
|
|
15
|
+
# Folders skipped wherever they are.
|
|
16
|
+
SKIPPED_ANYWHERE = %w[node_modules].freeze
|
|
17
|
+
# Top-level folders whose YAML files are fixtures, not the configuration.
|
|
18
|
+
NO_CONFIGURATION = %w[spec test features].freeze
|
|
19
|
+
RUBY = /\.(rb|rake)\z/
|
|
20
|
+
YAML_FILE = /\.(yml|yaml)(\.erb)?\z/
|
|
21
|
+
# The line of a file that ERB shapes, which cannot be parsed: enough
|
|
22
|
+
# to report it.
|
|
23
|
+
ENDPOINTS_LINE = /^[ \t]+endpoints:[ \t]*(#.*)?$/
|
|
24
|
+
DECLARATION = /^[ \t]*api[ \t(]+:([A-Za-z_]\w*)(?:.*?\bas:[ \t]*[:'"]([A-Za-z_]\w*))?/
|
|
25
|
+
# A file larger than this is not a description of an api.
|
|
26
|
+
LARGEST = 2 * 1024 * 1024
|
|
27
|
+
# More values than a description holds: aliases make them from a few lines.
|
|
28
|
+
MAX_VALUES = 200_000
|
|
29
|
+
|
|
30
|
+
# api: the name given to `api`; method: the name it is called by.
|
|
31
|
+
Declared = Data.define(:file, :line, :api, :method)
|
|
32
|
+
|
|
33
|
+
# Paths relative to root, sorted. warnings: what could not be read.
|
|
34
|
+
attr_reader :ruby_files, :config_files, :warnings
|
|
35
|
+
|
|
36
|
+
# Whether data holds no more than limit values, aliases counted each
|
|
37
|
+
# time they are used. It stops as soon as the limit is passed.
|
|
38
|
+
def self.within?(data, limit, seen = [0])
|
|
39
|
+
seen[0] += 1
|
|
40
|
+
return false if seen[0] > limit
|
|
41
|
+
|
|
42
|
+
case data
|
|
43
|
+
when Hash then data.all? { |key, inner| within?(key, limit, seen) && within?(inner, limit, seen) }
|
|
44
|
+
when Array then data.all? { |inner| within?(inner, limit, seen) }
|
|
45
|
+
else true
|
|
46
|
+
end
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def initialize(root = '.')
|
|
50
|
+
@root = root
|
|
51
|
+
@ruby_files = []
|
|
52
|
+
@config_files = []
|
|
53
|
+
@warnings = []
|
|
54
|
+
@texts = {}
|
|
55
|
+
@described = []
|
|
56
|
+
walk(nil)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Rails and most applications load ActiveSupport, which defines the
|
|
60
|
+
# Hash methods that api_recipes 2.x also added.
|
|
61
|
+
def active_support?
|
|
62
|
+
lock = File.join(@root, 'Gemfile.lock')
|
|
63
|
+
File.file?(lock) && File.foreach(lock).any? { |line| line.match?(/\A\s+activesupport \(/) }
|
|
64
|
+
rescue SystemCallError, ArgumentError
|
|
65
|
+
false
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# The text of a file of the project, or nil when it is not text.
|
|
69
|
+
def text(file)
|
|
70
|
+
return @texts[file] if @texts.key?(file)
|
|
71
|
+
|
|
72
|
+
@texts[file] = read(file)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# The names an api is called by: those the files describe, and those
|
|
76
|
+
# given to `api` in the code, with `as:` when there is one.
|
|
77
|
+
def api_names
|
|
78
|
+
@api_names ||= (described + declarations.map(&:method)).uniq.sort
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# The apis the files of the project describe.
|
|
82
|
+
def described = @described.uniq
|
|
83
|
+
|
|
84
|
+
# Where the code declares an api: a line that starts with `api :name`.
|
|
85
|
+
def declarations
|
|
86
|
+
@declarations ||= @ruby_files.flat_map do |file|
|
|
87
|
+
found = []
|
|
88
|
+
text(file).to_s.each_line.with_index(1) do |line, number|
|
|
89
|
+
match = DECLARATION.match(line)
|
|
90
|
+
found << Declared.new(file: file, line: number, api: match[1], method: match[2] || match[1]) if match
|
|
91
|
+
end
|
|
92
|
+
found
|
|
93
|
+
end
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# The declarations of an api that no file found here describes, and
|
|
97
|
+
# that do not describe it themselves.
|
|
98
|
+
def undescribed
|
|
99
|
+
return [] if @ruby_files.any? { |file| text(file).to_s.include?('apis_configs') }
|
|
100
|
+
|
|
101
|
+
declarations.reject do |declared|
|
|
102
|
+
described.include?(declared.api) || text(declared.file).to_s.lines[declared.line - 1].to_s.match?(/\b(endpoints|host):/)
|
|
103
|
+
end
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# Whether the code of a Ruby file names the gem or calls one of the
|
|
107
|
+
# apis. Comment lines are not code.
|
|
108
|
+
def uses_gem?(text)
|
|
109
|
+
code = text.each_line.reject { |line| line.lstrip.start_with?('#') }.join
|
|
110
|
+
return true if code.match?(/\bApiRecipes\b/)
|
|
111
|
+
|
|
112
|
+
names = api_names
|
|
113
|
+
!names.empty? && code.match?(%r{(?<![\w/])(?:#{names.map { |name| Regexp.escape(name) }.join('|')})\b[ \t]*(?:\.[a-z_]|\[)})
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
private
|
|
117
|
+
|
|
118
|
+
def walk(directory)
|
|
119
|
+
entries = Dir.children(directory ? File.join(@root, directory) : @root).sort
|
|
120
|
+
entries.each do |name|
|
|
121
|
+
next if name.start_with?('.') || SKIPPED_ANYWHERE.include?(name)
|
|
122
|
+
next if directory.nil? && SKIPPED.include?(name)
|
|
123
|
+
|
|
124
|
+
relative = directory ? File.join(directory, name) : name
|
|
125
|
+
full = File.join(@root, relative)
|
|
126
|
+
next if File.symlink?(full)
|
|
127
|
+
|
|
128
|
+
if File.directory?(full)
|
|
129
|
+
walk(relative)
|
|
130
|
+
elsif File.file?(full)
|
|
131
|
+
keep(relative, name)
|
|
132
|
+
end
|
|
133
|
+
end
|
|
134
|
+
rescue SystemCallError => e
|
|
135
|
+
@warnings << "#{directory || @root}: cannot read (#{e.class.name.split('::').last})"
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def keep(relative, name)
|
|
139
|
+
if RUBY.match?(name)
|
|
140
|
+
@ruby_files << relative
|
|
141
|
+
elsif name.end_with?(Internals::Recipe::SUFFIX)
|
|
142
|
+
@config_files << relative
|
|
143
|
+
@described.concat(apis_in(text(relative)) || [])
|
|
144
|
+
elsif YAML_FILE.match?(name) && !NO_CONFIGURATION.include?(relative.split('/').first)
|
|
145
|
+
names = apis_in(text(relative))
|
|
146
|
+
return if names.nil?
|
|
147
|
+
|
|
148
|
+
@config_files << relative
|
|
149
|
+
@described.concat(names)
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# The names of the apis that text describes, or nil when it describes
|
|
154
|
+
# none. An api is a name with endpoints, each with its options or with
|
|
155
|
+
# none. Tags are read as a word, never run.
|
|
156
|
+
def apis_in(text)
|
|
157
|
+
return nil if text.nil? || !text.include?('endpoints')
|
|
158
|
+
|
|
159
|
+
plain = text.gsub(/<%#.*?%>/m, '').gsub(/<%=.*?%>/m, 'erb')
|
|
160
|
+
return (ENDPOINTS_LINE.match?(text) ? [] : nil) if plain.gsub('<%%', '').include?('<%')
|
|
161
|
+
|
|
162
|
+
data = YAML.safe_load(plain, permitted_classes: [Symbol], aliases: true)
|
|
163
|
+
return nil unless data.is_a?(Hash) && self.class.within?(data, MAX_VALUES)
|
|
164
|
+
|
|
165
|
+
names = data.select { |_, options| api?(options) }.keys.map(&:to_s)
|
|
166
|
+
names.empty? ? nil : names
|
|
167
|
+
rescue Psych::Exception, SystemStackError
|
|
168
|
+
ENDPOINTS_LINE.match?(text) ? [] : nil
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def api?(options)
|
|
172
|
+
return false unless options.is_a?(Hash)
|
|
173
|
+
|
|
174
|
+
endpoints = options['endpoints'] || options[:endpoints]
|
|
175
|
+
endpoints.is_a?(Hash) && endpoints.values.all? { |one| one.nil? || one.is_a?(Hash) }
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def read(file)
|
|
179
|
+
full = File.join(@root, file)
|
|
180
|
+
return nil if File.size(full) > LARGEST
|
|
181
|
+
|
|
182
|
+
bytes = File.binread(full)
|
|
183
|
+
return nil if bytes.include?("\0")
|
|
184
|
+
|
|
185
|
+
text = bytes.force_encoding(Encoding::UTF_8)
|
|
186
|
+
text.valid_encoding? ? text : nil
|
|
187
|
+
rescue SystemCallError => e
|
|
188
|
+
@warnings << "#{file}: cannot read (#{e.class.name.split('::').last})"
|
|
189
|
+
nil
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
end
|
|
@@ -1,49 +1,84 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
+
require 'securerandom'
|
|
4
|
+
require 'api_recipes/cli/upgrade/project'
|
|
5
|
+
|
|
3
6
|
module ApiRecipes
|
|
4
7
|
module CLI
|
|
5
8
|
# Looks for what api_recipes 3.0 removed or changed. It reads files and
|
|
6
9
|
# never writes one. A result carries the file, the line, the kind and a fixed
|
|
7
10
|
# message: never the text of the line, which can hold a secret.
|
|
8
11
|
class Upgrade
|
|
9
|
-
|
|
12
|
+
# hint: lines of code shown under the finding, or nil.
|
|
13
|
+
Finding = Data.define(:file, :line, :kind, :message, :hint) do
|
|
14
|
+
def initialize(file:, line:, kind:, message:, hint: nil) = super
|
|
15
|
+
end
|
|
10
16
|
|
|
11
|
-
|
|
17
|
+
# general: the pattern also matches code that has nothing to do with the
|
|
18
|
+
# gem. In a whole project such a rule is applied only to the files that
|
|
19
|
+
# use the gem.
|
|
20
|
+
# fix: which code to paste the line gives, when it gives one.
|
|
21
|
+
Rule = Data.define(:kind, :pattern, :message, :general, :fix) do
|
|
22
|
+
def initialize(kind:, pattern:, message:, general: false, fix: nil) = super
|
|
23
|
+
end
|
|
12
24
|
|
|
13
25
|
RULES = [
|
|
14
|
-
Rule.new(:breaks, /\.route\b/, 'endpoint.route was removed: use response.fill or endpoint.definition'),
|
|
26
|
+
Rule.new(:breaks, /\.route\b/, 'endpoint.route was removed: use response.fill or endpoint.definition', false, :route),
|
|
15
27
|
Rule.new(:breaks, /RouteNameClashWithExistentMethod/,
|
|
16
28
|
'this error class was removed: a name clash is now a warning'),
|
|
17
29
|
Rule.new(:breaks, /RouteAndResourceNamesClashError|MissingRouteAttribute|ProvidedObjectNotAsResponseData|NoConfigurationGivenForEndpoint/,
|
|
18
30
|
'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'),
|
|
31
|
+
Rule.new(:breaks, /\.base_configs\b/, 'Api#base_configs was removed: use api.definition', false, :base_configs),
|
|
20
32
|
Rule.new(:breaks, /ApiRecipes::Route\b/, 'ApiRecipes::Route was removed: a request is sent with run'),
|
|
21
33
|
Rule.new(:breaks, /ApiRecipes::Settings\b/,
|
|
22
34
|
'ApiRecipes::Settings was removed: the defaults are listed in the README'),
|
|
23
35
|
Rule.new(:breaks, /\bconfiguration\.setup\b/,
|
|
24
36
|
'configuration.setup was removed: configure loads the configuration'),
|
|
25
|
-
Rule.new(:breaks, /ApiRecipes\.print_urls/, 'use config.print_urls inside ApiRecipes.configure'),
|
|
37
|
+
Rule.new(:breaks, /ApiRecipes\.print_urls/, 'use config.print_urls inside ApiRecipes.configure', false, :print_urls),
|
|
26
38
|
Rule.new(:breaks, /_aprcps_|set_authorization_for_api|set_basic_auth_for_api|copy_global_authorizations_to_api/,
|
|
27
39
|
'internal method removed'),
|
|
28
40
|
Rule.new(:breaks, /\bApiRecipes((\.|::)\w+|\[[^\]]*\])\.(authorization|basic_auth)\s*(\|\|)?=(?![=~])/,
|
|
29
41
|
'a credential of the whole application is given to ApiRecipes.configure, as ' \
|
|
30
|
-
'config.values = { name: { authorization: ... } }: this writer now raises'),
|
|
42
|
+
'config.values = { name: { authorization: ... } }: this writer now raises', false, :global_writer),
|
|
31
43
|
Rule.new(:check, /(?<!\bApiRecipes)\.\w+\.(authorization|basic_auth)\s*(\|\|)?=(?![=~])/,
|
|
32
44
|
'authorization= and basic_auth= now work on an object only: on a class they raise, ' \
|
|
33
|
-
'give the credential to `api :name, authorization: ...`, or to with(...) for one request'),
|
|
45
|
+
'give the credential to `api :name, authorization: ...`, or to with(...) for one request', false, :writer),
|
|
34
46
|
Rule.new(:check, /url_encode|CGI\.escape|encode_www_form_component/,
|
|
35
|
-
'path parameters are now encoded by ApiRecipes: remove manual encoding of values passed to endpoints'),
|
|
47
|
+
'path parameters are now encoded by ApiRecipes: remove manual encoding of values passed to endpoints', true),
|
|
36
48
|
Rule.new(:check, /\brescue\s*(=>.*)?$|rescue StandardError/,
|
|
37
|
-
'a bare rescue now catches ApiRecipes errors too'),
|
|
38
|
-
Rule.new(:check, /\bfollow:/, 'credentials are no longer sent to another origin after a redirect'),
|
|
49
|
+
'a bare rescue now catches ApiRecipes errors too', true),
|
|
50
|
+
Rule.new(:check, /\bfollow:/, 'credentials are no longer sent to another origin after a redirect', true),
|
|
39
51
|
Rule.new(:check, /\bresponse\.request\b/,
|
|
40
52
|
'response.request was removed, because the request holds the credentials: ' \
|
|
41
|
-
'read response.uri, or response.original_response'),
|
|
53
|
+
'read response.uri, or response.original_response', true, :request),
|
|
42
54
|
Rule.new(:check, /\.(deep_merge|deep_symbolize_keys|deep_stringify_keys|symbolize_keys|stringify_keys|extract_options!|assert_valid_keys)\b/,
|
|
43
55
|
'this method came from api_recipes 2.x unless ActiveSupport is loaded: ' \
|
|
44
|
-
'define it or add ActiveSupport')
|
|
56
|
+
'define it or add ActiveSupport', true)
|
|
45
57
|
].freeze
|
|
46
58
|
|
|
59
|
+
# The rule about the Hash methods that ActiveSupport defines too.
|
|
60
|
+
HASH_METHODS = RULES.last
|
|
61
|
+
|
|
62
|
+
# What stands for the value of an ERB tag in a file that is checked
|
|
63
|
+
# without running its code.
|
|
64
|
+
# Options whose value is a mapping: a tag that gives one gives a part
|
|
65
|
+
# of the structure, which is not guessed.
|
|
66
|
+
CONTAINERS = %w[variables endpoints default_headers default_params auth recipe resource].freeze
|
|
67
|
+
|
|
68
|
+
# What a line assigns, read without running it, to give the code to paste.
|
|
69
|
+
WRITTEN = '\\s*(?:\\|\\|)?=(?![=~])\\s*(?<code>.+)\\z'
|
|
70
|
+
FIXES = {
|
|
71
|
+
print_urls: /\bApiRecipes\.print_urls#{WRITTEN}/,
|
|
72
|
+
global_writer: /\bApiRecipes(?:(?:\.|::)(?<api>\w+)|\[\s*[:'"](?<api>\w+)['"]?\s*\])\.(?<key>authorization|basic_auth)#{WRITTEN}/,
|
|
73
|
+
writer: /(?<![^\s(=,])(?<receiver>[\w.@:\[\]'"]+)\.(?<api>\w+)\.(?<key>authorization|basic_auth)#{WRITTEN}/,
|
|
74
|
+
base_configs: /(?<![^\s(=,])(?<receiver>[\w.@:\[\]'"]+)\.base_configs\b/,
|
|
75
|
+
route: /\.route\.fill\((?<code>.*)\)/
|
|
76
|
+
}.freeze
|
|
77
|
+
# Code longer than this is not copied into the code to paste.
|
|
78
|
+
MAX_CODE = 300
|
|
79
|
+
ERB_COMMENT = /<%#.*?%>/m
|
|
80
|
+
ERB_OUTPUT = /<%=.*?%>/m
|
|
81
|
+
|
|
47
82
|
SILENT_CHANGES = [
|
|
48
83
|
'path parameters encoded by hand: %2F would become %252F, remove the encoding',
|
|
49
84
|
'a / inside a path parameter to cover several segments: use *name or two placeholders',
|
|
@@ -80,23 +115,54 @@ module ApiRecipes
|
|
|
80
115
|
# the file could not be checked.
|
|
81
116
|
attr_reader :warnings
|
|
82
117
|
|
|
83
|
-
|
|
118
|
+
# What was checked and how, said after the findings. Not findings.
|
|
119
|
+
attr_reader :notes
|
|
120
|
+
|
|
121
|
+
# project: the Project the paths and the files were found in, when the
|
|
122
|
+
# command was given none.
|
|
123
|
+
# code: false leaves out the code to paste, as in a CI whose output is kept.
|
|
124
|
+
def initialize(paths, config: [], erb: false, project: nil, code: true)
|
|
125
|
+
@code = code
|
|
84
126
|
@paths = Array(paths)
|
|
85
127
|
@configs = Array(config)
|
|
86
128
|
@erb = erb
|
|
129
|
+
@project = project
|
|
87
130
|
@warnings = []
|
|
131
|
+
@notes = []
|
|
132
|
+
# What stands for the value of an ERB tag in a file that is checked
|
|
133
|
+
# without running its code: random, so that no file can write it.
|
|
134
|
+
@erb_value = "API_RECIPES_ERB_VALUE_#{SecureRandom.hex(6)}"
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# The command without arguments: the project in the current directory.
|
|
138
|
+
def self.for_project(project, erb: false, code: true)
|
|
139
|
+
new(project.ruby_files, config: project.config_files, erb: erb, project: project, code: code)
|
|
88
140
|
end
|
|
89
141
|
|
|
90
142
|
def run
|
|
91
|
-
@warnings = []
|
|
92
|
-
|
|
93
|
-
|
|
143
|
+
@warnings = @project ? @project.warnings.dup : []
|
|
144
|
+
@notes = []
|
|
145
|
+
@uses = 0
|
|
146
|
+
@startup = []
|
|
147
|
+
@configure = {}
|
|
148
|
+
findings = with_request_hints(@paths.flat_map { |path| scan_path(path) })
|
|
149
|
+
findings += @configs.flat_map { |file| check_config(file) }
|
|
150
|
+
@notes = scope + @notes if @project
|
|
151
|
+
findings
|
|
94
152
|
end
|
|
95
153
|
|
|
96
154
|
# Prints the results on out and the warnings on err. Returns the exit code.
|
|
97
155
|
def report(out, err)
|
|
98
156
|
findings = run
|
|
99
|
-
findings.each
|
|
157
|
+
findings.each do |finding|
|
|
158
|
+
out.puts format_finding(finding)
|
|
159
|
+
Code.show(out, finding.hint) if @code && finding.hint
|
|
160
|
+
end
|
|
161
|
+
unless @notes.empty?
|
|
162
|
+
out.puts unless findings.empty?
|
|
163
|
+
@notes.each { |note| out.puts note }
|
|
164
|
+
end
|
|
165
|
+
code_to_paste(out) if @code
|
|
100
166
|
out.puts
|
|
101
167
|
out.puts 'What this command cannot find'
|
|
102
168
|
SILENT_CHANGES.each { |change| out.puts " - #{change}" }
|
|
@@ -112,20 +178,47 @@ module ApiRecipes
|
|
|
112
178
|
|
|
113
179
|
def summary(count)
|
|
114
180
|
case count
|
|
115
|
-
when 0 then
|
|
181
|
+
when 0 then nothing_found
|
|
116
182
|
when 1 then '1 finding'
|
|
117
183
|
else "#{count} findings"
|
|
118
184
|
end
|
|
119
185
|
end
|
|
120
186
|
|
|
187
|
+
# "Nothing to change" is said only of what was checked.
|
|
188
|
+
def nothing_found
|
|
189
|
+
return 'Nothing to change' unless @project && @configs.empty?
|
|
190
|
+
|
|
191
|
+
'Nothing to change in the Ruby files. No configuration file was found: if the apis are described in ' \
|
|
192
|
+
'YAML files, name each one with --config FILE'
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
# What a run on a project looked at.
|
|
196
|
+
def scope
|
|
197
|
+
ruby = @paths.size
|
|
198
|
+
lines = ["Checked #{ruby} Ruby file#{'s' unless ruby == 1}, #{@uses} of them use#{'s' if @uses == 1} api_recipes"]
|
|
199
|
+
lines << if @configs.empty?
|
|
200
|
+
'No configuration file was found'
|
|
201
|
+
else
|
|
202
|
+
"Checked #{@configs.size} configuration file#{'s' unless @configs.size == 1}: #{@configs.map { |file| shown_path(file) }.join(', ')}"
|
|
203
|
+
end
|
|
204
|
+
lines + @project.undescribed.map do |declared|
|
|
205
|
+
"#{shown_path(declared.file)}:#{declared.line}: declares the api '#{declared.api}', and no configuration file found here describes it"
|
|
206
|
+
end
|
|
207
|
+
end
|
|
208
|
+
|
|
209
|
+
# A name found in the project is shown without what a terminal would
|
|
210
|
+
# obey; a path that was given is shown as it was given.
|
|
211
|
+
def shown_path(file) = @project ? Recipes::Summary.shown(file, 300) : file
|
|
212
|
+
|
|
121
213
|
def format_finding(finding)
|
|
122
|
-
|
|
214
|
+
file = shown_path(finding.file)
|
|
215
|
+
where = finding.line ? "#{file}:#{finding.line}" : file
|
|
123
216
|
"#{where}: [#{finding.kind}] #{finding.message}"
|
|
124
217
|
end
|
|
125
218
|
|
|
126
219
|
def scan_path(path)
|
|
127
220
|
if File.directory?(path)
|
|
128
|
-
Dir.glob('**/*.rb', base: path).sort.flat_map do |relative|
|
|
221
|
+
Dir.glob('**/*.{rb,rake}', base: path).sort.flat_map do |relative|
|
|
129
222
|
file = File.join(path, relative)
|
|
130
223
|
File.directory?(file) ? [] : scan_file(file)
|
|
131
224
|
end
|
|
@@ -141,15 +234,156 @@ module ApiRecipes
|
|
|
141
234
|
text = read_ruby(file)
|
|
142
235
|
return [] unless text
|
|
143
236
|
|
|
237
|
+
rules = rules_for(text)
|
|
238
|
+
@configure[file] = text if text.match?(/\bApiRecipes\.configure\b/)
|
|
144
239
|
found = []
|
|
145
240
|
text.each_line(chomp: true).with_index(1) do |line, number|
|
|
146
|
-
|
|
147
|
-
|
|
241
|
+
rules.each do |rule|
|
|
242
|
+
next unless rule.pattern.match?(line)
|
|
243
|
+
|
|
244
|
+
found << Finding.new(file: file, line: number, kind: rule.kind, message: rule.message, hint: hint(rule.fix, line, file, number, text))
|
|
148
245
|
end
|
|
149
246
|
end
|
|
150
247
|
found
|
|
151
248
|
end
|
|
152
249
|
|
|
250
|
+
# ---- the code to paste ----
|
|
251
|
+
|
|
252
|
+
# The code a line assigns, when it can be copied: on one line, short,
|
|
253
|
+
# and with nothing a terminal would obey.
|
|
254
|
+
def code_of(match)
|
|
255
|
+
code = without_comment(match[:code].to_s.strip)
|
|
256
|
+
return nil if code.empty? || code.length > MAX_CODE || Code::UNSAFE.match?(code) || !expression?(code)
|
|
257
|
+
|
|
258
|
+
code
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
# code up to a comment that follows it on the line.
|
|
262
|
+
def without_comment(code)
|
|
263
|
+
quote = nil
|
|
264
|
+
code.each_char.with_index do |char, index|
|
|
265
|
+
if quote
|
|
266
|
+
quote = nil if char == quote && code[index - 1] != '\\'
|
|
267
|
+
elsif ["'", '"', '`'].include?(char)
|
|
268
|
+
quote = char
|
|
269
|
+
elsif char == '#' && (index.zero? || code[index - 1].match?(/\s/))
|
|
270
|
+
return code[0...index].rstrip
|
|
271
|
+
end
|
|
272
|
+
end
|
|
273
|
+
code
|
|
274
|
+
end
|
|
275
|
+
|
|
276
|
+
# Whether code is one whole Ruby expression, and not one that a word
|
|
277
|
+
# after it changes (if, unless, rescue, and, or). It is read, never run.
|
|
278
|
+
def expression?(code)
|
|
279
|
+
tree = Code.tree(code)
|
|
280
|
+
return false unless tree && tree.statements.body.size == 1
|
|
281
|
+
|
|
282
|
+
node = tree.statements.body.first
|
|
283
|
+
return false if [Prism::IfNode, Prism::UnlessNode, Prism::RescueModifierNode, Prism::WhileNode, Prism::UntilNode].any? { |kind| node.is_a?(kind) }
|
|
284
|
+
|
|
285
|
+
!((node.is_a?(Prism::AndNode) || node.is_a?(Prism::OrNode)) && %w[and or].include?(node.operator_loc.slice))
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
# Whether the statement on line is always run when its file is: a
|
|
289
|
+
# statement of the file itself, or of the block of ApiRecipes.configure,
|
|
290
|
+
# not one inside a condition or another block.
|
|
291
|
+
def always_run?(file, text, line)
|
|
292
|
+
@direct ||= {}
|
|
293
|
+
@direct[file] ||= begin
|
|
294
|
+
tree = Code.tree(text)
|
|
295
|
+
top = tree ? tree.statements.body.map { |node| node.location.start_line } : []
|
|
296
|
+
block = Code::ConfigureBlock.in(text)
|
|
297
|
+
top + (block ? block.statement_lines : [])
|
|
298
|
+
end
|
|
299
|
+
@direct[file].include?(line)
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
# The lines shown under a finding. A value given when the application
|
|
303
|
+
# starts is kept aside: all of them go in one block of configure.
|
|
304
|
+
def hint(fix, line, file, number, text)
|
|
305
|
+
match = FIXES[fix]&.match(line)
|
|
306
|
+
case fix
|
|
307
|
+
when :request then ['response.uri # the address of the request', 'response.original_response # the http.rb response']
|
|
308
|
+
when :base_configs then match && !Code::UNSAFE.match?(match[:receiver]) ? ["#{match[:receiver]}.definition"] : nil
|
|
309
|
+
when :route then (code = match && code_of(match)) ? ["response.fill(#{code}) # response is what run returned"] : nil
|
|
310
|
+
when :writer
|
|
311
|
+
code = match && code_of(match)
|
|
312
|
+
return nil unless code && !Code::UNSAFE.match?(match[:receiver])
|
|
313
|
+
|
|
314
|
+
['# for a class, where it declares the api:', "api :#{match[:api]}, #{match[:key]}: #{code}", '# for one request:',
|
|
315
|
+
"#{match[:receiver]}.#{match[:api]}.with(#{match[:key]}: #{code})"]
|
|
316
|
+
when :print_urls, :global_writer
|
|
317
|
+
code = match && code_of(match)
|
|
318
|
+
return nil unless code && always_run?(file, text, number)
|
|
319
|
+
|
|
320
|
+
@startup << { file: file, line: number, api: fix == :print_urls ? nil : match[:api], key: fix == :print_urls ? 'print_urls' : match[:key], code: code }
|
|
321
|
+
nil
|
|
322
|
+
end
|
|
323
|
+
end
|
|
324
|
+
|
|
325
|
+
# A credential of the application assigned in more than one place is
|
|
326
|
+
# assigned for each request: each of those lines becomes a with.
|
|
327
|
+
def with_request_hints(findings)
|
|
328
|
+
repeated = @startup.group_by { |item| [item[:api], item[:key]] }.select { |(api, _), items| api && items.size > 1 }.values.flatten
|
|
329
|
+
@startup -= repeated
|
|
330
|
+
findings.map do |finding|
|
|
331
|
+
item = repeated.find { |one| one[:file] == finding.file && one[:line] == finding.line }
|
|
332
|
+
next finding unless item && finding.hint.nil? && FIXES[:global_writer].match?('ApiRecipes.x.' + item[:key] + ' = 1') && finding.message.include?('config.values')
|
|
333
|
+
|
|
334
|
+
finding.with(hint: ["ApiRecipes.#{item[:api]}.with(#{item[:key]}: #{item[:code]}) # use the api it returns for the calls of this request"])
|
|
335
|
+
end
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
# The values given when the application starts, in the block of
|
|
339
|
+
# ApiRecipes.configure: the whole block when one file has it.
|
|
340
|
+
def code_to_paste(out)
|
|
341
|
+
return if @startup.empty?
|
|
342
|
+
|
|
343
|
+
file, text = @configure.size == 1 ? @configure.first : nil
|
|
344
|
+
block = Code::ConfigureBlock.in(text)
|
|
345
|
+
block = nil if block&.problem
|
|
346
|
+
config = block ? block.config : 'config'
|
|
347
|
+
inside = @startup.select { |item| block && item[:file] == file && item[:line].between?(block.first, block.last) }
|
|
348
|
+
added = @startup.select { |item| item[:api].nil? }.first(1).map { |item| "#{config}.print_urls = #{item[:code]}" }
|
|
349
|
+
added = [] if block&.line_of(:print_urls)
|
|
350
|
+
entries = @startup.select { |item| item[:api] }.group_by { |item| item[:api] }.map do |api, items|
|
|
351
|
+
"#{api.match?(/\A[a-z_]\w*\z/) ? api : "\"#{api}\""}: { #{items.map { |item| "#{item[:key]}: #{item[:code]}" }.join(', ')} }"
|
|
352
|
+
end
|
|
353
|
+
entries = entries.each_with_index.map { |entry, index| index == entries.size - 1 ? entry : "#{entry}," }
|
|
354
|
+
merged = block && block.line_of(:values)
|
|
355
|
+
added += ["#{config}.values = {", *entries.map { |entry| " #{entry}" }, '}'] unless entries.empty? || merged
|
|
356
|
+
|
|
357
|
+
out.puts '', 'Code to paste', ''
|
|
358
|
+
if block
|
|
359
|
+
out.puts "In #{shown_path(file)}, replace the block of ApiRecipes.configure (lines #{block.first} to #{block.last}) with:"
|
|
360
|
+
Code.show(out, block.lines(added, without: inside.map { |item| item[:line] }))
|
|
361
|
+
else
|
|
362
|
+
out.puts 'Inside the block of ApiRecipes.configure:'
|
|
363
|
+
Code.show(out, added)
|
|
364
|
+
end
|
|
365
|
+
if merged && !entries.empty?
|
|
366
|
+
out.puts "and add to the Hash that #{config}.values is given at line #{merged}:"
|
|
367
|
+
Code.show(out, entries)
|
|
368
|
+
end
|
|
369
|
+
outside = (@startup - inside).map { |item| "#{shown_path(item[:file])}:#{item[:line]}" }
|
|
370
|
+
out.puts "Then remove the lines that gave these values: #{outside.join(', ')}" unless outside.empty?
|
|
371
|
+
end
|
|
372
|
+
|
|
373
|
+
# Every rule for the paths that were given. In a project, the general
|
|
374
|
+
# ones only for a file that uses the gem, and never the one about the
|
|
375
|
+
# methods that ActiveSupport defines when the project has it.
|
|
376
|
+
def rules_for(text)
|
|
377
|
+
return RULES unless @project
|
|
378
|
+
|
|
379
|
+
@specific ||= RULES.reject(&:general)
|
|
380
|
+
@all ||= @project.active_support? ? RULES - [HASH_METHODS] : RULES
|
|
381
|
+
return @specific unless @project.uses_gem?(text)
|
|
382
|
+
|
|
383
|
+
@uses += 1
|
|
384
|
+
@all
|
|
385
|
+
end
|
|
386
|
+
|
|
153
387
|
# Returns the text, or nil after recording why the file was not checked.
|
|
154
388
|
def read_ruby(file)
|
|
155
389
|
bytes = File.binread(file)
|
|
@@ -168,17 +402,112 @@ module ApiRecipes
|
|
|
168
402
|
end
|
|
169
403
|
|
|
170
404
|
def check_config(file)
|
|
171
|
-
|
|
405
|
+
return check_recipe(file) if file.end_with?(Internals::Recipe::SUFFIX)
|
|
406
|
+
return [config_finding(file, 'describes more values than can be checked: aliases make them from a few lines')] if too_many_values?(file)
|
|
407
|
+
|
|
408
|
+
unchecked = []
|
|
409
|
+
tags = false
|
|
410
|
+
apis = Configuration.new.read_recipe_file(file, erb: @erb) do |text|
|
|
411
|
+
tags = true
|
|
412
|
+
without_erb(file, text)
|
|
413
|
+
end
|
|
414
|
+
return not_checked(file) if tags && structural_tag?(apis)
|
|
415
|
+
|
|
416
|
+
unchecked = erb_values(apis)
|
|
172
417
|
Internals::Compiler.compile_all(apis)
|
|
418
|
+
note_unchecked(file, unchecked)
|
|
173
419
|
[]
|
|
174
420
|
rescue RecipeFileError => e
|
|
421
|
+
return not_checked(file) if tags && e.errors.all? { |problem| problem.include?('invalid YAML') }
|
|
422
|
+
|
|
175
423
|
e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
|
|
176
424
|
rescue ConfigurationError => e
|
|
177
|
-
|
|
425
|
+
note_unchecked(file, unchecked)
|
|
426
|
+
checked(e.errors, unchecked).map { |problem| config_finding(file, problem) }
|
|
427
|
+
rescue SystemStackError
|
|
428
|
+
[config_finding(file, 'is nested too deeply to be checked')]
|
|
178
429
|
rescue StandardError, ScriptError => e
|
|
179
430
|
[config_finding(file, "could not be evaluated (#{e.class})")]
|
|
180
431
|
end
|
|
181
432
|
|
|
433
|
+
# A file whose tags give a name or a part of the structure is not
|
|
434
|
+
# guessed: it is said, and it is not a finding.
|
|
435
|
+
def not_checked(file)
|
|
436
|
+
@notes << "#{shown_path(file)}: an ERB tag gives a name or a part of the structure: not checked without --erb"
|
|
437
|
+
[]
|
|
438
|
+
end
|
|
439
|
+
|
|
440
|
+
def structural_tag?(value)
|
|
441
|
+
case value
|
|
442
|
+
when Hash
|
|
443
|
+
value.any? do |key, inner|
|
|
444
|
+
key.to_s.include?(@erb_value) || (CONTAINERS.include?(key.to_s) && inner.to_s == @erb_value) || structural_tag?(inner)
|
|
445
|
+
end
|
|
446
|
+
when Array then value.any? { |inner| structural_tag?(inner) }
|
|
447
|
+
else false
|
|
448
|
+
end
|
|
449
|
+
end
|
|
450
|
+
|
|
451
|
+
# Aliases can make millions of values from a few lines: the file is
|
|
452
|
+
# measured, with its tags read as a word, before anything walks it.
|
|
453
|
+
def too_many_values?(file)
|
|
454
|
+
text = File.binread(file).force_encoding(Encoding::UTF_8)
|
|
455
|
+
return false unless text.valid_encoding? && text.include?('*')
|
|
456
|
+
|
|
457
|
+
data = YAML.safe_load(text.gsub(/<%.*?%>/m, 'erb'), permitted_classes: [Symbol], aliases: true)
|
|
458
|
+
!Project.within?(data, Project::MAX_VALUES)
|
|
459
|
+
rescue SystemCallError, Psych::Exception, SystemStackError
|
|
460
|
+
false
|
|
461
|
+
end
|
|
462
|
+
|
|
463
|
+
# A file called NAME.recipe.yml is a portable recipe, read as data only.
|
|
464
|
+
def check_recipe(file)
|
|
465
|
+
Internals::Recipe.read(file)
|
|
466
|
+
[]
|
|
467
|
+
rescue ConfigurationError => e
|
|
468
|
+
e.errors.map { |problem| config_finding(file, problem.delete_prefix("#{file}: ")) }
|
|
469
|
+
rescue StandardError => e
|
|
470
|
+
[config_finding(file, "could not be read (#{e.class})")]
|
|
471
|
+
end
|
|
472
|
+
|
|
473
|
+
# The text of a file with ERB, made checkable without running anything:
|
|
474
|
+
# the value of each output tag becomes ERB_VALUE. A tag that is not an
|
|
475
|
+
# output tag can decide which lines the file has, so it is not guessed.
|
|
476
|
+
def without_erb(file, text)
|
|
477
|
+
plain = text.gsub(ERB_COMMENT, '').gsub(ERB_OUTPUT, @erb_value)
|
|
478
|
+
return plain.gsub('<%%', '<%') unless plain.gsub('<%%', '').include?('<%')
|
|
479
|
+
|
|
480
|
+
raise RecipeFileError.new(file, 'contains ERB that decides the structure of the file (<% ... %>): run again ' \
|
|
481
|
+
'with --erb to evaluate it (this executes the code in the file)')
|
|
482
|
+
end
|
|
483
|
+
|
|
484
|
+
# The places, as the compiler names them, whose value holds the value
|
|
485
|
+
# of a tag.
|
|
486
|
+
def erb_values(value, path = nil, found = [])
|
|
487
|
+
case value
|
|
488
|
+
when Hash then value.each { |key, inner| erb_values(inner, [path, place(key)].compact.join('.'), found) }
|
|
489
|
+
when Array then found << path if value.any? { |item| item.to_s.include?(@erb_value) }
|
|
490
|
+
else found << path if value.to_s.include?(@erb_value)
|
|
491
|
+
end
|
|
492
|
+
found
|
|
493
|
+
end
|
|
494
|
+
|
|
495
|
+
# A name as the compiler writes it in the place of a problem.
|
|
496
|
+
def place(name) = name.to_s.gsub(/[^[:print:]]/, '?')[0, 40]
|
|
497
|
+
|
|
498
|
+
# The problems that are not about a value that an ERB tag gives.
|
|
499
|
+
def checked(problems, unchecked)
|
|
500
|
+
problems.reject { |problem| unchecked.any? { |path| problem.start_with?("#{path}: ") } }
|
|
501
|
+
end
|
|
502
|
+
|
|
503
|
+
def note_unchecked(file, unchecked)
|
|
504
|
+
return if unchecked.empty?
|
|
505
|
+
|
|
506
|
+
count = unchecked.size
|
|
507
|
+
@notes << "#{shown_path(file)}: #{count} value#{'s' unless count == 1} come#{'s' if count == 1} from ERB and " \
|
|
508
|
+
"#{count == 1 ? 'was' : 'were'} not checked"
|
|
509
|
+
end
|
|
510
|
+
|
|
182
511
|
def config_finding(file, message)
|
|
183
512
|
Finding.new(file: file, line: nil, kind: :config, message: message)
|
|
184
513
|
end
|