Skip to content

Commit 4031d98

Browse files
authored
Merge pull request #3273 from basecamp/import-fail-cleanly-on-bad-data
Fail an import cleanly when its data doesn't fit a column
2 parents 55634ed + f0a2b36 commit 4031d98

4 files changed

Lines changed: 134 additions & 3 deletions

File tree

‎app/jobs/account/data_import_job.rb‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ class Account::DataImportJob < ApplicationJob
88
Account::Import::InsufficientStorageSpaceError ].freeze
99

1010
queue_as :backend
11-
discard_on(*TERMINAL_ERRORS)
11+
discard_on(*TERMINAL_ERRORS, report: true)
1212

1313
def perform(import)
1414
step :check do |step|

‎app/models/account/data_transfer/record_set.rb‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@ class Account::DataTransfer::RecordSet
22
class IntegrityError < StandardError; end
33
class ConflictError < IntegrityError; end
44

5+
# Values a real export can't produce. Named rather than rescuing StatementInvalid,
6+
# which a failover raises too, and those imports should retry.
7+
INVALID_DATA_ERRORS = [ ActiveRecord::ValueTooLong, ActiveRecord::RangeError, ActiveModel::RangeError,
8+
ActiveRecord::NotNullViolation, ActiveRecord::CheckViolation, ActiveRecord::RecordInvalid,
9+
ActiveRecord::SerializationTypeMismatch ].freeze
10+
511
IMPORT_BATCH_SIZE = 100
612

713
# A batch holds every record it reads until it inserts them, so a batch also
@@ -47,6 +53,8 @@ def import(from:, start: nil, callback: nil)
4753
end
4854
rescue ActiveRecord::RecordNotUnique => e
4955
raise ConflictError, "#{model} import violated a uniqueness constraint: #{e.message}"
56+
rescue *INVALID_DATA_ERRORS => e
57+
raise IntegrityError, "#{model} import has invalid data: #{e.message}"
5058
end
5159

5260
def check(from:, start: nil, callback: nil)
@@ -217,8 +225,10 @@ def skip_to(file_list, last_id)
217225
end
218226

219227
def load(file_path)
220-
JSON.parse(zip.read(file_path))
221-
rescue ArgumentError => e
228+
JSON.parse(zip.read(file_path)).tap do |data|
229+
raise IntegrityError, "#{file_path} isn't a JSON object" unless data.is_a?(Hash)
230+
end
231+
rescue ArgumentError, JSON::ParserError => e
222232
raise IntegrityError, e.message
223233
end
224234

‎test/jobs/account/data_import_job_test.rb‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,18 @@ class Account::DataImportJobTest < ActiveJob::TestCase
105105
end
106106
end
107107

108+
test "reports a discarded import once instead of retrying it" do
109+
import = Account::Import.create!(identity: identities(:david), account: Account.create!(name: "Import Test"))
110+
Account::Import.any_instance.stubs(:process).raises(Account::DataTransfer::RecordSet::IntegrityError, "users import has a value its column can't hold")
111+
Account::Import.any_instance.stubs(:check)
112+
113+
assert_error_reported(Account::DataTransfer::RecordSet::IntegrityError) do
114+
assert_no_enqueued_jobs only: Account::DataImportJob do
115+
Account::DataImportJob.perform_now(import)
116+
end
117+
end
118+
end
119+
108120
private
109121
# Simulates a hand-edited export: an extra board_publications record with a
110122
# fresh id but a key copied from another record in the same export.

‎test/models/account/data_transfer/record_set_test.rb‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,97 @@ def import_batch(files)
229229
assert Board::Publication.exists?(id: publication_data["id"], key: publication_data["key"])
230230
end
231231

232+
test "import fails as invalid when a crafted export's value doesn't fit its serialized column" do
233+
webhook_data = {
234+
"id" => ActiveRecord::Type::Uuid.generate,
235+
"account_id" => ActiveRecord::Type::Uuid.generate,
236+
"board_id" => ActiveRecord::Type::Uuid.generate,
237+
"name" => "Pre-encoded actions",
238+
"url" => "https://example.com/hook",
239+
"signing_secret" => "secret",
240+
"subscribed_actions" => [ "card_published" ].to_json,
241+
"active" => true,
242+
"created_at" => Time.current.iso8601,
243+
"updated_at" => Time.current.iso8601
244+
}
245+
246+
error = assert_raises(Account::DataTransfer::RecordSet::IntegrityError) do
247+
webhook_record_set.import(from: build_reader(dir: "webhooks", data: webhook_data))
248+
end
249+
250+
assert_match(/invalid data/i, error.message)
251+
assert_not Webhook.exists?(id: webhook_data["id"])
252+
end
253+
254+
test "import fails as invalid when a value is too long for its column" do
255+
error = assert_raises(Account::DataTransfer::RecordSet::IntegrityError) do
256+
import_account(build_account_data("name" => "a" * 256))
257+
end
258+
259+
assert_match(/invalid data/i, error.message)
260+
end
261+
262+
test "import fails as invalid when a count is out of range for its column" do
263+
error = assert_raises(Account::DataTransfer::RecordSet::IntegrityError) do
264+
import_account(build_account_data("cards_count" => 2**63))
265+
end
266+
267+
assert_match(/invalid data/i, error.message)
268+
end
269+
270+
test "import fails as invalid when a user's email address doesn't validate" do
271+
user_data = { "id" => ActiveRecord::Type::Uuid.generate, "email_address" => "nope", "name" => "Crafted", "role" => "member",
272+
"active" => true, "verified_at" => nil, "created_at" => Time.current.iso8601, "updated_at" => Time.current.iso8601 }
273+
274+
error = assert_raises(Account::DataTransfer::RecordSet::IntegrityError) do
275+
Account::DataTransfer::UserRecordSet.new(importing_account).import(from: build_reader(dir: "users", data: user_data))
276+
end
277+
278+
assert_match(/invalid data/i, error.message)
279+
end
280+
281+
test "import leaves transient database errors to retry" do
282+
Board::Publication.stubs(:insert_all!).raises(ActiveRecord::Deadlocked)
283+
284+
assert_raises(ActiveRecord::Deadlocked) do
285+
publication_record_set.import(from: build_reader(dir: "board_publications", data: build_publication_data(key: SecureRandom.base58(24))))
286+
end
287+
end
288+
289+
test "check fails as invalid on a record that isn't JSON" do
290+
tempfile = Tempfile.new([ "import_test", ".zip" ])
291+
tempfile.binmode
292+
writer = ZipFile::Writer.new(tempfile)
293+
writer.add_file("data/board_publications/#{ActiveRecord::Type::Uuid.generate}.json", "/etc/passwd")
294+
writer.close
295+
tempfile.rewind
296+
297+
assert_raises(Account::DataTransfer::RecordSet::IntegrityError) do
298+
publication_record_set.check(from: ZipFile::Reader.new(tempfile))
299+
end
300+
ensure
301+
tempfile&.close
302+
tempfile&.unlink
303+
end
304+
305+
test "check fails as invalid on a record that isn't a JSON object" do
306+
[ "[1,2]", "null", "42" ].each do |body|
307+
tempfile = Tempfile.new([ "import_test", ".zip" ])
308+
tempfile.binmode
309+
writer = ZipFile::Writer.new(tempfile)
310+
writer.add_file("data/board_publications/#{ActiveRecord::Type::Uuid.generate}.json", body)
311+
writer.close
312+
tempfile.rewind
313+
314+
assert_raises(Account::DataTransfer::RecordSet::IntegrityError, body) do
315+
publication_record_set.check(from: ZipFile::Reader.new(tempfile))
316+
end
317+
ensure
318+
tempfile&.close
319+
tempfile&.unlink
320+
end
321+
end
322+
232323
test "a webhook exported before attribution existed checks and imports without a creator" do
233324
webhook_data = {
234325
"id" => ActiveRecord::Type::Uuid.generate,
@@ -296,6 +387,24 @@ def exported_user_data
296387
}
297388
end
298389

390+
def build_account_data(overrides)
391+
{ "name" => "Imported", "join_code" => { "code" => "ABCD-EFGH-IJKL", "usage_count" => 0, "usage_limit" => 10 } }.merge(overrides)
392+
end
393+
394+
def import_account(account_data)
395+
tempfile = Tempfile.new([ "import_test", ".zip" ])
396+
tempfile.binmode
397+
writer = ZipFile::Writer.new(tempfile)
398+
writer.add_file("data/account.json", account_data.to_json)
399+
writer.close
400+
tempfile.rewind
401+
402+
Account::DataTransfer::AccountRecordSet.new(importing_account).import(from: ZipFile::Reader.new(tempfile))
403+
ensure
404+
tempfile&.close
405+
tempfile&.unlink
406+
end
407+
299408
def build_reader(dir:, data:, users: [])
300409
tempfile = Tempfile.new([ "import_test", ".zip" ])
301410
tempfile.binmode

0 commit comments

Comments
 (0)