Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 6 additions & 12 deletions lib/zerobounce.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
44 changes: 42 additions & 2 deletions lib/zerobounce/base_request.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# frozen_string_literal: true

require 'json'
require 'stringio'
require 'zerobounce/api_urls'
require 'zerobounce/response_error'
require 'zerobounce/api_key'
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand Down
19 changes: 19 additions & 0 deletions lib/zerobounce/response_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
10 changes: 7 additions & 3 deletions lib/zerobounce/warmup.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions spec/bulk_jobs_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
36 changes: 36 additions & 0 deletions spec/request_hygiene_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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') }

Expand Down
Loading
Loading