diff --git a/CHANGELOG.md b/CHANGELOG.md index fb26148..3001368 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - `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. - An HTML page on a 200 (such as a proxy's "Access denied" page), or a JSON content type with a body that does not parse, raises `Zerobounce::ApiResponseError` with `status_code` 200 from every request method, as the Python and PHP SDKs do; so does any other non-JSON body from the calls that answer in JSON. Up to 3.0.1 `validate_file_send`, `scoring_file_send` (and their `_stream` forms), `send_email_finder_file`, `send_domain_search_file`, `email_finder_file_status`, `email_finder_file_delete`, `domain_search_file_status`, `domain_search_file_delete`, `send_list_evaluator_file`, `send_evaluated_file` and `list_s3_files` returned an HTML or other non-JSON body as a successful `String`; `validate_file_check`, `validate_file_delete`, `scoring_file_check` and `scoring_file_delete` raised a plain `RuntimeError` with no status for an HTML page, and `JSON::ParserError` for a JSON content type with a body that does not parse. - `Zerobounce::Warmup#add_sending_account` parses `ignore_conflict` strictly, as the client parses its boolean options: `true`/`false`, `'true'`/`'false'` (any case) and `1`/`0` are accepted, and anything else raises `ArgumentError` before a request is sent. Up to 3.0.1 any truthy value was sent as `true`, so `ignore_conflict: 'false'` sent `true`. `ignore_conflict: nil` now leaves the field out (3.0.1 sent `false`). +- `Zerobounce::Warmup#add_sending_account` sends the documented ZeroBounce Managed fields: `email_content` takes `company_name`, `company_website`, `company_description`, `types_of_emails` and `example_email`, and `managed_sending` takes `weekdays_only`, `timezone`, `timezone_offset` and `warmup_start_date`, as the Python SDK and the API docs have them. Up to 3.0.1 it dropped `company_website`, `company_description`, `example_email`, `weekdays_only` and `timezone` without a word and sent `industry`, `website` and `daily_limit`, which the API does not read. The old `website` key is still accepted and sent as `company_website`; `industry`, `daily_limit` and any other unknown key are left out, as unknown keys always were, but now with a warning that names the documented fields. `weekdays_only` is parsed strictly (`'false'` is false; anything that is not a boolean raises `ArgumentError`), `timezone` must be a String, and `timezone_offset` takes fractional hours (-11 to 14, e.g. `3.0`), which 3.0.1 rejected. + +### Security + +- No error raised by the SDK carries the API key when a response body quotes it. Messages built from a body (a 2xx `{"error": "Invalid API key "}`, a `{"success": false, "message": ...}`, a batch `"all"` error, an HTML page's title, a result-file download's JSON error) were passed on unredacted on every client method up to 3.0.1; only HTTP error statuses were redacted. `Zerobounce::ApiResponseError` now redacts its message itself (raw and URL-encoded forms), so every path that raises it is covered. A body that is not valid JSON no longer keeps the parser's error, which quotes the body, as `#cause` (client and `Zerobounce::Warmup`). ## [3.0.1] - 2026-11-11 diff --git a/README.md b/README.md index ce792ac..2d1399d 100644 --- a/README.md +++ b/README.md @@ -742,11 +742,16 @@ Or have ZeroBounce provision the mailbox. A 200 means the request was accepted; ```ruby warmup.add_sending_account( 'sender@example.com', 'zb_managed', - email_content: { types_of_emails: %w[newsletter marketing] }, - managed_sending: { timezone_offset: -5, warmup_start_date: Date.new(2026, 3, 4) } + email_content: { company_name: 'Acme', company_website: 'https://acme.example', + company_description: 'B2B email tools', types_of_emails: %w[newsletter marketing], + example_email: 'Hi, a short intro to Acme.' }, + managed_sending: { weekdays_only: true, timezone: 'America/New_York', timezone_offset: -5, + warmup_start_date: Date.new(2026, 3, 4) } ) ``` +Keys other than these are not API fields: they are left out of the request with a warning. + A custom engagement rule can be changed only once every seven days; inside that window the API answers 429. ```ruby diff --git a/lib/zerobounce/base_request.rb b/lib/zerobounce/base_request.rb index a3713e1..2b2b27f 100644 --- a/lib/zerobounce/base_request.rb +++ b/lib/zerobounce/base_request.rb @@ -355,7 +355,9 @@ def self.__parse_json_body__(response) begin JSON.parse(body) rescue JSON::ParserError - raise ApiResponseError.new('ZeroBounce returned a response that is not valid JSON.', code) + # cause: nil, or the parser's error, which quotes the body, would ride + # along as #cause. + raise ApiResponseError.new('ZeroBounce returned a response that is not valid JSON.', code), cause: nil end end diff --git a/lib/zerobounce/error.rb b/lib/zerobounce/error.rb index 64de588..3732beb 100644 --- a/lib/zerobounce/error.rb +++ b/lib/zerobounce/error.rb @@ -64,14 +64,26 @@ def parse200(env) # successful HTTP response; both carry the same short message. It is a # RuntimeError, which those errors were before, so `rescue RuntimeError` # still catches them. + # + # Its message is often built from a response body, which can quote the + # API key (an "Invalid API key " message, a proxy echoing the request + # URL, an HTML title). Every message is therefore redacted here, once, so + # each path that raises this error inherits it. class ApiResponseError < RuntimeError # @return [Integer] the HTTP status of the failed response, or 0 attr_reader :status_code def initialize(message, status_code = 0) - super(message) + super(ApiResponseError.redact(message)) @status_code = status_code.to_i end + + # The message with the request's API key replaced by ***. + def self.redact(message) + return message unless defined?(Zerobounce::BaseRequest) + + Zerobounce::BaseRequest.__redact_api_key__(message) + end end # Server returned a 500 error. diff --git a/lib/zerobounce/request.rb b/lib/zerobounce/request.rb index d459724..e2539cf 100644 --- a/lib/zerobounce/request.rb +++ b/lib/zerobounce/request.rb @@ -94,7 +94,10 @@ def self.interpret_json_response(response, path = nil) begin parsed = JSON.parse(body) rescue JSON::ParserError - raise ApiResponseError.new('ZeroBounce returned a response that is not valid JSON.', response.code) + # cause: nil, or the parser's error, which quotes the body, would ride + # along as #cause. + raise ApiResponseError.new('ZeroBounce returned a response that is not valid JSON.', response.code), + cause: nil end return parsed unless parsed.is_a?(Hash) diff --git a/lib/zerobounce/warmup.rb b/lib/zerobounce/warmup.rb index 61056bf..bf42785 100644 --- a/lib/zerobounce/warmup.rb +++ b/lib/zerobounce/warmup.rb @@ -32,6 +32,12 @@ class Warmup ONBOARDING_MODELS = %w[self_managed zb_managed].freeze EMAIL_TYPES = %w[transactional newsletter marketing].freeze + # The documented email_content fields + # (https://www.zerobounce.net/docs/warmup-api/adding-a-sending-account). + EMAIL_CONTENT_FIELDS = %w[company_name company_website company_description types_of_emails example_email].freeze + # The documented managed_sending fields. + MANAGED_SENDING_FIELDS = %w[weekdays_only timezone timezone_offset warmup_start_date].freeze + # Required by the schema but always replaced with the key's own team. ANY_TEAM_ID = 1 @@ -74,9 +80,12 @@ def get_sending_account(from_address) # Adds a from-address to warmup. POST /sending-accounts # # +self_managed+ runs your own mailbox and needs +engagement_rule_id+ 0-4. - # +zb_managed+ has ZeroBounce provision it and takes +email_content+ and - # +managed_sending+; a 200 means accepted, and the mailbox is provisioned - # afterwards. + # +zb_managed+ has ZeroBounce provision it and takes +email_content+ + # (+company_name+, +company_website+, +company_description+, + # +types_of_emails+, +example_email+) and +managed_sending+ + # (+weekdays_only+, +timezone+, +timezone_offset+ -11 to 14, + # +warmup_start_date+); a 200 means accepted, and the mailbox is + # provisioned afterwards. Other keys are not sent and draw a warning. def add_sending_account(from_address, onboarding_model, **options) require_value(from_address, 'from_address') unless ONBOARDING_MODELS.include?(onboarding_model.to_s) @@ -351,12 +360,33 @@ def engagement_body(c_from, reply_pct, important_pct, click_pct) 'important_pct' => important_pct, 'click_pct' => click_pct } end + # The value of +key+ (a Symbol or String key) and whether it was given. + # Looked up with key? so a false value is kept. + def field(hash, key) + return [true, hash[key.to_sym]] if hash.key?(key.to_sym) + return [true, hash[key.to_s]] if hash.key?(key.to_s) + + [false, nil] + end + + # Keys that are not API fields are left out of the request, with a + # warning naming the documented fields, as unknown keys were always left + # out (silently, up to 3.0.1). + def warn_unknown(hash, known, name) + unknown = hash.keys.map(&:to_s).uniq - known + return if unknown.empty? + + warn "Zerobounce::Warmup#add_sending_account: #{name} #{unknown.join(', ')} " \ + "#{unknown.length == 1 ? 'is not an API field' : 'are not API fields'} and not sent; " \ + "the fields are #{known.join(', ')}" + end + def email_content_body(content) raise ArgumentError, 'email_content must be a Hash' unless content.is_a?(Hash) body = {} - types = content[:types_of_emails] || content['types_of_emails'] - unless types.nil? + given, types = field(content, :types_of_emails) + if given && !types.nil? Array(types).each do |kind| unless EMAIL_TYPES.include?(kind.to_s) raise ArgumentError, 'types_of_emails must be transactional, newsletter and/or marketing' @@ -364,10 +394,15 @@ def email_content_body(content) end body['types_of_emails'] = Array(types).map(&:to_s) end - %i[industry company_name website].each do |key| - value = content[key] || content[key.to_s] - body[key.to_s] = value unless value.nil? + %w[company_name company_website company_description example_email].each do |key| + given, value = field(content, key) + body[key] = value if given && !value.nil? end + # Up to 3.0.1 the SDK took the website as "website", which the API does + # not read; it is still accepted and sent as company_website. + given, website = field(content, :website) + body['company_website'] = website if given && !website.nil? && !body.key?('company_website') + warn_unknown(content, EMAIL_CONTENT_FIELDS + %w[website], 'email_content') body end @@ -375,15 +410,31 @@ def managed_sending_body(sending) raise ArgumentError, 'managed_sending must be a Hash' unless sending.is_a?(Hash) body = {} - offset = sending[:timezone_offset] || sending['timezone_offset'] - body['timezone_offset'] = in_range(offset, -11, 14, 'timezone_offset') unless offset.nil? - start = sending[:warmup_start_date] || sending['warmup_start_date'] - body['warmup_start_date'] = api_date(start, 'warmup_start_date') unless start.nil? - limit = sending[:daily_limit] || sending['daily_limit'] - body['daily_limit'] = limit unless limit.nil? + given, weekdays = field(sending, :weekdays_only) + body['weekdays_only'] = StrictBool.parse(weekdays, 'weekdays_only') if given && !weekdays.nil? + given, timezone = field(sending, :timezone) + if given && !timezone.nil? + raise ArgumentError, 'timezone must be a String, e.g. Europe/Bucharest' unless timezone.is_a?(String) + + body['timezone'] = timezone + end + given, offset = field(sending, :timezone_offset) + body['timezone_offset'] = timezone_offset(offset) if given && !offset.nil? + given, start = field(sending, :warmup_start_date) + body['warmup_start_date'] = api_date(start, 'warmup_start_date') if given && !start.nil? + warn_unknown(sending, MANAGED_SENDING_FIELDS, 'managed_sending') body end + # -11 to 14, whole or fractional hours (the docs' example sends 3.0). + def timezone_offset(value) + unless (value.is_a?(Integer) || value.is_a?(Float)) && value.between?(-11, 14) + raise ArgumentError, 'timezone_offset must be -11 to 14' + end + + value + end + # -- transport ---------------------------------------------------------- # Replaces every form of a secret in a message with ***. @@ -457,7 +508,7 @@ def json_request(method, path, params = {}, body = nil, secrets: []) response.code, (response.headers[:content_type] || '').to_s, text ), secrets ), response.code - ) + ), cause: nil # the parser's error quotes the body end end diff --git a/spec/strict_booleans_spec.rb b/spec/strict_booleans_spec.rb new file mode 100644 index 0000000..bd557c3 --- /dev/null +++ b/spec/strict_booleans_spec.rb @@ -0,0 +1,204 @@ +# frozen_string_literal: true + +require 'spec_helper' +require 'webmock/rspec' + +# rubocop:disable Metrics/BlockLength +# Every boolean parameter of every public method is parsed strictly: 'false' +# is never sent as true and anything that is not a boolean raises before a +# request. The parameters are found from the methods' signatures, so a new +# boolean parameter (or a new method taking one) fails the completeness +# checks until it is added to the sweep. +module StrictBooleanSweep + FILE = 'spec/fixtures/priority3_finder.csv' + DONE = 'https://example.com/d' + + # Parameter names that take a boolean. + BOOLEAN_NAMES = %w[activity_data verify_plus domain_info greylist_processing has_header_row allow_phase_2 + remove_duplicates ignore_conflict auto_enable].freeze + + # Client-side switches that choose how a request is sent, not API fields. + CLIENT_SWITCHES = %w[use_post].freeze + + # Every other parameter name of the public methods. + OTHER_NAMES = %w[api_key body bucket c_from callback_url click_pct company_name dkim_selector domain + domain_column email email_address_column emails end_date engagement_rule_id export_bucket + export_path file_id file_name filepath first_name first_name_column from_address + full_name_column gender_column important_pct io ip_address ip_addresses last_name + last_name_column limit middle_name middle_name_column name new_from_address offset + old_from_address onboarding_model options opts password port reply_pct return_url rule + rule_id search search_from server start_date status_id target test_id timeout username value + webhook_url].freeze + + # The booleans a method takes through **options, which its signature does + # not name. Every method with a ** parameter is listed, with [] when none. + KEYREST_BOOLEANS = { + validate_file_send_stream: %w[has_header_row allow_phase_2], + scoring_file_send_stream: %w[has_header_row], + validate_s3_file: %w[remove_duplicates], + score_s3_file: %w[remove_duplicates], + email_finder_s3_file: %w[remove_duplicates], + domain_search_s3_file: %w[remove_duplicates], + validate_sftp_file: %w[remove_duplicates], + score_sftp_file: %w[remove_duplicates], + email_finder_sftp_file: %w[remove_duplicates], + domain_search_sftp_file: %w[remove_duplicates], + create_inbox_placement_test: [], + list_inbox_placement_tests: [], + validate_file_get: [], + scoring_file_get: [], + 'Warmup#add_sending_account': %w[ignore_conflict] + }.freeze + + def self.csv_io + StringIO.new("email\na@example.com\n") + end + + # An S3/SFTP job, whose has_header_row is positional. + def self.positional(method) + lambda { |o| + Zerobounce.public_send(method, 'f.csv', o.fetch(:has_header_row, true), return_url: DONE, + **o.except(:has_header_row)) + } + end + + # Each method with a boolean parameter, called with +o+ (the parameter + # under test) merged into otherwise valid arguments. + CALLS = { + validate: ->(o) { Zerobounce.validate('a@example.com', **o) }, + validate_batch: ->(o) { Zerobounce.validate_batch(['a@example.com'], **o) }, + validate_file_send: ->(o) { Zerobounce.validate_file_send(FILE, **o) }, + validate_file_send_stream: ->(o) { Zerobounce.validate_file_send_stream(csv_io, 'f.csv', **o) }, + scoring_file_send: ->(o) { Zerobounce.scoring_file_send(FILE, **o) }, + scoring_file_send_stream: ->(o) { Zerobounce.scoring_file_send_stream(csv_io, 'f.csv', **o) }, + send_email_finder_file: lambda { |o| + Zerobounce.send_email_finder_file(FILE, domain_column: 1, first_name_column: 2, **o) + }, + send_domain_search_file: ->(o) { Zerobounce.send_domain_search_file(FILE, domain_column: 1, **o) }, + validate_s3_file: ->(o) { Zerobounce.validate_s3_file(file_name: 'f.csv', return_url: DONE, **o) }, + score_s3_file: ->(o) { Zerobounce.score_s3_file(file_name: 'f.csv', return_url: DONE, **o) }, + email_finder_s3_file: positional(:email_finder_s3_file), + domain_search_s3_file: positional(:domain_search_s3_file), + validate_sftp_file: positional(:validate_sftp_file), + score_sftp_file: positional(:score_sftp_file), + email_finder_sftp_file: positional(:email_finder_sftp_file), + domain_search_sftp_file: positional(:domain_search_sftp_file), + 'Warmup#add_sending_account': lambda { |o| + Zerobounce::Warmup.new('warmup-key').add_sending_account('a@b.com', 'self_managed', engagement_rule_id: 0, **o) + }, + 'Warmup#update_sending_account': lambda { |o| + Zerobounce::Warmup.new('warmup-key').update_sending_account('a@b.com', 1, 4, o.fetch(:auto_enable)) + } + }.freeze + + # [method, parameter names] for every public method of the client and the + # Warmup client. + def self.public_methods_with_parameters + client = Zerobounce.singleton_methods.map { |m| [m, Zerobounce.method(m).parameters] } + warmup = Zerobounce::Warmup.public_instance_methods(false).map do |m| + [:"Warmup##{m}", Zerobounce::Warmup.instance_method(m).parameters] + end + client + warmup + end + + # The boolean parameters each public method takes, from its signature and + # KEYREST_BOOLEANS. + def self.booleans_by_method + found = public_methods_with_parameters.to_h do |method, parameters| + named = parameters.map { |_, name| name.to_s } & BOOLEAN_NAMES + [method, (named + KEYREST_BOOLEANS.fetch(method, [])).uniq] + end + found.reject { |_, names| names.empty? } + end + + # What a request sent for +name+: the query, a JSON body member, or a + # multipart or form field, as a string ('true'/'false'); nil when not sent. + def self.sent_value(request, name) + query = URI.decode_www_form(request.uri.query.to_s).to_h + return query[name] if query.key?(name) + + body_value(request.body.to_s, name) + end + + def self.body_value(body, name) + if body.start_with?('{') + json = JSON.parse(body) + return json.key?(name) ? json[name].to_s : nil + end + multipart = body.match(/name="#{Regexp.escape(name)}"\r\n(?:[^\r\n]+\r\n)*\r\n([^\r\n]*)/) + multipart ? multipart[1] : URI.decode_www_form(body).to_h[name] + rescue ArgumentError, JSON::ParserError + nil + end +end + +describe 'Strict boolean parameters' do + around do |example| + saved = Zerobounce.configuration + Zerobounce.configuration = Zerobounce::Configuration.new + Zerobounce.configure { |c| c.apikey = 'bool-key' } + example.run + ensure + Zerobounce.configuration = saved + end + + before do + stub_request(:any, /.*/) + .to_return(status: 200, body: '{"success":true}', headers: { 'Content-Type' => 'application/json' }) + end + + def last_request + WebMock::RequestRegistry.instance.requested_signatures.hash.keys.last + end + + it 'classifies every parameter name of every public method' do + names = StrictBooleanSweep.public_methods_with_parameters.flat_map { |_, ps| ps.map { |_, n| n.to_s } } + known = StrictBooleanSweep::BOOLEAN_NAMES + StrictBooleanSweep::CLIENT_SWITCHES + StrictBooleanSweep::OTHER_NAMES + expect(names.uniq.reject(&:empty?) - known).to eq([]) + end + + it 'lists the booleans of every method that takes **options' do + with_keyrest = StrictBooleanSweep.public_methods_with_parameters + .select { |_, ps| ps.any? { |type, _| type == :keyrest } }.map(&:first) + expect(with_keyrest.sort - StrictBooleanSweep::KEYREST_BOOLEANS.keys).to eq([]) + end + + it 'knows every name the library parses as a strict boolean' do + source = Dir['lib/**/*.rb'].map { |f| File.read(f) }.join("\n") + parsed = source.scan(/(?:StrictBool\.parse|__strict_bool__|__wire_bool__)\([^,]+,\s*'(\w+)'\)/).flatten.uniq + expect(parsed).not_to be_empty + # weekdays_only sits inside add_sending_account's managed_sending Hash and + # has its own spec in warmup_spec.rb. + expect(parsed - StrictBooleanSweep::BOOLEAN_NAMES - %w[weekdays_only]).to eq([]) + end + + it 'sweeps every method that takes a boolean' do + expect(StrictBooleanSweep.booleans_by_method.keys.sort).to eq(StrictBooleanSweep::CALLS.keys.sort) + end + + StrictBooleanSweep::CALLS.each do |method, call| + describe method.to_s do + it "rejects 'junk' and never sends 'false' as true, for each boolean" do + names = StrictBooleanSweep.booleans_by_method.fetch(method) + names.each do |name| + WebMock.reset_executed_requests! + expect { call.call(name.to_sym => 'junk') } + .to raise_error(ArgumentError, /#{name}/), "#{method} took #{name}: 'junk'" + expect(a_request(:any, /.*/)).not_to have_been_made, "#{method} sent #{name}: 'junk'" + + WebMock.reset_executed_requests! + begin + call.call(name.to_sym => 'false') + rescue ArgumentError => e + # A parameter that takes only true/false may reject the string. + expect(e.message).to match(/#{name}/) + next + end + sent = StrictBooleanSweep.sent_value(last_request, name) + expect(sent).to eq('false'), "#{method} sent #{name}: 'false' as #{sent.inspect}" + end + end + end + end +end +# rubocop:enable Metrics/BlockLength diff --git a/spec/transport_guards_spec.rb b/spec/transport_guards_spec.rb index beb9f25..ce5fc71 100644 --- a/spec/transport_guards_spec.rb +++ b/spec/transport_guards_spec.rb @@ -373,5 +373,83 @@ def expect_error_on_ok(&call) end end end + + # A response body that quotes the key (an API message naming the key, a + # proxy echoing the request URL, an HTML title) must not hand it to the + # caller, whatever the status: every error the SDK raises from a body is + # redacted, in the key's raw and URL-encoded forms. + describe 'a response body that quotes the API key' do + echo_key = 'echo+key/42' + encoded = 'echo%2Bkey%2F42' + json = 'application/json' + batch_all = %({"email_batch":[],"errors":[{"email_address":"all","error":"Invalid API key #{echo_key}"}]}) + bodies = { + '200 {"error"}' => [200, json, %({"error":"Invalid API key #{echo_key}"})], + '200 {"success":false}' => [200, json, %({"success":false,"message":"Invalid API key #{echo_key}"})], + '200 batch "all" error' => [200, json, batch_all], + '200 HTML title' => [200, 'text/html', "Denied #{echo_key}"], + '200 JSON cut off' => [200, json, %({"error":"Invalid API key #{echo_key}")], + '400 text quoting the URL' => [400, 'text/plain', "Bad request: https://first.example/v2/x?api_key=#{encoded}"], + '400 {"error"}' => [400, json, %({"error":"Invalid API key #{echo_key}"})] + }.freeze + + def stub_body(status, type, body) + stub_request(:any, %r{\Ahttps://first\.example/}) + .to_return(status: status, body: body, headers: { 'Content-Type' => type }) + end + + # Everything a caller or an uncaught-exception printer reads off the + # error, down the whole #cause chain. + def visible_text(error) + parts = [] + while error + parts << error.message << error.inspect << error.full_message(highlight: false) + error = error.cause + end + parts.join("\n") + end + + def expect_redacted(label, key, encoded_key) + yield + rescue StandardError => e + text = visible_text(e) + expect(text).not_to include(key), "#{label}: #{e.class}: #{text}" + expect(text).not_to include(encoded_key), "#{label}: #{e.class}: #{text}" + end + + TransportSweep::CALLS.each do |name, call| + it "keeps the key out of every error from #{name}" do + TransportSweep.configure(echo_key, 'https://first.example') + bodies.each do |label, (status, type, body)| + WebMock.reset! + stub_body(status, type, body) + expect_redacted(label, echo_key, encoded) { call.call } + end + end + end + + TransportSweep::WARMUP_CALLS.each do |name, call| + it "keeps the key out of every error from Warmup##{name}" do + bodies.each do |label, (status, type, body)| + WebMock.reset! + stub_body(status, type, body) + expect_redacted(label, echo_key, encoded) { call.call(TransportSweep.warmup(echo_key, 'https://first.example')) } + end + end + end + + # The sweep above only checks the errors that are raised; these bodies + # are errors on every call of the client, so each must raise. + it 'raises for each error body on every call of the client' do + TransportSweep.configure(echo_key, 'https://first.example') + bodies.except('200 batch "all" error').each do |label, (status, type, body)| + TransportSweep::CALLS.each do |name, call| + WebMock.reset! + stub_body(status, type, body) + expect { call.call }.to raise_error(StandardError), "#{name} returned for #{label}" + end + end + end + end end # rubocop:enable Metrics/BlockLength, Metrics/ModuleLength diff --git a/spec/warmup_spec.rb b/spec/warmup_spec.rb index 71b5974..d698508 100644 --- a/spec/warmup_spec.rb +++ b/spec/warmup_spec.rb @@ -252,6 +252,62 @@ def stub_ok(body = '{"ok":true}', status: 200, content_type: 'application/json') expect(body['managed_sending']['warmup_start_date']).to eq('2026-03-04') end + it 'sends the documented zb_managed fields, exactly' do + stub_ok + warmup.add_sending_account( + 'a@b.com', 'zb_managed', + email_content: { company_name: 'Acme', company_website: 'https://acme.example', + company_description: 'B2B email tools', types_of_emails: ['marketing'], + example_email: 'Hi, short intro to Acme.' }, + managed_sending: { weekdays_only: true, timezone: 'Europe/Bucharest', timezone_offset: 3.0, + warmup_start_date: '2026-09-15' } + ) + expect(last_json).to eq( + 'from_address' => 'a@b.com', 'onboarding_model' => 'zb_managed', + 'email_content' => { 'company_name' => 'Acme', 'company_website' => 'https://acme.example', + 'company_description' => 'B2B email tools', 'types_of_emails' => ['marketing'], + 'example_email' => 'Hi, short intro to Acme.' }, + 'managed_sending' => { 'weekdays_only' => true, 'timezone' => 'Europe/Bucharest', + 'timezone_offset' => 3.0, 'warmup_start_date' => '2026-09-15' } + ) + + # String keys work too, and a false weekdays_only is sent as false. + warmup.add_sending_account('a@b.com', 'zb_managed', managed_sending: { 'weekdays_only' => false }) + expect(last_json['managed_sending']).to eq('weekdays_only' => false) + end + + it 'sends the old website key as company_website and leaves out what the API does not read' do + stub_ok + expect(warmup).to receive(:warn).with(/email_content industry is not an API field.*company_website/) + expect(warmup).to receive(:warn).with(/managed_sending daily_limit is not an API field.*weekdays_only/) + warmup.add_sending_account( + 'a@b.com', 'zb_managed', + email_content: { industry: 'SaaS', company_name: 'Acme', website: 'https://acme.example' }, + managed_sending: { daily_limit: 50, timezone_offset: -5 } + ) + expect(last_json['email_content']).to eq('company_name' => 'Acme', 'company_website' => 'https://acme.example') + expect(last_json['managed_sending']).to eq('timezone_offset' => -5) + end + + it 'checks the types of the zb_managed fields' do + stub_ok + add = ->(sending) { warmup.add_sending_account('a@b.com', 'zb_managed', managed_sending: sending) } + ['junk', 'yes', 2, ''].each do |bad| + expect { add.call(weekdays_only: bad) }.to raise_error(ArgumentError, /weekdays_only/) + end + expect { add.call(timezone: 3) }.to raise_error(ArgumentError, /timezone/) + expect { add.call(timezone_offset: '3') }.to raise_error(ArgumentError, /timezone_offset/) + expect { add.call(timezone_offset: 14.5) }.to raise_error(ArgumentError, /timezone_offset/) + expect(request_count).to eq(0) + + [['false', false], ['TRUE', true], [0, false], [1, true]].each do |value, sent| + WebMock.reset! + stub_ok + add.call(weekdays_only: value) + expect(last_json['managed_sending']['weekdays_only']).to be(sent) + end + end + it 'checks the from-address search and sends paging as strings' do expect { warmup.list_from_addresses(search_from: 'bad search!') }.to raise_error(ArgumentError) expect { warmup.list_from_addresses(offset: -1) }.to raise_error(ArgumentError)