test-kitchen 4.1.4 → 4.2.0

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c56fc990001b04aa4573652682c08b02ea00508480f76beb1db8ed72e8ade07f
4
- data.tar.gz: 575f723e4cd3105fdd6e3ec4961f3bcfaa08ab8d2d38bc434dab095c3e9f193c
3
+ metadata.gz: 1dacb005a654a08e058d116c425e11fba212683cbe11282377078e98ad5c7aed
4
+ data.tar.gz: b81fa1cd0500fb7d84878fb06347eca39a0d497ffe65e7b982a2e9ad6bbf2c21
5
5
  SHA512:
6
- metadata.gz: f629caaf011634872054a8e6fae1643758a50a97c98d28fd4967181d4a5e6f68719965894cdb007d571e9a71ae45eb41cf1de8d9639d917b2b9cab99540d5c3e
7
- data.tar.gz: e10c5f823385e29b6d3c08fe9f7059d160e815ef02ebca55e81e5dd526bcbb081727b6f3aacdc4f46bcb0b0928f562014fcc0475a4c3fe95c88e6d4e67d898ab
6
+ metadata.gz: db6bb67daf31fd7472aebff5bb1bbe5b122514a046d81eac74425b1a2420b19f28d6a173e970e615df5b4456b1df2acf257e83a10aec5592626965f32e6d2f6a
7
+ data.tar.gz: fa5bc39878cff7f42ded8a7311be13661d79dcf6f9b8851b273beed624b33335bfdaea9fd2cf7b96e66b9e127fe6b23f5b01f0ea008e92eb1d47e7d55389f2cb
data/Gemfile CHANGED
@@ -12,7 +12,7 @@ group :test do
12
12
  gem "maruku", "~> 0.7"
13
13
  gem "minitest", "~> 6.0", "< 6.1"
14
14
  gem "mocha", "~> 3.0"
15
- gem "simplecov", "~> 0.22", require: false
15
+ gem "simplecov", "~> 1.0", require: false
16
16
  gem "yard", "~> 0.9"
17
17
  end
18
18
 
@@ -0,0 +1,251 @@
1
+ # Copyright 2026 Dan Webb
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ require "digest" unless defined?(Digest::SHA256)
5
+ require "fileutils" unless defined?(FileUtils)
6
+ require "json" unless defined?(JSON)
7
+ require "tmpdir" unless defined?(Dir.mktmpdir)
8
+ require "securerandom" unless defined?(SecureRandom)
9
+ require "kitchen/errors"
10
+ require_relative "catalog"
11
+
12
+ module Kitchen
13
+ module Box
14
+ # Stores verified archive copies. Drivers keep a lease until destroy, including
15
+ # after partial creation, so a prune plan can account for in-flight work.
16
+ class Cache
17
+ ENV_KEY = "KITCHEN_BOX_CACHE".freeze
18
+ DIGEST = /\A[0-9a-f]{64}\z/
19
+ TOKEN = /\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/
20
+
21
+ attr_reader :root
22
+
23
+ def initialize(path = nil)
24
+ @root = File.expand_path(path || ENV[ENV_KEY] || "~/.cache/test-kitchen/boxes")
25
+ end
26
+
27
+ def validate_destination(catalog, entry)
28
+ validate_location(entry_path(entry.fetch("sha256")), catalog.directory)
29
+ rescue SystemCallError, IOError => e
30
+ raise UserError, "Cannot inspect box cache destination in #{root}: #{e.message}"
31
+ end
32
+
33
+ def fetch(catalog, entry, token)
34
+ digest = entry.fetch("sha256")
35
+ validate_token(token)
36
+ directory = entry_path(digest)
37
+ validate_location(directory, catalog.directory)
38
+ FileUtils.mkdir_p(root, mode: 0o700)
39
+ create_directory(directory)
40
+
41
+ with_lock(directory) do
42
+ leases = File.join(directory, "leases")
43
+ create_directory(leases)
44
+ create_lease(File.join(leases, token))
45
+ archive = File.join(directory, "archive.box")
46
+ populate(directory, catalog, entry) unless verified?(archive, entry)
47
+ remember_identity(directory, entry)
48
+ archive
49
+ end
50
+ rescue SystemCallError, IOError => e
51
+ raise UserError, "Cannot cache box in #{root}: #{e.message}"
52
+ end
53
+
54
+ def release(digest, token)
55
+ validate_token(token)
56
+ directory = entry_path(digest)
57
+ raise UserError, "Invalid box cache directory: #{root}" if File.symlink?(root)
58
+ return unless existing_directory?(directory)
59
+
60
+ leases = File.join(directory, "leases")
61
+ return unless existing_directory?(leases)
62
+
63
+ with_lock(directory, create: false) do
64
+ remove_lease(File.join(leases, token))
65
+ end
66
+ rescue SystemCallError, IOError => e
67
+ raise UserError, "Cannot release cached box in #{root}: #{e.message}"
68
+ end
69
+
70
+ def prune_plan(**filters)
71
+ return { removable: [], protected: [], reclaimable_bytes: 0 } unless File.directory?(root) && !File.symlink?(root)
72
+
73
+ removable = []
74
+ protected = []
75
+ Dir.children(root).sort.each do |digest|
76
+ next unless DIGEST.match?(digest)
77
+
78
+ candidate, reason = inspect_entry(digest, filters)
79
+ next unless candidate
80
+
81
+ if reason
82
+ protected << candidate.merge(reason: reason)
83
+ else
84
+ removable << candidate
85
+ end
86
+ end
87
+ { removable: removable, protected: protected, reclaimable_bytes: removable.sum { |row| row.fetch(:bytes) } }
88
+ rescue SystemCallError, IOError => e
89
+ raise UserError, "Cannot inspect box cache #{root}: #{e.message}"
90
+ end
91
+
92
+ private
93
+
94
+ def validate_location(directory, source_directory)
95
+ actual_root = physical_path(root)
96
+ destination = physical_path(directory)
97
+ if File.symlink?(root) || within_directory?(actual_root, source_directory) ||
98
+ within_directory?(destination, source_directory) || within_directory?(source_directory, destination)
99
+ raise UserError, "Keep the local box cache outside the manifest directory"
100
+ end
101
+ end
102
+
103
+ def physical_path(path)
104
+ parent = path
105
+ parent = File.dirname(parent) until File.exist?(parent)
106
+ File.join(File.realpath(parent), path.delete_prefix(parent).sub(%r{\A/}, ""))
107
+ end
108
+
109
+ def within_directory?(path, directory)
110
+ loop do
111
+ return true if File.identical?(path, directory)
112
+
113
+ parent = File.dirname(path)
114
+ return false if parent == path
115
+
116
+ path = parent
117
+ end
118
+ end
119
+
120
+ def validate_token(token)
121
+ raise UserError, "Invalid box cache lease ID" unless TOKEN.match?(token.to_s)
122
+ end
123
+
124
+ def entry_path(digest)
125
+ raise UserError, "Invalid box cache digest" unless DIGEST.match?(digest.to_s)
126
+
127
+ File.join(root, digest)
128
+ end
129
+
130
+ def create_directory(path)
131
+ Dir.mkdir(path, 0o700)
132
+ rescue Errno::EEXIST
133
+ existing_directory?(path)
134
+ end
135
+
136
+ def existing_directory?(path)
137
+ stat = File.lstat(path)
138
+ raise UserError, "Invalid box cache directory: #{path}" unless stat.directory?
139
+
140
+ true
141
+ rescue Errno::ENOENT
142
+ false
143
+ end
144
+
145
+ def create_lease(path)
146
+ raise UserError, "Invalid box cache lease: #{path}" if File.symlink?(path)
147
+
148
+ File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600) {}
149
+ rescue Errno::EEXIST
150
+ raise UserError, "Invalid box cache lease: #{path}" unless regular_file?(path)
151
+ end
152
+
153
+ def remove_lease(path)
154
+ File.unlink(path)
155
+ rescue Errno::ENOENT
156
+ nil
157
+ end
158
+
159
+ def with_lock(directory, create: true)
160
+ lock = File.join(directory, "lock")
161
+ raise UserError, "Invalid box cache lock: #{lock}" if File.symlink?(lock)
162
+
163
+ flags = create ? File::RDWR | File::CREAT : File::RDWR
164
+ File.open(lock, flags, 0o600) do |file|
165
+ file.flock(File::LOCK_EX)
166
+ yield
167
+ end
168
+ end
169
+
170
+ def regular_file?(path)
171
+ File.file?(path) && !File.symlink?(path)
172
+ end
173
+
174
+ def verified?(path, entry)
175
+ regular_file?(path) && File.size(path) == entry.fetch("bytes") &&
176
+ Digest::SHA256.file(path).hexdigest == entry.fetch("sha256")
177
+ end
178
+
179
+ def populate(directory, catalog, entry)
180
+ source = catalog.verify(entry)
181
+ Dir.mktmpdir("download-", directory) do |staging|
182
+ archive = File.join(staging, "archive.box")
183
+ File.copy_stream(source, archive)
184
+ raise UserError, "SHA-256 or size mismatch while caching #{source}" unless verified?(archive, entry)
185
+
186
+ File.rename(archive, File.join(directory, "archive.box"))
187
+ end
188
+ end
189
+
190
+ def remember_identity(directory, entry)
191
+ digest = entry.fetch("sha256")
192
+ metadata = File.join(directory, "metadata.json")
193
+ identities = cached_identities(metadata, digest)
194
+ identity = entry.slice(*Catalog::IDENTITY)
195
+ return if identities.include?(identity)
196
+
197
+ Dir.mktmpdir("metadata-", directory) do |staging|
198
+ update = File.join(staging, "metadata.json")
199
+ File.write(update, JSON.generate(sha256: digest, identities: identities + [identity]))
200
+ File.rename(update, metadata)
201
+ end
202
+ end
203
+
204
+ def cached_identities(path, digest)
205
+ return [] unless regular_file?(path)
206
+
207
+ metadata = JSON.parse(File.read(path))
208
+ return [] unless metadata.is_a?(Hash) && metadata["sha256"] == digest
209
+
210
+ identities = metadata.fetch("identities") { [metadata.slice(*Catalog::IDENTITY)] }
211
+ return [] unless identities.is_a?(Array)
212
+
213
+ identities.select { |identity| identity.is_a?(Hash) && Catalog::IDENTITY.all? { |key| identity[key].is_a?(String) } }
214
+ rescue JSON::ParserError
215
+ []
216
+ end
217
+
218
+ def inspect_entry(digest, filters)
219
+ directory = entry_path(digest)
220
+ archive = File.join(directory, "archive.box")
221
+ metadata = File.join(directory, "metadata.json")
222
+ lock = File.join(directory, "lock")
223
+ return unless File.directory?(directory) && !File.symlink?(directory) &&
224
+ [archive, metadata, lock].all? { |path| regular_file?(path) }
225
+
226
+ File.open(lock, "rb") do |file|
227
+ locked = file.flock(File::LOCK_SH | File::LOCK_NB)
228
+ entry = cached_identities(metadata, digest).find { |identity| filters.all? { |key, value| identity[key.to_s] == value } }
229
+ next unless entry
230
+
231
+ stat = File.stat(archive)
232
+ row = { sha256: digest, name: entry["name"], version: entry["version"],
233
+ provider: entry["provider"], architecture: entry["architecture"], path: archive, bytes: stat.size }
234
+ leases = File.join(directory, "leases")
235
+ reason = if !locked
236
+ "cache operation in progress"
237
+ elsif !File.directory?(leases) || File.symlink?(leases)
238
+ "lease directory unavailable"
239
+ elsif !Dir.empty?(leases)
240
+ "in use by a Kitchen instance"
241
+ elsif stat.nlink > 1
242
+ "archive has another hard link"
243
+ end
244
+ [row, reason]
245
+ end
246
+ rescue Errno::ENOENT
247
+ nil
248
+ end
249
+ end
250
+ end
251
+ end
@@ -0,0 +1,94 @@
1
+ # Copyright 2026 Dan Webb
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ require "digest" unless defined?(Digest)
5
+ require "json" unless defined?(JSON)
6
+ require "rbconfig" unless defined?(RbConfig)
7
+ require "kitchen/errors"
8
+
9
+ module Kitchen
10
+ module Box
11
+ class Catalog
12
+ IDENTITY = %w{name version provider architecture}.freeze
13
+ FIELDS = (IDENTITY + %w{file bytes sha256}).freeze
14
+ ENV_KEY = "KITCHEN_BOX_MANIFEST".freeze
15
+
16
+ attr_reader :directory
17
+
18
+ def self.host_architecture
19
+ case RbConfig::CONFIG.fetch("host_cpu")
20
+ when "aarch64", "arm64" then "arm64"
21
+ when "x86_64", "amd64" then "amd64"
22
+ else RbConfig::CONFIG.fetch("host_cpu")
23
+ end
24
+ end
25
+
26
+ def initialize(manifest)
27
+ raise UserError, "Specify a box manifest with --manifest or #{ENV_KEY}" if manifest.to_s.empty?
28
+
29
+ @manifest = File.realpath(manifest)
30
+ @directory = File.dirname(@manifest)
31
+ records = JSON.parse(File.read(@manifest))
32
+ raise UserError, "Box manifest must contain an array: #{@manifest}" unless records.is_a?(Array)
33
+
34
+ @entries = records.map.with_index(1) { |record, index| parse_entry(record, index) }
35
+ keys = @entries.map { |entry| entry.values_at(*IDENTITY) }
36
+ raise UserError, "Duplicate name, version, provider and architecture in #{@manifest}" unless keys.uniq.size == keys.size
37
+ rescue JSON::ParserError, SystemCallError, IOError => e
38
+ raise UserError, "Cannot read box manifest #{manifest}: #{e.message}"
39
+ end
40
+
41
+ def entries(name: nil, version: nil, provider: nil, architecture: nil)
42
+ filters = { "name" => name, "version" => version, "provider" => provider, "architecture" => architecture }.compact
43
+ @entries.select { |entry| filters.all? { |key, value| entry[key] == value } }
44
+ end
45
+
46
+ def resolve(name:, version:, provider:, architecture: self.class.host_architecture)
47
+ verify(find(name: name, version: version, provider: provider, architecture: architecture), checksum: true)
48
+ end
49
+
50
+ def find(name:, version:, provider:, architecture: self.class.host_architecture)
51
+ unless [name, version, provider, architecture].all? { |value| value.is_a?(String) && !value.empty? }
52
+ raise UserError, "Box resolution requires a name, exact version, provider and architecture"
53
+ end
54
+
55
+ entry = entries(name: name, version: version, provider: provider, architecture: architecture).first
56
+ unless entry
57
+ raise UserError, "No box matches #{name} #{version} (#{provider}/#{architecture}) in #{@manifest}"
58
+ end
59
+
60
+ entry
61
+ end
62
+
63
+ def verify(entry, checksum: false)
64
+ path = File.realpath(File.join(directory, entry.fetch("file")))
65
+ unless path.start_with?("#{directory.delete_suffix(File::SEPARATOR)}#{File::SEPARATOR}") && File.file?(path) && File.readable?(path)
66
+ raise UserError, "Box must be a regular file inside the manifest directory: #{entry.fetch("file")}"
67
+ end
68
+ raise UserError, "Size mismatch for #{path}" unless File.size(path) == entry.fetch("bytes")
69
+ if checksum && Digest::SHA256.file(path).hexdigest != entry.fetch("sha256")
70
+ raise UserError, "SHA-256 mismatch for #{path}"
71
+ end
72
+
73
+ path
74
+ rescue SystemCallError, IOError => e
75
+ raise UserError, "Cannot read box #{entry.fetch("file")}: #{e.message}"
76
+ end
77
+
78
+ private
79
+
80
+ def parse_entry(record, index)
81
+ unless record.is_a?(Hash) && (IDENTITY + %w{file sha256}).all? { |key| record[key].is_a?(String) && !record[key].empty? } &&
82
+ record["bytes"].is_a?(Integer) && record["bytes"] > 0 &&
83
+ /\A[0-9a-f]{64}\z/i.match?(record["sha256"]) &&
84
+ record["file"].match?(%r{\A[^/\\:\x00]+\.box\z})
85
+ raise UserError, "Invalid box manifest entry #{index} in #{@manifest}"
86
+ end
87
+
88
+ entry = record.slice(*FIELDS)
89
+ entry["sha256"] = entry["sha256"].downcase
90
+ entry.transform_values(&:freeze).freeze
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,94 @@
1
+ # Copyright 2026 Dan Webb
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ require "thor" unless defined?(Thor)
5
+ require_relative "catalog"
6
+ require_relative "cache"
7
+
8
+ module Kitchen
9
+ module Box
10
+ class CLI < Thor
11
+ class_option :manifest, type: :string, desc: "Path to the box manifest (or KITCHEN_BOX_MANIFEST)"
12
+ class_option :name, type: :string, desc: "Filter by exact box name"
13
+ class_option :version, type: :string, desc: "Filter by exact box version"
14
+ class_option :provider, type: :string, desc: "Filter by provider"
15
+ class_option :architecture, type: :string, desc: "Filter by architecture"
16
+ class_option :json, type: :boolean, aliases: "-j", desc: "Print JSON"
17
+
18
+ def self.exit_on_failure?
19
+ true
20
+ end
21
+
22
+ desc "list", "List boxes from the manifest"
23
+ def list
24
+ entries = selected_entries(catalog)
25
+ if options[:json]
26
+ puts JSON.pretty_generate(entries)
27
+ else
28
+ rows = entries.map { |entry| entry.values_at(*Catalog::FIELDS.first(6)) }
29
+ print_table([%w{Name Version Provider Architecture File Bytes}, *rows])
30
+ end
31
+ end
32
+
33
+ desc "doctor", "Check that selected archives are readable and match the manifest"
34
+ option :checksum, type: :boolean, desc: "Read each selected archive to verify its SHA-256"
35
+ def doctor
36
+ source = catalog
37
+ entries = selected_entries(source)
38
+ raise UserError, "No boxes match the selected filters" if entries.empty?
39
+
40
+ results = entries.map { |entry| check_entry(source, entry) }
41
+ if options[:json]
42
+ puts JSON.pretty_generate(results)
43
+ else
44
+ results.each { |entry| puts "#{entry[:error] ? "FAIL" : "OK"} #{entry[:file]}#{entry[:error] && " #{entry[:error]}"}" }
45
+ end
46
+ exit 1 if results.any? { |entry| entry[:error] }
47
+ end
48
+
49
+ desc "prune --dry-run", "Show unused local archives and how much space they occupy"
50
+ option :dry_run, type: :boolean, desc: "Preview without changing the cache"
51
+ option :cache, type: :string, desc: "Cache directory (or KITCHEN_BOX_CACHE)"
52
+ def prune
53
+ raise UserError, "Use kitchen box prune --dry-run to preview cache cleanup" unless options[:dry_run]
54
+
55
+ cache = Cache.new(options[:cache])
56
+ plan = cache.prune_plan(**filters)
57
+ if options[:json]
58
+ puts JSON.pretty_generate(plan.merge(cache: cache.root, dry_run: true))
59
+ else
60
+ puts "Dry run for #{cache.root}"
61
+ plan.fetch(:removable).each { |row| puts "Would remove #{box_label(row)} (#{row.fetch(:bytes)} bytes)\n #{row.fetch(:path)}" }
62
+ plan.fetch(:protected).each { |row| puts "Keep #{box_label(row)} (#{row.fetch(:reason)})" }
63
+ bytes = plan.fetch(:reclaimable_bytes)
64
+ puts "#{plan.fetch(:removable).size} archive(s), #{bytes} bytes reclaimable (#{format("%.2f", bytes.fdiv(1024**2))} MiB)"
65
+ end
66
+ end
67
+
68
+ private
69
+
70
+ def catalog
71
+ Catalog.new(options[:manifest] || ENV[Catalog::ENV_KEY])
72
+ end
73
+
74
+ def selected_entries(source)
75
+ source.entries(**filters)
76
+ end
77
+
78
+ def filters
79
+ { name: options[:name], version: options[:version], provider: options[:provider], architecture: options[:architecture] }.compact
80
+ end
81
+
82
+ def box_label(row)
83
+ "#{row[:name]} #{row[:version]} (#{row[:provider]}/#{row[:architecture]})"
84
+ end
85
+
86
+ def check_entry(source, entry)
87
+ path = source.verify(entry, checksum: options[:checksum])
88
+ { file: entry.fetch("file"), path: path, checksum_verified: !!options[:checksum] }
89
+ rescue UserError => e
90
+ { file: entry.fetch("file"), error: e.message }
91
+ end
92
+ end
93
+ end
94
+ end
@@ -0,0 +1,36 @@
1
+ # Copyright 2026 Dan Webb
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ require "json" unless defined?(JSON)
5
+
6
+ module Kitchen
7
+ module Box
8
+ # Extracts a trusted local Vagrant-format box without evaluating its Vagrantfile.
9
+ # Callers supply a private, empty destination and select their provider payload.
10
+ class LocalArchive
11
+ class InvalidBox < StandardError; end
12
+
13
+ def initialize(path, provider:)
14
+ @path = path
15
+ @provider = provider
16
+ end
17
+
18
+ def extract(destination)
19
+ yield "/usr/bin/tar", "-xf", @path, "-C", destination, "--no-same-owner", "--no-same-permissions"
20
+ metadata_path = File.join(destination, "metadata.json")
21
+ unless File.file?(metadata_path) && !File.symlink?(metadata_path)
22
+ raise InvalidBox, "Box is missing a regular metadata.json file: #{@path}"
23
+ end
24
+
25
+ metadata = JSON.parse(File.read(metadata_path))
26
+ unless metadata.is_a?(Hash) && metadata["provider"] == @provider
27
+ raise InvalidBox, "Box metadata must specify the #{@provider} provider: #{@path}"
28
+ end
29
+
30
+ metadata
31
+ rescue JSON::ParserError => e
32
+ raise InvalidBox, "Invalid metadata.json in #{@path}: #{e.message}"
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,52 @@
1
+ # Copyright 2026 Dan Webb
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ require_relative "catalog"
5
+ require_relative "cache"
6
+
7
+ module Kitchen
8
+ module Box
9
+ module Source
10
+ private
11
+
12
+ def box_source(provider, state)
13
+ box = config[:box]
14
+ return File.expand_path(box, config[:kitchen_root]) if box.is_a?(String)
15
+
16
+ unless box.is_a?(Hash) && %i{name version}.all? { |key| box[key].is_a?(String) && !box[key].empty? }
17
+ raise ActionFailed, "Set driver.box to a local path or a map with name and an exact version"
18
+ end
19
+
20
+ manifest = config[:box_manifest] || ENV[Catalog::ENV_KEY]
21
+ manifest = File.expand_path(manifest, config[:kitchen_root]) unless manifest.to_s.empty?
22
+ source = Catalog.new(manifest)
23
+ entry = source.find(name: box[:name], version: box[:version], provider: provider)
24
+ cache = Cache.new(config[:box_cache])
25
+ reference = state[:box_cache_lease]
26
+ if reference && (reference[:root] != cache.root || reference[:digest] != entry.fetch("sha256"))
27
+ raise ActionFailed, "Run kitchen destroy before changing the cached box or cache location for this instance"
28
+ end
29
+
30
+ unless reference
31
+ cache.validate_destination(source, entry)
32
+ reference = { root: cache.root, digest: entry.fetch("sha256"), token: SecureRandom.uuid }
33
+ state[:box_cache_lease] = reference
34
+ yield
35
+ end
36
+ cache.fetch(source, entry, reference.fetch(:token))
37
+ rescue UserError => e
38
+ raise ActionFailed, e.message
39
+ end
40
+
41
+ def release_box_source(state)
42
+ reference = state[:box_cache_lease]
43
+ return unless reference
44
+
45
+ Cache.new(reference.fetch(:root)).release(reference.fetch(:digest), reference.fetch(:token))
46
+ state.delete(:box_cache_lease)
47
+ rescue UserError => e
48
+ raise ActionFailed, e.message
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,61 @@
1
+ # Copyright 2026 Dan Webb
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ require "fileutils" unless defined?(FileUtils)
5
+ require "tmpdir" unless defined?(Dir.mktmpdir)
6
+
7
+ module Kitchen
8
+ module Box
9
+ module SshBootstrap
10
+ module_function
11
+
12
+ def install(directory, runner:)
13
+ path = instance_key(directory, runner)
14
+ public_key = runner.call("/usr/bin/ssh-keygen", "-y", "-f", path).strip
15
+ yield ["-c", INSTALL_KEY, "kitchen-key", INSECURE_RSA, INSECURE_ED25519, public_key.split.fetch(1), public_key]
16
+ path
17
+ end
18
+
19
+ # Public key blobs from Vagrant's keys/vagrant.pub.{rsa,ed25519}.
20
+ INSECURE_RSA = "AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9HZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHilFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRdK8jlqm8tehUc9c9WhQ==".freeze
21
+ INSECURE_ED25519 = "AAAAC3NzaC1lZDI1NTE5AAAAIN1YdxBpNlzxDqfJyw/QKow1F+wvG9hXGoqiysfJOn5Y".freeze
22
+
23
+ INSTALL_KEY = <<~'SH'.freeze
24
+ set -eu
25
+ umask 077
26
+ mkdir -p "$HOME/.ssh"
27
+ chmod 700 "$HOME/.ssh"
28
+ keys="$HOME/.ssh/authorized_keys"
29
+ touch "$keys"
30
+ temp=$(mktemp "$HOME/.ssh/kitchen-keys.XXXXXX")
31
+ trap 'rm -f "$temp"' EXIT
32
+ awk -v rsa="$1" -v ed="$2" -v new="$3" '
33
+ /^[[:space:]]*#/ { print; next }
34
+ {
35
+ for (i = 2; i <= NF; i++) {
36
+ if ($i == rsa || $i == ed || $i == new) next
37
+ }
38
+ print
39
+ }
40
+ ' "$keys" > "$temp"
41
+ printf '%s\n' "$4" >> "$temp"
42
+ mv -f "$temp" "$keys"
43
+ SH
44
+
45
+ def instance_key(directory, runner)
46
+ FileUtils.mkdir_p(directory, mode: 0o700)
47
+ path = File.join(directory, "ssh_key")
48
+ return path if File.file?(path)
49
+
50
+ Dir.mktmpdir("key-", directory) do |temporary|
51
+ new_key = File.join(temporary, "ssh_key")
52
+ runner.call("/usr/bin/ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", new_key)
53
+ File.chmod(0o600, new_key)
54
+ File.rename(new_key, path)
55
+ end
56
+ path
57
+ end
58
+
59
+ end
60
+ end
61
+ end
data/lib/kitchen/cli.rb CHANGED
@@ -19,6 +19,7 @@
19
19
  require "thor" # rubocop:disable Chef/Ruby/UnlessDefinedRequire
20
20
 
21
21
  require_relative "../kitchen"
22
+ require_relative "box/cli"
22
23
  require_relative "generator/init"
23
24
 
24
25
  module Kitchen
@@ -133,6 +134,9 @@ module Kitchen
133
134
  end
134
135
  map status: :list
135
136
 
137
+ desc "box SUBCOMMAND", "Inspect a local box manifest"
138
+ subcommand "box", Kitchen::Box::CLI
139
+
136
140
  desc "diagnose [INSTANCE|REGEXP|all]", "Show computed diagnostic configuration"
137
141
  method_option :loader,
138
142
  type: :boolean,
@@ -139,9 +139,15 @@ module Kitchen
139
139
  # @return [Array<Instance>] an array of Instances
140
140
  # @api private
141
141
  def build_instances
142
- filter_instances.map.with_index do |(suite, platform), index|
143
- new_instance(suite, platform, index)
142
+ instances = []
143
+ suites.each do |suite|
144
+ platforms.each do |platform|
145
+ next unless platform_selected?(suite, platform)
146
+
147
+ instances << new_instance(suite, platform, instances.length)
148
+ end
144
149
  end
150
+ instances
145
151
  end
146
152
 
147
153
  # Returns an object which can generate configuration hashes for all the
@@ -171,23 +177,19 @@ module Kitchen
171
177
  File.join(kitchen_root, Kitchen::DEFAULT_TEST_DIR)
172
178
  end
173
179
 
174
- # Generates a filtered Array of tuples (Suite/Platform pairs) which is the
175
- # cartesian product of suites and platforms. A Suite has two optional
176
- # arrays (`#includes` and `#excludes`) which can be used to drop or
177
- # select certain Platforms with which to join.
180
+ # Returns whether a platform passes a suite's include or exclude filters.
178
181
  #
179
- # @return [Array<Array<Suite, Platform>>] an Array of Suite/Platform
180
- # tuples
182
+ # @param suite [Suite] a suite with optional platform filters
183
+ # @param platform [Platform] the platform to check
184
+ # @return [Boolean] whether an instance should be built for the pair
181
185
  # @api private
182
- def filter_instances
183
- suites.product(platforms).select do |suite, platform|
184
- if !suite.includes.empty?
185
- suite.includes.include?(platform.name)
186
- elsif !suite.excludes.empty?
187
- !suite.excludes.include?(platform.name)
188
- else
189
- true
190
- end
186
+ def platform_selected?(suite, platform)
187
+ if !suite.includes.empty?
188
+ suite.includes.include?(platform.name)
189
+ elsif !suite.excludes.empty?
190
+ !suite.excludes.include?(platform.name)
191
+ else
192
+ true
191
193
  end
192
194
  end
193
195
 
@@ -26,6 +26,24 @@ module Kitchen
26
26
  #
27
27
  # @author Fletcher Nichol <fnichol@nichol.ca>
28
28
  module Configurable
29
+ # @return [String] the canonical Bourne shell type
30
+ # @api private
31
+ BOURNE_SHELL_TYPE = "bourne".freeze
32
+
33
+ # @return [String] the canonical PowerShell shell type
34
+ # @api private
35
+ POWERSHELL_SHELL_TYPE = "powershell".freeze
36
+
37
+ # @return [String] the canonical Unix OS type
38
+ # @api private
39
+ UNIX_OS_TYPE = "unix".freeze
40
+
41
+ # @return [String] the canonical Windows OS type
42
+ # @api private
43
+ WINDOWS_OS_TYPE = "windows".freeze
44
+
45
+ private_constant :BOURNE_SHELL_TYPE, :POWERSHELL_SHELL_TYPE, :UNIX_OS_TYPE, :WINDOWS_OS_TYPE
46
+
29
47
  # Extends the including class with {ClassMethods} so that the
30
48
  # `default_config`, `required_config`, and related DSL is available at the
31
49
  # class level.
@@ -73,7 +91,7 @@ module Kitchen
73
91
  # unset, for backwards compatibility)
74
92
  def bourne_shell?
75
93
  shell_type = instance.platform.respond_to?(:shell_type) ? instance.platform.shell_type : nil
76
- ["bourne", nil].include?(shell_type)
94
+ BOURNE_SHELL_TYPE == shell_type || shell_type.nil?
77
95
  end
78
96
 
79
97
  # Find an appropriate path to a file or directory, based on graceful
@@ -103,13 +121,14 @@ module Kitchen
103
121
  end
104
122
  end
105
123
 
106
- [
107
- File.join(base, instance.suite.name, path),
108
- File.join(base, path),
109
- File.join(Dir.pwd, path),
110
- ].find do |candidate|
111
- type == :directory ? File.directory?(candidate) : File.file?(candidate)
112
- end
124
+ candidate = File.join(base, instance.suite.name, path)
125
+ return candidate if path_exists?(candidate, type)
126
+
127
+ candidate = File.join(base, path)
128
+ return candidate if path_exists?(candidate, type)
129
+
130
+ candidate = File.join(Dir.pwd, path)
131
+ candidate if path_exists?(candidate, type)
113
132
  end
114
133
 
115
134
  # Returns an array of configuration keys.
@@ -150,7 +169,7 @@ module Kitchen
150
169
  # @return [TrueClass,FalseClass] true if `:shell_type` is `"powershell"`
151
170
  def powershell_shell?
152
171
  shell_type = instance.platform.respond_to?(:shell_type) ? instance.platform.shell_type : nil
153
- ["powershell"].include?(shell_type)
172
+ POWERSHELL_SHELL_TYPE == shell_type
154
173
  end
155
174
 
156
175
  # Builds a file path based on the `:os_type` (`"windows"` or `"unix"`).
@@ -165,7 +184,7 @@ module Kitchen
165
184
  # unset, for backwards compatibility)
166
185
  def unix_os?
167
186
  os_type = instance.platform.respond_to?(:os_type) ? instance.platform.os_type : nil
168
- ["unix", nil].include?(os_type)
187
+ UNIX_OS_TYPE == os_type || os_type.nil?
169
188
  end
170
189
 
171
190
  # Performs whatever tests that may be required to ensure that this plugin
@@ -182,11 +201,21 @@ module Kitchen
182
201
  # @return [TrueClass,FalseClass] true if `:os_type` is `"windows"`
183
202
  def windows_os?
184
203
  os_type = instance.platform.respond_to?(:os_type) ? instance.platform.os_type : nil
185
- ["windows"].include?(os_type)
204
+ WINDOWS_OS_TYPE == os_type
186
205
  end
187
206
 
188
207
  private
189
208
 
209
+ # Returns whether a path exists as the requested filesystem type.
210
+ #
211
+ # @param path [String] filesystem path to inspect
212
+ # @param type [Symbol] either `:file` or `:directory`
213
+ # @return [Boolean] whether the path exists as the requested type
214
+ # @api private
215
+ def path_exists?(path, type)
216
+ type == :directory ? File.directory?(path) : File.file?(path)
217
+ end
218
+
190
219
  # @return [LazyHash] a configuration hash
191
220
  # @api private
192
221
  attr_reader :config
@@ -148,9 +148,16 @@ module Kitchen
148
148
 
149
149
  def combine_arrays!(root, key, *namespaces)
150
150
  if root.key?(key)
151
- root[key] = namespaces
152
- .map { |namespace| root.fetch(key).fetch(namespace, []) }.flatten
153
- .compact
151
+ values = namespaces.map { |namespace| root.fetch(key).fetch(namespace, []) }
152
+ root[key] = if values.all?(Array)
153
+ combined = values.each_with_object([]) do |value, result|
154
+ result.concat(value.any?(Array) ? value.flatten : value)
155
+ end
156
+ combined.compact!
157
+ combined
158
+ else
159
+ values.flatten.compact
160
+ end
154
161
  end
155
162
  end
156
163
 
@@ -620,9 +620,11 @@ module Kitchen
620
620
  private
621
621
 
622
622
  def line_buffer
623
- formatter = StreamLineFormatter.new(self)
624
- @line_buffer ||= LineBuffer.new do |line|
625
- formatter.format(line)
623
+ @line_buffer ||= begin
624
+ formatter = StreamLineFormatter.new(self)
625
+ LineBuffer.new do |line|
626
+ formatter.format(line)
627
+ end
626
628
  end
627
629
  end
628
630
  end
@@ -818,9 +820,11 @@ module Kitchen
818
820
  private
819
821
 
820
822
  def line_buffer
821
- formatter = StreamLineFormatter.new(self)
822
- @line_buffer ||= LineBuffer.new do |line|
823
- formatter.format(line)
823
+ @line_buffer ||= begin
824
+ formatter = StreamLineFormatter.new(self)
825
+ LineBuffer.new do |line|
826
+ formatter.format(line)
827
+ end
824
828
  end
825
829
  end
826
830
 
data/lib/kitchen/util.rb CHANGED
@@ -35,6 +35,13 @@ module Kitchen
35
35
  # "kitchen/util" is required on its own.
36
36
  @mutex_chdir = Mutex.new
37
37
 
38
+ # Directory entries omitted from listings even when dot files are enabled.
39
+ #
40
+ # @return [Array<String>] current and parent directory entries
41
+ # @api private
42
+ DOT_DIRECTORY_ENTRIES = [".".freeze, "..".freeze].freeze
43
+ private_constant :DOT_DIRECTORY_ENTRIES
44
+
38
45
  # Returns the standard library Logger level constants for a given symbol
39
46
  # representation.
40
47
  #
@@ -235,9 +242,9 @@ module Kitchen
235
242
  else
236
243
  []
237
244
  end
238
- Dir.glob(glob_pattern, *flags)
239
- .reject { |f| [".", ".."].include?(f) }
240
- .map { |f| File.join(path, f) }
245
+ Dir.glob(glob_pattern, *flags).filter_map do |entry|
246
+ File.join(path, entry) unless DOT_DIRECTORY_ENTRIES.include?(entry)
247
+ end
241
248
  end
242
249
  end
243
250
  end
@@ -19,5 +19,5 @@ module Kitchen
19
19
  # The currently released version of Test Kitchen.
20
20
  #
21
21
  # @return [String] a semantic version string
22
- VERSION = "4.1.4".freeze
22
+ VERSION = "4.2.0".freeze
23
23
  end
@@ -67,9 +67,8 @@ module HashRecursiveMerge
67
67
  # h1.merge(h2) #=> {"a" => 100, "b" = >254, "c" => {"c1" => 16, "c3" => 94}}
68
68
  #
69
69
  def rmerge(other_hash)
70
- r = {}
71
- merge(other_hash) do |key, oldval, newval|
72
- r[key] = oldval.class == self.class ? oldval.rmerge(newval) : newval
70
+ merge(other_hash) do |_key, oldval, newval|
71
+ oldval.class == self.class ? oldval.rmerge(newval) : newval
73
72
  end
74
73
  end
75
74
  end
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: test-kitchen
3
3
  version: !ruby/object:Gem::Version
4
- version: 4.1.4
4
+ version: 4.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Fletcher Nichol
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2026-09-04 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: bcrypt_pbkdf
@@ -303,6 +302,12 @@ files:
303
302
  - bin/kitchen
304
303
  - lib/kitchen.rb
305
304
  - lib/kitchen/base64_stream.rb
305
+ - lib/kitchen/box/cache.rb
306
+ - lib/kitchen/box/catalog.rb
307
+ - lib/kitchen/box/cli.rb
308
+ - lib/kitchen/box/local_archive.rb
309
+ - lib/kitchen/box/source.rb
310
+ - lib/kitchen/box/ssh_bootstrap.rb
306
311
  - lib/kitchen/chef_utils_wiring.rb
307
312
  - lib/kitchen/cli.rb
308
313
  - lib/kitchen/collection.rb
@@ -400,7 +405,6 @@ homepage: https://kitchen.ci/
400
405
  licenses:
401
406
  - Apache-2.0
402
407
  metadata: {}
403
- post_install_message:
404
408
  rdoc_options: []
405
409
  require_paths:
406
410
  - lib
@@ -415,8 +419,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
415
419
  - !ruby/object:Gem::Version
416
420
  version: '0'
417
421
  requirements: []
418
- rubygems_version: 3.5.9
419
- signing_key:
422
+ rubygems_version: 3.6.9
420
423
  specification_version: 4
421
424
  summary: Test Kitchen is an integration tool for developing and testing infrastructure
422
425
  code and software on isolated target platforms.