From 2f767630326d0a6b461d9a4bab1c8e9e6535f961 Mon Sep 17 00:00:00 2001 From: Francisc Balint <7178547+franciscbalint@users.noreply.github.com> Date: Thu, 12 Nov 2026 05:11:19 +0400 Subject: [PATCH] fix: audit findings (2026-11-11, round 4) --- CHANGELOG.md | 8 + lib/zerobounce.rb | 18 +- lib/zerobounce/base_request.rb | 44 +++- lib/zerobounce/response_error.rb | 19 ++ lib/zerobounce/warmup.rb | 10 +- spec/bulk_jobs_spec.rb | 8 + spec/request_hygiene_spec.rb | 36 ++++ spec/transport_guards_spec.rb | 355 +++++++++++++++++++++++++++++++ 8 files changed, 481 insertions(+), 17 deletions(-) create mode 100644 spec/transport_guards_spec.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 87d9988..5184cd6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Fixed + +- `validate_file_send_stream` and `scoring_file_send_stream` work again. From 2.0.1 to 3.0.1 they raised `ArgumentError` ("File path must be under the current directory") whenever the system temp directory is outside the current directory, as it usually is: they wrote the content to a Tempfile in the system temp directory and uploaded its path, which the path check added in 2.0.1 rejects. 2.0.0 was not affected. The content is now uploaded from memory under the given `file_name` (2.0.0 sent the temp file's random name); file paths passed to `validate_file_send` and the other upload methods are still checked as before. +- A response whose body is cut short (the connection closes before `Content-Length` bytes arrive) raises `Zerobounce::ApiResponseError` with `status_code` 0 on every request, including the result-file downloads and `Zerobounce::Warmup`. Up to 3.0.1 Net::HTTP returned the bytes that had arrived, so a truncated result file or JSON body after a 200 header was returned as a success. +- `Zerobounce::Warmup#download_seeds` and `#download_statistics` raise `Zerobounce::ApiResponseError` (with the HTTP status) for an HTML page on a 200, such as a proxy's "Access denied" page, as the Python SDK does. Up to 3.0.1 the page was returned as the CSV text. + ## [3.0.1] - 2026-11-11 ### Fixed diff --git a/lib/zerobounce.rb b/lib/zerobounce.rb index 41fe970..5b55bfa 100644 --- a/lib/zerobounce.rb +++ b/lib/zerobounce.rb @@ -377,12 +377,9 @@ def validate_file_send( # @return [Hash] same as validate_file_send def validate_file_send_stream(io, file_name, **opts) content = io.respond_to?(:read) ? io.read : io.to_s - Tempfile.create(['zb', File.extname(file_name)]) do |tmp| - tmp.binmode - tmp.write(content) - tmp.rewind - validate_file_send(tmp.path, **opts) - end + # Uploaded from memory: a Tempfile in Dir.tmpdir failed the check that + # keeps file paths under the current directory (2.0.1 to 3.0.1). + validate_file_send(BaseRequest::Upload.new(content, file_name), **opts) end # Get validate file status @@ -477,12 +474,9 @@ def scoring_file_send( # @return [Hash] same as scoring_file_send def scoring_file_send_stream(io, file_name, **opts) content = io.respond_to?(:read) ? io.read : io.to_s - Tempfile.create(['zb', File.extname(file_name)]) do |tmp| - tmp.binmode - tmp.write(content) - tmp.rewind - scoring_file_send(tmp.path, **opts) - end + # Uploaded from memory: a Tempfile in Dir.tmpdir failed the check that + # keeps file paths under the current directory (2.0.1 to 3.0.1). + scoring_file_send(BaseRequest::Upload.new(content, file_name), **opts) end # Get scoring bulk results file diff --git a/lib/zerobounce/base_request.rb b/lib/zerobounce/base_request.rb index d53421b..5c5a758 100644 --- a/lib/zerobounce/base_request.rb +++ b/lib/zerobounce/base_request.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require 'json' +require 'stringio' require 'zerobounce/api_urls' require 'zerobounce/response_error' require 'zerobounce/api_key' @@ -14,6 +15,36 @@ module Zerobounce # Sends the HTTP request. class BaseRequest + # A file part the SDK builds from the caller's IO or String (the + # *_send_stream methods). It is content, not a path, so the check that + # keeps caller-supplied paths under the current directory does not apply + # to it, and nothing is written to disk. RestClient sends it as a file + # part named +original_filename+. + class Upload + attr_reader :original_filename + + def initialize(content, file_name) + @io = StringIO.new(content.to_s.b) + @original_filename = File.basename(file_name.to_s) + end + + # RestClient treats an object with #path and #read as a file part. + def path + @original_filename + end + + def read(*args) + @io.read(*args) + end + + def content_type + 'text/csv' + end + + def close + @io.close + end + end protected @@ -99,7 +130,9 @@ def self.__execute_request__(**kwargs) kwargs[:max_redirects] = 0 user_agent = Zerobounce.config.headers && Zerobounce.config.headers[:user_agent] kwargs[:headers] = (kwargs[:headers] || {}).merge(user_agent: user_agent) if user_agent - RestClient::Request.execute(**kwargs) + response = RestClient::Request.execute(**kwargs) + ResponseError.raise_if_cut_short!(response) + response rescue RestClient::ExceptionWithResponse => e # Re-raised as the same RestClient class (RestClient::NotFound and so # on), so `rescue RestClient::...` and #http_code keep working as they @@ -110,6 +143,8 @@ def self.__execute_request__(**kwargs) rescue RestClient::Exception => e e.message = __redact_api_key__(e.message) raise e + rescue ApiResponseError + raise rescue StandardError => e # Same class and backtrace, redacted message. cause: nil, because the # original (unredacted) error would otherwise ride along as #cause and @@ -145,7 +180,12 @@ def self._post(root, path, params, content_type='application/json', filepath=nil params.each do |key, value| params[key] = value ? 'true' : 'false' if value == true || value == false end - params[:file] = File.new(Zerobounce::BaseRequest.__safe_file_path__(filepath), 'rb') + params[:file] = + if filepath.is_a?(Upload) + filepath + else + File.new(Zerobounce::BaseRequest.__safe_file_path__(filepath), 'rb') + end params[:multipart] = true response = __execute_request__(method: :post, url: url, payload: params, timeout: 120) diff --git a/lib/zerobounce/response_error.rb b/lib/zerobounce/response_error.rb index 68fe864..9dfe6b7 100644 --- a/lib/zerobounce/response_error.rb +++ b/lib/zerobounce/response_error.rb @@ -113,5 +113,24 @@ def message_from(response) code = response.respond_to?(:code) ? response.code : 0 message_from_parts(code, content_type, response.respond_to?(:body) ? response.body : response.to_s) end + + # Raises when fewer bytes arrived than the response's Content-Length. + # Net::HTTP ignores an early EOF by default (ignore_eof) and returns what + # it has, so a connection that closes mid-body would otherwise read as a + # complete, successful response. A transport failure: status 0. + def raise_if_cut_short!(response) + return if [204, 304].include?(response.code.to_i) + + expected = response.headers[:content_length].to_s + return unless expected.match?(/\A\d+\z/) + + received = response.body.to_s.bytesize + return if received >= expected.to_i + + raise ApiResponseError.new( + "The response from ZeroBounce was cut short: #{received} of #{expected} bytes arrived " \ + 'before the connection closed.', 0 + ) + end end end diff --git a/lib/zerobounce/warmup.rb b/lib/zerobounce/warmup.rb index 2228771..19f7766 100644 --- a/lib/zerobounce/warmup.rb +++ b/lib/zerobounce/warmup.rb @@ -411,7 +411,9 @@ def send_request(method, path, params, body, secrets) options[:payload] = body.to_json options[:headers][:content_type] = :json end - RestClient::Request.execute(**options) + response = RestClient::Request.execute(**options) + ResponseError.raise_if_cut_short!(response) + response rescue RestClient::ExceptionWithResponse => e response = e.response status = response.respond_to?(:code) ? response.code : 0 @@ -456,12 +458,14 @@ def json_request(method, path, params = {}, body = nil, secrets: []) end end - # A CSV download, returned as text. + # A CSV download, returned as text. An HTML page on a 200 (a proxy's + # "Access denied") is an error, not CSV. def csv(path, **params) response = send_request(:get, path, params, nil, []) text = response.body.to_s content_type = (response.headers[:content_type] || '').to_s - if text.strip.empty? || content_type.downcase.include?('application/json') + if text.strip.empty? || content_type.downcase.include?('application/json') || + ResponseError.html?(text, content_type) raise ApiResponseError.new( redact(ResponseError.message_from_parts(response.code, content_type, text)), response.code diff --git a/spec/bulk_jobs_spec.rb b/spec/bulk_jobs_spec.rb index f5c4bbb..db4f8d2 100644 --- a/spec/bulk_jobs_spec.rb +++ b/spec/bulk_jobs_spec.rb @@ -317,6 +317,14 @@ def last_query expect(JSON.parse(last_request.body)).to eq('name' => 'Launch', 'testType' => 3) end + it 'treats an empty 2xx answer to a delete as success, as the Go SDK does' do + [204, 200].each do |status| + stub_request(:delete, %r{\Ahttps://bulkapi\.zerobounce\.net/api/ipt/test/7\z}) + .to_return(status: status, body: '') + expect(Zerobounce.delete_inbox_placement_test('7')).to be_nil + end + end + it 'deletes a test and sets the webhook' do Zerobounce.delete_inbox_placement_test('a b/c') expect(last_request.method).to eq(:delete) diff --git a/spec/request_hygiene_spec.rb b/spec/request_hygiene_spec.rb index 708a1b7..bcba895 100644 --- a/spec/request_hygiene_spec.rb +++ b/spec/request_hygiene_spec.rb @@ -52,6 +52,42 @@ def json_reply(body = '{}') end end + # Up to 3.0.1 these wrote a Tempfile in Dir.tmpdir and uploaded its path, + # which the check that keeps file paths under the current directory + # rejected unless the temp dir happened to be inside it. + describe 'stream uploads, with the real temp dir' do + before do + stub_request(:post, %r{\Ahttps://bulkapi\.zerobounce\.net/v2/(scoring/)?sendfile\z}) + .to_return(json_reply('{"success":true,"file_id":"f1"}')) + end + + it 'runs where the temp dir is outside the current directory, as it usually is' do + expect(File.realpath(Dir.tmpdir)).not_to start_with(File.realpath(Dir.pwd) + File::SEPARATOR) + end + + { + validate_file_send_stream: '/v2/sendfile', + scoring_file_send_stream: '/v2/scoring/sendfile' + }.each do |name, path| + it "#{name} uploads an IO and a String under the given file name" do + [StringIO.new("email\na@example.com\n"), "email\na@example.com\n"].each do |content| + expect(Zerobounce.public_send(name, content, 'list.csv')).to include('file_id' => 'f1') + expect(last_request.uri.path).to eq(path) + body = last_request.body.to_s + expect(body).to include('filename="list.csv"', "\r\n\r\nemail\na@example.com\n\r\n") + expect(body).to include("name=\"api_key\"\r\n\r\n#{api_key}") + end + end + end + + it 'still checks a file path the caller passes' do + expect { Zerobounce.validate_file_send('/etc/passwd') } + .to raise_error(ArgumentError, 'File path must be under the current directory') + expect { Zerobounce.scoring_file_send('../outside.csv') } + .to raise_error(ArgumentError, 'File path must be under the current directory') + end + end + describe 'list evaluator base URL' do let(:file) { File.join('spec', 'fixtures', 'priority3_finder.csv') } diff --git a/spec/transport_guards_spec.rb b/spec/transport_guards_spec.rb new file mode 100644 index 0000000..15822fc --- /dev/null +++ b/spec/transport_guards_spec.rb @@ -0,0 +1,355 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'socket' +require 'webmock/rspec' + +# rubocop:disable Metrics/BlockLength, Metrics/ModuleLength +# The transport guards on every request path: a body cut short, redirects and +# timeouts. Each sweep enumerates every public request method of the client +# and the Warmup client, and a guard fails when one is missing from it. +module TransportSweep + FILE = 'spec/fixtures/priority3_finder.csv' + DONE = 'https://example.com/d' + + def self.csv_io + StringIO.new("email\na@example.com\n") + end + + # Every public request method of Zerobounce, called once. + CALLS = { + validate: -> { Zerobounce.validate('a@example.com') }, + credits: -> { Zerobounce.credits }, + api_usage: -> { Zerobounce.api_usage(Date.new(2024, 1, 1), Date.new(2024, 1, 2)) }, + activity: -> { Zerobounce.activity('a@example.com') }, + score_email: -> { Zerobounce.score_email('a@example.com') }, + validate_batch: -> { Zerobounce.validate_batch(['a@example.com']) }, + validate_file_send: -> { Zerobounce.validate_file_send(FILE) }, + validate_file_send_stream: -> { Zerobounce.validate_file_send_stream(csv_io, 'f.csv') }, + validate_file_check: -> { Zerobounce.validate_file_check('f1') }, + validate_file_get: -> { Zerobounce.validate_file_get('f1') }, + validate_file_delete: -> { Zerobounce.validate_file_delete('f1') }, + scoring_file_send: -> { Zerobounce.scoring_file_send(FILE) }, + scoring_file_send_stream: -> { Zerobounce.scoring_file_send_stream(csv_io, 'f.csv') }, + scoring_file_get: -> { Zerobounce.scoring_file_get('f1') }, + scoring_file_check: -> { Zerobounce.scoring_file_check('f1') }, + scoring_file_delete: -> { Zerobounce.scoring_file_delete('f1') }, + guessformat: -> { Zerobounce.guessformat('example.com') }, + find_email: -> { Zerobounce.find_email('Ann', domain: 'example.com') }, + find_domain: -> { Zerobounce.find_domain(domain: 'example.com') }, + send_email_finder_file: -> { Zerobounce.send_email_finder_file(FILE, domain_column: 1, first_name_column: 2) }, + email_finder_file_status: -> { Zerobounce.email_finder_file_status('f1') }, + email_finder_file_get: -> { Zerobounce.email_finder_file_get('f1') }, + email_finder_file_delete: -> { Zerobounce.email_finder_file_delete('f1') }, + send_domain_search_file: -> { Zerobounce.send_domain_search_file(FILE, domain_column: 1) }, + domain_search_file_status: -> { Zerobounce.domain_search_file_status('f1') }, + domain_search_file_get: -> { Zerobounce.domain_search_file_get('f1') }, + domain_search_file_delete: -> { Zerobounce.domain_search_file_delete('f1') }, + send_list_evaluator_file: -> { Zerobounce.send_list_evaluator_file(FILE, email_address_column: 1) }, + get_list_evaluator_result: -> { Zerobounce.get_list_evaluator_result('f1') }, + send_evaluated_file: -> { Zerobounce.send_evaluated_file('f1') }, + add_filter: -> { Zerobounce.add_filter(rule: 'allow', target: 'email', value: 'a@example.com') }, + list_filters: -> { Zerobounce.list_filters }, + delete_filter: -> { Zerobounce.delete_filter(rule: 'allow', target: 'email', value: 'a@example.com') }, + list_s3_files: -> { Zerobounce.list_s3_files }, + validate_s3_file: -> { Zerobounce.validate_s3_file(file_name: 'f.csv', return_url: DONE) }, + score_s3_file: -> { Zerobounce.score_s3_file(file_name: 'f.csv', return_url: DONE) }, + export_s3_file: -> { Zerobounce.export_s3_file(file_id: 'f1') }, + email_finder_s3_file: -> { Zerobounce.email_finder_s3_file('f.csv', true, return_url: DONE) }, + domain_search_s3_file: -> { Zerobounce.domain_search_s3_file('f.csv', true, return_url: DONE) }, + validate_sftp_file: -> { Zerobounce.validate_sftp_file('f.csv', true, return_url: DONE) }, + score_sftp_file: -> { Zerobounce.score_sftp_file('f.csv', true, return_url: DONE) }, + email_finder_sftp_file: -> { Zerobounce.email_finder_sftp_file('f.csv', true, return_url: DONE) }, + domain_search_sftp_file: -> { Zerobounce.domain_search_sftp_file('f.csv', true, return_url: DONE) }, + export_sftp_file: -> { Zerobounce.export_sftp_file(file_id: 'f1') }, + inbox_placement_providers: -> { Zerobounce.inbox_placement_providers }, + inbox_placement_test_types: -> { Zerobounce.inbox_placement_test_types }, + create_inbox_placement_test: -> { Zerobounce.create_inbox_placement_test('Test', test_type: 2) }, + inbox_placement_test: -> { Zerobounce.inbox_placement_test('1') }, + list_inbox_placement_tests: -> { Zerobounce.list_inbox_placement_tests }, + delete_inbox_placement_test: -> { Zerobounce.delete_inbox_placement_test('1') }, + inbox_placement_webhook: -> { Zerobounce.inbox_placement_webhook }, + set_inbox_placement_webhook: -> { Zerobounce.set_inbox_placement_webhook('https://example.com/hook') } + }.freeze + + NOT_REQUESTS = %i[configuration config configure configuration= with_api_key + get_file_json_indicates_error? zb_request].freeze + + # Every public method of Zerobounce::Warmup, called once. + WARMUP_CALLS = { + list_sending_accounts: ->(w) { w.list_sending_accounts }, + get_sending_account: ->(w) { w.get_sending_account('a@b.com') }, + add_sending_account: ->(w) { w.add_sending_account('a@b.com', 'self_managed', engagement_rule_id: 0) }, + update_sending_account: ->(w) { w.update_sending_account('a@b.com', 1, 4, true) }, + delete_sending_account: ->(w) { w.delete_sending_account('a@b.com') }, + change_from_address: ->(w) { w.change_from_address('a@b.com', 'c@d.com') }, + list_from_addresses: ->(w) { w.list_from_addresses }, + engagement_rules: ->(w) { w.engagement_rules }, + set_engagement_rule: ->(w) { w.set_engagement_rule('a@b.com', 2) }, + custom_engagement: ->(w) { w.custom_engagement('a@b.com') }, + create_custom_engagement: ->(w) { w.create_custom_engagement('a@b.com', 10, 10, 5) }, + update_custom_engagement: ->(w) { w.update_custom_engagement('a@b.com', 10, 10, 5) }, + delete_custom_engagement: ->(w) { w.delete_custom_engagement('a@b.com', 1) }, + seeds: ->(w) { w.seeds }, + download_seeds: ->(w) { w.download_seeds }, + seed_count: ->(w) { w.seed_count }, + progress_today: ->(w) { w.progress_today }, + sent_today: ->(w) { w.sent_today }, + emails_per_day: ->(w) { w.emails_per_day }, + statistics: ->(w) { w.statistics('a@b.com') }, + statistics_per_day: ->(w) { w.statistics_per_day('a@b.com', '2026-09-01', '2026-09-14') }, + statistics_detailed: ->(w) { w.statistics_detailed('a@b.com') }, + download_statistics: ->(w) { w.download_statistics('a@b.com') }, + from_address_statistics: ->(w) { w.from_address_statistics('a@b.com') }, + check_domain_dmarc: ->(w) { w.check_domain_dmarc('a@b.com') }, + test_smtp_configuration: ->(w) { w.test_smtp_configuration('a@b.com', 'u', 'p', 'smtp.example.com', 587) } + }.freeze + + # Points every base URL of the client at +root+. + def self.configure(api_key, root) + Zerobounce.configure do |c| + c.apikey = api_key + c.api_root_url = "#{root}/v2" + c.bulk_api_root_url = "#{root}/v2" + c.bulk_root_url = root + c.list_evaluator_root_url = "#{root}/v2/listevaluator" + c.inbox_placement_root_url = "#{root}/api/ipt" + end + end + + def self.warmup(api_key, root) + Zerobounce::Warmup.new(api_key).tap { |w| w.instance_variable_set(:@root, "#{root}/api/v1/warmup") } + end +end + +# A loopback HTTP server on a raw socket: reads each request, writes the bytes +# the block returns for its request line, and closes the connection. +class RawSocketServer + attr_reader :hits + + def initialize(&responder) + @server = TCPServer.new('127.0.0.1', 0) + @hits = 0 + @thread = Thread.new { serve(responder) } + end + + def url + "http://127.0.0.1:#{@server.addr[1]}" + end + + def close + @thread.kill + @server.close + end + + private + + def serve(responder) + loop do + client = @server.accept + @hits += 1 + answer(client, responder) + end + end + + def answer(client, responder) + client.write(responder.call(read_request(client))) + rescue StandardError + nil + ensure + client.close + end + + # The request line, after the whole request (headers and body) is read. + def read_request(client) + data = +'' + data << client.readpartial(65_536) until data.include?("\r\n\r\n") + head, body = data.split("\r\n\r\n", 2) + length = head[/^content-length:\s*(\d+)/i, 1].to_i + body << client.readpartial(65_536) while body.bytesize < length + head.lines.first.to_s + end +end + +describe 'Transport guards on every request path' do + let(:api_key) { 'guard-key-123' } + + around do |example| + saved = Zerobounce.configuration + Zerobounce.configuration = Zerobounce::Configuration.new + example.run + ensure + Zerobounce.configuration = saved + end + + before { allow(Zerobounce).to receive(:warn) } + + it 'sweeps every public request method of the client' do + expect(Zerobounce.singleton_methods.sort - TransportSweep::NOT_REQUESTS - TransportSweep::CALLS.keys).to eq([]) + end + + it 'sweeps every public method of the Warmup client' do + expect(Zerobounce::Warmup.public_instance_methods(false).sort - %i[inspect] - TransportSweep::WARMUP_CALLS.keys) + .to eq([]) + end + + # Net::HTTP returns what arrived when the connection closes before + # Content-Length bytes (ignore_eof), so a 200 with a cut-short body would + # otherwise read as a complete result. + describe 'a body cut short after its 200 header' do + csv = "email,status\na@b.c,valid\n" # 25 bytes + json = '{"Credits":"5","a":"bbb"}' # 25 bytes, valid JSON on its own + + server = nil + before(:all) do + WebMock.disable! + server = RawSocketServer.new do |request_line| + file = request_line.include?('getfile') || request_line.include?('/download') + type, body = file ? ['application/octet-stream', csv] : ['application/json', json] + "HTTP/1.1 200 OK\r\nContent-Type: #{type}\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n#{body}" + end + end + + after(:all) do + server.close + WebMock.enable! + end + + before do + allow(Zerobounce::BaseRequest).to receive(:__require_https__) { |url| url } + TransportSweep.configure(api_key, server.url) + end + + def expect_cut_short(&call) + expect(&call).to raise_error(Zerobounce::ApiResponseError) { |error| + expect([error.status_code, error.message]).to match([0, include('25 of 1000 bytes')]) + expect(error.full_message(highlight: false)).not_to include(api_key) + } + end + + TransportSweep::CALLS.each do |name, call| + it "raises for #{name}" do + expect_cut_short { call.call } + end + end + + TransportSweep::WARMUP_CALLS.each do |name, call| + it "raises for Warmup##{name}" do + warmup = TransportSweep.warmup(api_key, server.url) + expect_cut_short { call.call(warmup) } + end + end + end + + # A 3xx WITH a Location header: a client that followed redirects would + # reach the second host, carrying the key. + describe 'redirects' do + statuses = [301, 302, 303, 307, 308] + + def stub_redirect(status) + stub_request(:any, %r{\Ahttps://first\.example/}) + .to_return(status: status, body: '', headers: { 'Location' => 'https://second.example/landed' }) + stub_request(:any, %r{\Ahttps://second\.example/}) + .to_return(status: 200, body: '{"Credits":"999"}', headers: { 'Content-Type' => 'application/json' }) + end + + def expect_refused(status, &call) + expect(&call).to raise_error(StandardError) { |error| + expect(error.message).not_to include('999') + } + expect(a_request(:any, %r{\Ahttps://second\.example/})).not_to have_been_made, "HTTP #{status} was followed" + end + + before { TransportSweep.configure(api_key, 'https://first.example') } + + TransportSweep::CALLS.each do |name, call| + it "are not followed by #{name}" do + statuses.each do |status| + WebMock.reset! + stub_redirect(status) + expect_refused(status) { call.call } + end + end + end + + TransportSweep::WARMUP_CALLS.each do |name, call| + it "are not followed by Warmup##{name}" do + statuses.each do |status| + WebMock.reset! + stub_redirect(status) + expect_refused(status) { call.call(TransportSweep.warmup(api_key, 'https://first.example')) } + end + end + end + end + + # Every request is sent with an explicit timeout: RestClient's own + # defaults would otherwise apply. + describe 'timeouts' do + let(:sent) { [] } + + before do + TransportSweep.configure(api_key, 'https://first.example') + stub_request(:any, %r{\Ahttps://first\.example/}) + .to_return(status: 200, body: '{"success":true}', headers: { 'Content-Type' => 'application/json' }) + allow(RestClient::Request).to receive(:execute).and_wrap_original do |original, *args, **kwargs, &block| + sent << (args.first || kwargs) + original.call(*args, **kwargs, &block) + end + end + + def expect_timeouts(name) + begin + yield + rescue StandardError + nil # Only the options the request went out with matter here. + end + expect(sent).not_to be_empty, "#{name} sent no request" + sent.each { |options| expect(options[:timeout]).to eq(120), "#{name} was sent without its timeout" } + end + + TransportSweep::CALLS.each do |name, call| + it "are set by #{name}" do + expect_timeouts(name) { call.call } + end + end + + TransportSweep::WARMUP_CALLS.each do |name, call| + it "are set by Warmup##{name}" do + expect_timeouts(name) { call.call(TransportSweep.warmup(api_key, 'https://first.example')) } + end + end + end + + describe 'an HTML page on a 200' do + page = '