Class: MockServer::BinaryLauncher

Inherits:
Object
  • Object
show all
Defined in:
lib/mockserver/binary_launcher.rb

Overview

On-demand binary launcher for MockServer.

Downloads the self-contained, JVM-less MockServer bundle (a jlink runtime + the server + a mockserver launcher) for the current platform from the GitHub Release, verifies its SHA-256, caches it per-user, and launches it. No Java installation and no Docker required.

This mirrors the reference implementation at mockserver-node/downloadBinary.js.

Environment overrides:

MOCKSERVER_BINARY_BASE_URL       mirror host for the release assets
MOCKSERVER_BINARY_CACHE          cache directory (default: per-OS user cache)
MOCKSERVER_SKIP_BINARY_DOWNLOAD  fail instead of downloading (air-gapped CI with pre-seeded cache)
HTTP_PROXY / HTTPS_PROXY         honoured by Net::HTTP via +ENV['http_proxy']+ (Ruby convention)
SSL_CERT_FILE / SSL_CERT_DIR     honoured by OpenSSL for corporate TLS proxies

Examples:

Start a server on port 1080

handle = MockServer::BinaryLauncher.start(port: 1080)
# ... use MockServer ...
handle.stop

Just ensure the binary is present

path = MockServer::BinaryLauncher.ensure_launcher

Defined Under Namespace

Classes: ServerHandle

Constant Summary collapse

REPO =
'mock-server/mockserver-monorepo'
SNAPSHOT_CDN =

CDN base URL used for SNAPSHOT version downloads.

'https://downloads.mock-server.com'
MAX_PREVIOUS_VERSIONS_TO_KEEP =

Maximum number of previous version directories to keep (in addition to the current).

1
VERSION_PATTERN =

Strict pattern for version strings — blocks path separators and ‘..’.

/\A[0-9]+\.[0-9]+\.[0-9]+([-.][0-9A-Za-z.]+)?\z/

Class Method Summary collapse

Class Method Details

.asset_url(version, file) ⇒ String

Return the download URL for a release asset.

Uses MOCKSERVER_BINARY_BASE_URL if set; otherwise defaults to GitHub Releases for release versions and the downloads.mock-server.com CDN for SNAPSHOT versions.

Parameters:

  • version (String)
  • file (String)

Returns:

  • (String)


105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/mockserver/binary_launcher.rb', line 105

def asset_url(version, file)
  base = ENV['MOCKSERVER_BINARY_BASE_URL'] ||
         if snapshot?(version)
           "#{SNAPSHOT_CDN}/mockserver-#{version}"
         else
           "https://github.com/#{REPO}/releases/download/mockserver-#{version}"
         end
  # Strip trailing slashes with a single linear scan rather than a regex,
  # so there is no ReDoS surface at all (CWE-1333) on the operator-supplied
  # MOCKSERVER_BINARY_BASE_URL. Interior slashes are preserved; only the
  # trailing run is removed.
  last = base.length
  last -= 1 while last.positive? && base[last - 1] == '/'
  "#{base[0, last]}/#{file}"
end

.bundle_base_name(version) ⇒ Hash

Return the bundle base name and extension for a given version.

Parameters:

  • version (String)

Returns:

  • (Hash)

    with keys :name and :ext



72
73
74
75
76
77
78
# File 'lib/mockserver/binary_launcher.rb', line 72

def bundle_base_name(version)
  platform = resolve_platform
  {
    name: "mockserver-#{version}-#{platform[:os_name]}-#{platform[:arch]}",
    ext: platform[:ext]
  }
end

.cache_dirString

Return the per-user cache directory for MockServer binaries.

Returns:

  • (String)


83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/mockserver/binary_launcher.rb', line 83

def cache_dir
  if ENV['MOCKSERVER_BINARY_CACHE'] && !ENV['MOCKSERVER_BINARY_CACHE'].empty?
    return ENV['MOCKSERVER_BINARY_CACHE']
  end

  base = if windows?
           ENV['LOCALAPPDATA'] || File.join(Dir.home, 'AppData', 'Local')
         else
           ENV['XDG_CACHE_HOME'] || File.join(Dir.home, '.cache')
         end
  File.join(base, 'mockserver', 'binaries')
end

.ensure_launcher(version: nil, log: nil) ⇒ String

Ensure the platform bundle is present and return the launcher path, downloading + verifying + extracting + caching on first use.

Parameters:

  • version (String) (defaults to: nil)

    the MockServer version (defaults to MockServer::VERSION)

  • log (Logger, nil) (defaults to: nil)

    optional logger

Returns:

  • (String)

    absolute path to the launcher executable

Raises:

  • (Error)

    on download/verification failure



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# File 'lib/mockserver/binary_launcher.rb', line 138

def ensure_launcher(version: nil, log: nil)
  version ||= MockServer::VERSION
  log ||= Logger.new($stderr, level: Logger::WARN)

  validate_version!(version)

  meta = bundle_base_name(version)
  base = cache_dir
  dir = File.join(base, version)
  launcher = launcher_path(dir, meta[:name])

  # H1: Assert version dir stays within cache base (path traversal guard)
  assert_within_base!(dir, base)

  # Check cache
  if File.exist?(launcher) && File.size(launcher) > 0
    log.info("Using cached binary: #{launcher}")
    # Contract section 7: prune only after a successful install, not on cache hit
    return launcher
  end

  # Skip-download check
  if ENV['MOCKSERVER_SKIP_BINARY_DOWNLOAD'] && !ENV['MOCKSERVER_SKIP_BINARY_DOWNLOAD'].empty?
    raise Error, "MOCKSERVER_SKIP_BINARY_DOWNLOAD is set but no cached binary at #{launcher}"
  end

  FileUtils.mkdir_p(dir)
  archive_file = "#{meta[:name]}.#{meta[:ext]}"
  archive = File.join(dir, archive_file)
  partial = "#{archive}.part"
  sha_file = "#{archive}.sha256"

  begin
    # Download to a temp file
    url = asset_url(version, archive_file)
    log.info("Downloading #{url}")
    download_file(url, partial)

    # Verify SHA-256 (fail-closed — always required, no bypass)
    sha_url = asset_url(version, "#{archive_file}.sha256")
    download_file(sha_url, sha_file)
    raw = File.read(sha_file, encoding: 'utf-8').strip
    expected = raw.split(/\s+/).first
    if expected.nil? || expected.empty?
      raise Error, "checksum file for #{meta[:name]} is empty or unparseable"
    end

    actual = Digest::SHA256.file(partial).hexdigest
    if expected != actual
      raise Error,
            "checksum mismatch for #{meta[:name]}: expected #{expected}, got #{actual}"
    end
    log.info('Checksum verified')

    File.rename(partial, archive)
  rescue StandardError
    # H3: Best-effort cleanup of BOTH .part and .sha256 temp files on failure
    File.delete(partial) if File.exist?(partial)
    File.delete(sha_file) if File.exist?(sha_file)
    raise
  end

  # Extract the archive into the version directory.
  log.info("Extracting #{archive}")
  extract_archive(archive, dir, meta[:ext])

  # H3: Post-extract path traversal guard — enumerate every extracted entry
  # and verify it resolves within the version directory. If any entry escaped
  # (via ../ or absolute paths in the archive), abort with a clear error.
  verify_extracted_paths!(dir)

  unless File.exist?(launcher) && File.size(launcher) > 0
    raise Error, "launcher missing or empty after extract: #{launcher}"
  end

  File.chmod(0o755, launcher) unless windows?

  # Contract section 7: prune after successful install
  prune_old_versions(version, log: log)

  launcher
end

.launcher_path(dir, bundle_name) ⇒ String

Return the expected launcher path inside a versioned cache directory.

Parameters:

  • dir (String)

    the version directory

  • bundle_name (String)

    the bundle base name

Returns:

  • (String)


126
127
128
129
# File 'lib/mockserver/binary_launcher.rb', line 126

def launcher_path(dir, bundle_name)
  exe = windows? ? 'mockserver.bat' : 'mockserver'
  File.join(dir, bundle_name, 'bin', exe)
end

.prune_old_versions(current_version, log: nil) ⇒ void

This method returns an undefined value.

Remove old version directories from the cache, keeping the current version and at most MAX_PREVIOUS_VERSIONS_TO_KEEP previous versions.

Uses semver-aware numeric segment comparison (H7) rather than lexicographic or mtime-based ordering.

Parameters:

  • current_version (String)
  • log (Logger, nil) (defaults to: nil)


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

def prune_old_versions(current_version, log: nil)
  log ||= Logger.new($stderr, level: Logger::WARN)
  base = cache_dir

  return unless File.directory?(base)

  entries = Dir.entries(base).select do |entry|
    next false if entry == '.' || entry == '..'

    full = File.join(base, entry)
    # Only consider directories (version directories) — never files
    File.directory?(full)
  rescue Errno::ENOENT
    # Directory vanished between Dir.entries and File.directory? — skip
    false
  end

  # Separate current from old
  old_entries = entries.reject { |e| e == current_version }

  # H7: Sort old entries by semver-aware numeric comparison (highest first = kept)
  old_sorted = old_entries.sort { |a, b| compare_versions(b, a) }

  # Keep at most MAX_PREVIOUS_VERSIONS_TO_KEEP
  to_remove = old_sorted.drop(MAX_PREVIOUS_VERSIONS_TO_KEEP)
  to_remove.each do |name|
    full = File.join(base, name)
    begin
      # Safety: never delete outside the cache dir
      real_base = File.realpath(base)
      real_full = File.realpath(full)
      unless real_full.start_with?(real_base + File::SEPARATOR) || real_full == real_base
        log.warn("Skipping suspicious path during prune: #{full}")
        next
      end

      log.info("Pruning old version cache: #{name}")
      FileUtils.rm_rf(full)
    rescue Errno::ENOENT, Errno::EACCES => e
      # COR-06: directory vanished concurrently or permission denied — skip gracefully
      log.warn("Skipping during prune (#{e.class}): #{full}")
      next
    end
  end

  # Clean up leftover .part and .sha256 temp files at ALL levels (not just base)
  Dir.glob(File.join(base, '**', '*.part')).each do |part_file|
    log.info("Removing leftover temp file: #{part_file}")
    File.delete(part_file)
  rescue StandardError => e
    log.warn("Failed to remove temp file #{part_file}: #{e.message}")
  end

  Dir.glob(File.join(base, '**', '*.sha256')).each do |sha_file|
    # Only remove orphaned .sha256 files (where the corresponding archive is absent)
    archive_path = sha_file.sub(/\.sha256\z/, '')
    next if File.exist?(archive_path)

    log.info("Removing orphaned checksum file: #{sha_file}")
    File.delete(sha_file)
  rescue StandardError => e
    log.warn("Failed to remove checksum file #{sha_file}: #{e.message}")
  end
end

.resolve_platformHash

Resolve the current platform to the bundle naming tokens.

Returns:

  • (Hash)

    with keys :os_name, :arch, :ext

Raises:

  • (Error)

    on unsupported platform or architecture



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/mockserver/binary_launcher.rb', line 51

def resolve_platform
  os_name, ext = case RbConfig::CONFIG['host_os']
                 when /linux/i    then ['linux', 'tar.gz']
                 when /darwin/i   then ['darwin', 'tar.gz']
                 when /mswin|mingw|cygwin/i then ['windows', 'zip']
                 else raise Error, "unsupported platform: #{RbConfig::CONFIG['host_os']}"
                 end

  arch = case RbConfig::CONFIG['host_cpu']
         when /x86_64|x64|amd64/i then 'x86_64'
         when /aarch64|arm64/i     then 'aarch64'
         else raise Error, "unsupported architecture: #{RbConfig::CONFIG['host_cpu']}"
         end

  { os_name: os_name, arch: arch, ext: ext }
end

.start(port:, version: nil, extra_args: [], log: nil) ⇒ ServerHandle

Start a MockServer instance on the given port.

Parameters:

  • port (Integer)

    the server port

  • version (String, nil) (defaults to: nil)

    the MockServer version

  • extra_args (Array<String>) (defaults to: [])

    additional CLI arguments

  • log (Logger, nil) (defaults to: nil)

    optional logger

Returns:



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/mockserver/binary_launcher.rb', line 228

def start(port:, version: nil, extra_args: [], log: nil)
  launcher = ensure_launcher(version: version, log: log)
  args = ['-serverPort', port.to_s] + extra_args

  # H4: On Windows, .bat files must be invoked via cmd.exe /c.
  # H5: Drain stdout/stderr via :out/:err redirection to avoid pipe-buffer deadlock.
  pid = if windows?
          Process.spawn('cmd.exe', '/c', launcher, *args,
                        out: File::NULL, err: File::NULL)
        else
          Process.spawn(launcher, *args,
                        out: File::NULL, err: File::NULL)
        end
  ServerHandle.new(pid: pid, port: port, launcher: launcher)
end