bulkrax 10.0.0 → 10.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/app/controllers/bulkrax/importers_controller.rb +59 -18
- data/app/controllers/concerns/bulkrax/importer_file_handler.rb +54 -8
- data/app/errors/bulkrax/unsafe_cloud_source_error.rb +11 -0
- data/app/errors/bulkrax/unsafe_path_error.rb +8 -0
- data/app/jobs/bulkrax/download_cloud_file_job.rb +156 -21
- data/app/parsers/bulkrax/application_parser.rb +13 -11
- data/app/parsers/bulkrax/bagit_parser.rb +18 -4
- data/app/parsers/bulkrax/csv_parser.rb +46 -15
- data/app/services/bulkrax/cloud_source_validator.rb +123 -0
- data/app/services/bulkrax/csv_template/model_loader.rb +2 -16
- data/app/services/bulkrax/factory_class_finder.rb +33 -18
- data/app/services/bulkrax/safe_path.rb +129 -0
- data/config/locales/bulkrax.en.yml +2 -0
- data/lib/bulkrax/version.rb +1 -1
- data/lib/bulkrax.rb +1 -0
- metadata +30 -3
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 45e75b95be0637ab412d6126ad0e975935a69be010b2bcc405e0ab31d6fb799c
|
|
4
|
+
data.tar.gz: f66ef6f1714b54acc7650d101128d2cd3bf276027cd57c67a8ae30e6d0587999
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 23458ed58b9d0fed52e97b24cc310ea3abd6fb3b9b1506d8dfacf3c8faee90d7d068c9fe74bdcf14b6de2484440a4e12dff53e886bff38343070d5aecd3097e3
|
|
7
|
+
data.tar.gz: 664e60be653705c3192f86235b90dda9f8aa0318bf9fe3b02a1544a95fd4ee8566255ea834d32a3fddf9eba5dbefa47d61d0cb50bf7c9f905a47e4e703a11ec7
|
|
@@ -101,7 +101,6 @@ module Bulkrax
|
|
|
101
101
|
# rubocop:disable Metrics/MethodLength
|
|
102
102
|
# rubocop:disable Metrics/AbcSize
|
|
103
103
|
def create
|
|
104
|
-
# rubocop:disable Style/IfInsideElse
|
|
105
104
|
if api_request?
|
|
106
105
|
return return_json_response unless valid_create_params?
|
|
107
106
|
# authenticate_and_authorize! doesn't build for API requests; build it here
|
|
@@ -117,8 +116,15 @@ module Bulkrax
|
|
|
117
116
|
# the following line is needed to handle updating remote files of a FileSet
|
|
118
117
|
# on a new import otherwise it only gets updated during the update path
|
|
119
118
|
@importer.parser_fields['update_files'] = true if params[:commit] == 'Create and Import'
|
|
119
|
+
|
|
120
|
+
# Reject an unsafe cloud selection before the importer is ever
|
|
121
|
+
# persisted, rather than after save when a row would already exist.
|
|
122
|
+
preflight_cloud_files!(cloud_files)
|
|
123
|
+
|
|
120
124
|
if @importer.save
|
|
121
|
-
files_for_import(file, cloud_files, uploads)
|
|
125
|
+
return render_create_failure if files_for_import(file, cloud_files, uploads) && !@importer.save
|
|
126
|
+
dispatch_cloud_downloads!
|
|
127
|
+
|
|
122
128
|
if params[:commit] == 'Create and Import'
|
|
123
129
|
Bulkrax::ImporterJob.send(@importer.parser.perform_method, @importer.id)
|
|
124
130
|
render_request('Importer was successfully created and import has been queued.')
|
|
@@ -129,13 +135,10 @@ module Bulkrax
|
|
|
129
135
|
render_request('Importer was successfully created.')
|
|
130
136
|
end
|
|
131
137
|
else
|
|
132
|
-
|
|
133
|
-
json_response('create', :unprocessable_entity)
|
|
134
|
-
else
|
|
135
|
-
render :new
|
|
136
|
-
end
|
|
138
|
+
render_create_failure
|
|
137
139
|
end
|
|
138
|
-
|
|
140
|
+
rescue Bulkrax::UnsafeCloudSourceError, Bulkrax::UnsafePathError => e
|
|
141
|
+
reject_unsafe_cloud_files(e)
|
|
139
142
|
end
|
|
140
143
|
# rubocop:enable Metrics/AbcSize
|
|
141
144
|
|
|
@@ -153,11 +156,19 @@ module Bulkrax
|
|
|
153
156
|
# Skipped during a continue
|
|
154
157
|
field_mapping_params if params[:importer][:parser_fields].present?
|
|
155
158
|
|
|
156
|
-
|
|
157
|
-
|
|
159
|
+
# Assign the proposed attributes in memory first, so an unsafe cloud
|
|
160
|
+
# selection is rejected before anything is persisted; the rescue
|
|
161
|
+
# below then leaves the importer's persisted attributes untouched.
|
|
162
|
+
@importer.assign_attributes(importer_params)
|
|
163
|
+
preflight_cloud_files!(cloud_files)
|
|
164
|
+
|
|
165
|
+
if @importer.save
|
|
166
|
+
return render_update_failure if files_for_import(file, cloud_files, uploads) && !@importer.save
|
|
167
|
+
return render_update_failure if params[:commit] != 'Update Importer' && !set_files_parser_fields
|
|
168
|
+
dispatch_cloud_downloads!
|
|
169
|
+
|
|
158
170
|
# do not perform the import
|
|
159
171
|
unless params[:commit] == 'Update Importer'
|
|
160
|
-
set_files_parser_fields
|
|
161
172
|
Bulkrax::ImporterJob.send(@importer.parser.perform_method, @importer.id, update_harvest)
|
|
162
173
|
end
|
|
163
174
|
if api_request?
|
|
@@ -166,12 +177,10 @@ module Bulkrax
|
|
|
166
177
|
redirect_to importers_path, notice: 'Importer was successfully updated.'
|
|
167
178
|
end
|
|
168
179
|
else
|
|
169
|
-
|
|
170
|
-
json_response('update', :unprocessable_entity, 'Something went wrong.')
|
|
171
|
-
else
|
|
172
|
-
render :edit
|
|
173
|
-
end
|
|
180
|
+
render_update_failure
|
|
174
181
|
end
|
|
182
|
+
rescue Bulkrax::UnsafeCloudSourceError, Bulkrax::UnsafePathError => e
|
|
183
|
+
reject_unsafe_cloud_files(e)
|
|
175
184
|
end
|
|
176
185
|
# rubocop:enable all
|
|
177
186
|
# rubocop:enable Metrics/MethodLength
|
|
@@ -275,7 +284,7 @@ module Bulkrax
|
|
|
275
284
|
:validate_only,
|
|
276
285
|
selected_files: {},
|
|
277
286
|
field_mapping: {},
|
|
278
|
-
parser_fields:
|
|
287
|
+
parser_fields: importable_parser_fields
|
|
279
288
|
)
|
|
280
289
|
end
|
|
281
290
|
|
|
@@ -333,6 +342,36 @@ module Bulkrax
|
|
|
333
342
|
'text/csv'
|
|
334
343
|
end
|
|
335
344
|
|
|
345
|
+
# Reports an unsafe cloud-file batch without leaking the error's class
|
|
346
|
+
# or backtrace (which could include a provider auth header) to the
|
|
347
|
+
# response; `e.message` is always one of our own static, credential-free
|
|
348
|
+
# strings (see Bulkrax::CloudSourceValidator / Bulkrax::SafePath).
|
|
349
|
+
def reject_unsafe_cloud_files(e)
|
|
350
|
+
Rails.logger.error("Bulkrax: rejected unsafe cloud file batch for importer #{@importer&.id}: #{e.class}: #{e.message}")
|
|
351
|
+
if api_request?
|
|
352
|
+
json_response('create', :unprocessable_entity, e.message)
|
|
353
|
+
else
|
|
354
|
+
flash[:error] = e.message
|
|
355
|
+
redirect_back fallback_location: bulkrax.importers_path
|
|
356
|
+
end
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
def render_create_failure
|
|
360
|
+
if api_request?
|
|
361
|
+
json_response('create', :unprocessable_entity)
|
|
362
|
+
else
|
|
363
|
+
render :new
|
|
364
|
+
end
|
|
365
|
+
end
|
|
366
|
+
|
|
367
|
+
def render_update_failure
|
|
368
|
+
if api_request?
|
|
369
|
+
json_response('update', :unprocessable_entity, 'Something went wrong.')
|
|
370
|
+
else
|
|
371
|
+
render :edit
|
|
372
|
+
end
|
|
373
|
+
end
|
|
374
|
+
|
|
336
375
|
def render_request(message, validate_only = false)
|
|
337
376
|
if api_request?
|
|
338
377
|
json_response('create', :created, message)
|
|
@@ -348,6 +387,8 @@ module Bulkrax
|
|
|
348
387
|
params[:commit] == 'Update and Harvest Updated Items'
|
|
349
388
|
end
|
|
350
389
|
|
|
390
|
+
# @return [Boolean] the result of the save, so the caller can treat a
|
|
391
|
+
# failure here like an ordinary validation failure
|
|
351
392
|
def set_files_parser_fields
|
|
352
393
|
@importer.parser_fields['update_files'] =
|
|
353
394
|
@importer.parser_fields['replace_files'] =
|
|
@@ -360,7 +401,7 @@ module Bulkrax
|
|
|
360
401
|
elsif params[:commit] == 'Remove and Rerun'
|
|
361
402
|
@importer.parser_fields['remove_and_rerun'] = true
|
|
362
403
|
elsif params[:commit] == 'Update and Harvest Updated Items'
|
|
363
|
-
return
|
|
404
|
+
return true
|
|
364
405
|
else
|
|
365
406
|
@importer.parser_fields['metadata_only'] = true
|
|
366
407
|
end
|
|
@@ -139,21 +139,38 @@ module Bulkrax
|
|
|
139
139
|
csv_by_depth[shallowest_depth]
|
|
140
140
|
end
|
|
141
141
|
|
|
142
|
-
#
|
|
142
|
+
# Validates every selected cloud-file entry — raw name and source
|
|
143
|
+
# safety — before the importer is created or updated at all. Must not
|
|
144
|
+
# touch the importer's workspace (no path_for_import, no directory
|
|
145
|
+
# creation, no download): for #create that workspace doesn't exist
|
|
146
|
+
# yet, and for #update it must not be assumed safe to touch before the
|
|
147
|
+
# proposed attributes are known to be acceptable.
|
|
148
|
+
#
|
|
149
|
+
# @param cloud_files [Hash, nil] cloud file specs from browse-everything
|
|
150
|
+
# @raise [Bulkrax::UnsafePathError, Bulkrax::UnsafeCloudSourceError] on the first unsafe entry
|
|
151
|
+
def preflight_cloud_files!(cloud_files)
|
|
152
|
+
return if cloud_files.blank?
|
|
153
|
+
|
|
154
|
+
cloud_files.values.each { |file| Bulkrax::CloudSourceValidator.preflight!(file) }
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# Assigns files/cloud selections onto the importer record's in-memory
|
|
158
|
+
# parser fields, but does not save: the caller (ImportersController)
|
|
159
|
+
# owns the second save, so it can check its result and avoid rendering
|
|
160
|
+
# success or enqueueing an import on failure.
|
|
161
|
+
#
|
|
143
162
|
# @param file [ActionDispatch::Http::UploadedFile, nil] a directly uploaded file
|
|
144
163
|
# @param cloud_files [Hash, nil] cloud file paths from browse-everything
|
|
145
164
|
# @param uploads [ActiveRecord::Relation, Array, nil] Hyrax::UploadedFile records
|
|
165
|
+
# @return [Boolean] true if any parser field was touched and a second save is needed
|
|
146
166
|
def files_for_import(file, cloud_files, uploads)
|
|
147
|
-
|
|
167
|
+
@cloud_download_plan = nil
|
|
168
|
+
return false if file.blank? && cloud_files.blank? && uploads.blank?
|
|
148
169
|
|
|
149
170
|
@importer[:parser_fields]['import_file_path'] = @importer.parser.write_import_file(file) if file.present?
|
|
150
171
|
if cloud_files.present?
|
|
151
172
|
@importer[:parser_fields]['cloud_file_paths'] = cloud_files
|
|
152
|
-
|
|
153
|
-
# For CSV, we expect only file uploads, so we won't get the file_path back
|
|
154
|
-
# and we expect the import_file_path to be set already
|
|
155
|
-
target = @importer.parser.retrieve_cloud_files(cloud_files, @importer)
|
|
156
|
-
@importer[:parser_fields]['import_file_path'] = target if target.present?
|
|
173
|
+
assign_cloud_file_paths(cloud_files)
|
|
157
174
|
end
|
|
158
175
|
|
|
159
176
|
if uploads.present?
|
|
@@ -162,7 +179,36 @@ module Bulkrax
|
|
|
162
179
|
end
|
|
163
180
|
end
|
|
164
181
|
|
|
165
|
-
|
|
182
|
+
true
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
# For a parser that separates planning from dispatch (currently only
|
|
186
|
+
# CsvParser), resolves and validates the whole batch and records the
|
|
187
|
+
# target paths, deferring enqueue until {#dispatch_cloud_downloads!} is
|
|
188
|
+
# called after the controller persists those paths. Other parsers
|
|
189
|
+
# (e.g. BagitParser) already complete cloud retrieval synchronously
|
|
190
|
+
# and return the resolved path directly, so there's nothing left to
|
|
191
|
+
# dispatch.
|
|
192
|
+
def assign_cloud_file_paths(cloud_files)
|
|
193
|
+
parser = @importer.parser
|
|
194
|
+
if parser.respond_to?(:plan_cloud_files)
|
|
195
|
+
@cloud_download_plan = parser.plan_cloud_files(cloud_files)
|
|
196
|
+
@importer[:parser_fields]['original_file_paths'] =
|
|
197
|
+
@cloud_download_plan.map { |_file, _relative_filename, target_file| target_file }
|
|
198
|
+
else
|
|
199
|
+
target = parser.retrieve_cloud_files(cloud_files, @importer)
|
|
200
|
+
@importer[:parser_fields]['import_file_path'] = target if target.present?
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
|
|
204
|
+
# Dispatches a plan prepared by {#assign_cloud_file_paths}, if any.
|
|
205
|
+
# Called by the controller only after it has successfully persisted
|
|
206
|
+
# the resolved paths, so a download is never enqueued for a path the
|
|
207
|
+
# importer doesn't actually have on record.
|
|
208
|
+
def dispatch_cloud_downloads!
|
|
209
|
+
return if @cloud_download_plan.blank?
|
|
210
|
+
|
|
211
|
+
@importer.parser.dispatch_cloud_files!(@cloud_download_plan, @importer)
|
|
166
212
|
end
|
|
167
213
|
|
|
168
214
|
def write_files(files)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bulkrax
|
|
4
|
+
# Raised by {Bulkrax::CloudSourceValidator} when a cloud-file source
|
|
5
|
+
# (the `url` a user selected via browse-everything, or supplied directly
|
|
6
|
+
# in importer params) can't be safely downloaded: a scheme other than
|
|
7
|
+
# `file`/`http`/`https`, a `file:` source outside the configured
|
|
8
|
+
# filesystem-provider root, or an HTTP(S) source that resolves to a
|
|
9
|
+
# private, loopback, or link-local/metadata address.
|
|
10
|
+
class UnsafeCloudSourceError < StandardError; end
|
|
11
|
+
end
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bulkrax
|
|
4
|
+
# Raised by {Bulkrax::SafePath} when a path would escape its configured
|
|
5
|
+
# root, whether that root is a ZIP extraction directory, an importer's
|
|
6
|
+
# trusted workspace, or a configured filesystem-provider home.
|
|
7
|
+
class UnsafePathError < StandardError; end
|
|
8
|
+
end
|
|
@@ -1,31 +1,166 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
|
+
|
|
2
3
|
module Bulkrax
|
|
3
4
|
class DownloadCloudFileJob < ApplicationJob
|
|
4
5
|
queue_as Bulkrax.config.ingest_queue_name
|
|
5
6
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
#
|
|
9
|
-
#
|
|
7
|
+
# Retrieve a cloud file and write it to the importer's workspace.
|
|
8
|
+
#
|
|
9
|
+
# `importer_id:` and `relative_filename:` are required keywords: the
|
|
10
|
+
# destination is always recomputed here, confined to this importer's
|
|
11
|
+
# own workspace, rather than trusted from a serialized job argument.
|
|
12
|
+
# `target_file` is a deprecated positional placeholder, kept only so
|
|
13
|
+
# that a pre-upgrade call shape (`file`, `target_file`) still binds
|
|
14
|
+
# without Ruby raising its own ArgumentError — it is never read, even
|
|
15
|
+
# when supplied alongside otherwise-valid keywords, so it can't be
|
|
16
|
+
# used to redirect the destination. A call made this way is missing
|
|
17
|
+
# the required keywords, so it raises below rather than running.
|
|
18
|
+
#
|
|
19
|
+
# Note: if using the file system provider, the mounted directory in
|
|
10
20
|
# browse_everything MUST be shared by web and worker servers
|
|
11
|
-
def perform(file, target_file)
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
21
|
+
def perform(file, target_file = nil, importer_id: nil, relative_filename: nil)
|
|
22
|
+
raise Bulkrax::UnsafePathError, I18n.t('bulkrax.importer.browse_everything.errors.missing_destination_context') if importer_id.blank? || relative_filename.blank?
|
|
23
|
+
|
|
24
|
+
# `file` and `relative_filename` are independent arguments and may
|
|
25
|
+
# not agree (a tampered or replayed job call could supply either
|
|
26
|
+
# one separately) — check the raw file_name directly rather than
|
|
27
|
+
# assuming it was already validated by whatever enqueued this job.
|
|
28
|
+
Bulkrax::SafePath.reject_unsafe_entry!(file['file_name'])
|
|
29
|
+
|
|
30
|
+
importer = Bulkrax::Importer.find(importer_id)
|
|
31
|
+
target_file = Bulkrax::SafePath.confine!(importer.parser.path_for_import, relative_filename, require_file: true)
|
|
32
|
+
|
|
33
|
+
# Re-validate the source here too: this job may run on a different
|
|
34
|
+
# process/host than the one that enqueued it, and could be invoked
|
|
35
|
+
# directly with a tampered or stale `file` argument.
|
|
36
|
+
Bulkrax::CloudSourceValidator.validate!(file)
|
|
37
|
+
|
|
38
|
+
download(file, target_file)
|
|
39
|
+
Rails.logger.info "Bulkrax: cloud file download complete for #{file['file_name']}"
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
private
|
|
43
|
+
|
|
44
|
+
# Downloads through a temp file in the *same* directory as
|
|
45
|
+
# `target_file` (so the final move is same-filesystem and atomic),
|
|
46
|
+
# named with a random suffix rather than anything derived from
|
|
47
|
+
# caller-controlled input, and removed on any failure. This means a
|
|
48
|
+
# failed or non-success download can never truncate or corrupt an
|
|
49
|
+
# already-good destination file from a previous successful import.
|
|
50
|
+
def download(file, target_file)
|
|
51
|
+
temp_file = "#{target_file}.#{SecureRandom.hex(8)}.part"
|
|
52
|
+
uri = Addressable::URI.parse(file['url'].to_s)
|
|
53
|
+
if uri.scheme == 'file'
|
|
54
|
+
download_file_source(uri, temp_file)
|
|
55
|
+
else
|
|
56
|
+
download_http_source(file, URI.parse(file['url'].to_s), temp_file)
|
|
57
|
+
end
|
|
58
|
+
FileUtils.mv(temp_file, target_file)
|
|
59
|
+
ensure
|
|
60
|
+
FileUtils.rm_f(temp_file) if temp_file && File.exist?(temp_file)
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# The source was already confined to the configured filesystem
|
|
64
|
+
# provider's root by {Bulkrax::CloudSourceValidator}.
|
|
65
|
+
def download_file_source(uri, temp_file)
|
|
66
|
+
source_path = URI::DEFAULT_PARSER.unescape(uri.path.to_s)
|
|
67
|
+
IO.copy_stream(source_path, temp_file)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Resolved, IP-pinned, redirect-free, and streamed straight to disk in
|
|
71
|
+
# bounded-size chunks — rather than handing the URL back to a transport
|
|
72
|
+
# (browse-everything's Retriever) that re-resolves the hostname with no
|
|
73
|
+
# SSRF protection at all. This is a *separate* connection from the one
|
|
74
|
+
# {Bulkrax::CloudSourceValidator}'s HEAD check made; each independently
|
|
75
|
+
# applies the same validation at its own connection time, so there is
|
|
76
|
+
# no single "pinned connection" shared between validation and download.
|
|
77
|
+
#
|
|
78
|
+
# ssrf_filter 1.0.8's public `get`/`head` API has no response-streaming
|
|
79
|
+
# hook: `fetch_once` calls `Net::HTTP#request` with no block, which
|
|
80
|
+
# reads the entire response body into memory before returning; the
|
|
81
|
+
# block `get`/`head` accept is for customizing the *outgoing* request,
|
|
82
|
+
# not consuming the response. So we can't use `SsrfFilter.get` here
|
|
83
|
+
# without buffering the whole remote file in memory first.
|
|
84
|
+
#
|
|
85
|
+
# Reuse ssrf_filter's resolver and IP policy, then pin the validated
|
|
86
|
+
# address with Net::HTTP#ipaddr=. Keeping the original hostname on
|
|
87
|
+
# the HTTP connection preserves native TLS SNI and certificate
|
|
88
|
+
# verification without relying on ssrf_filter's TLS monkeypatches.
|
|
89
|
+
def download_http_source(file, uri, temp_file)
|
|
90
|
+
headers = Bulkrax::CloudSourceValidator.request_headers(file)
|
|
91
|
+
stream_download(uri, headers) { |response| handle_response(file, response, temp_file) }
|
|
92
|
+
rescue SsrfFilter::Error
|
|
93
|
+
# The validator's own HEAD check already ran, but DNS can change
|
|
94
|
+
# between that check and this GET — same rationale as
|
|
95
|
+
# Bulkrax::CloudSourceValidator#validate_http_scheme!, and the same
|
|
96
|
+
# static, class-agnostic message for the same reason.
|
|
97
|
+
raise Bulkrax::UnsafeCloudSourceError, 'blocked unsafe remote source'
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def handle_response(file, response, temp_file)
|
|
101
|
+
unless response.is_a?(Net::HTTPSuccess)
|
|
102
|
+
# Static on purpose — this becomes the importer's status message,
|
|
103
|
+
# not just an ops log; see Bulkrax::CloudSourceValidator for why
|
|
104
|
+
# status codes/response details aren't echoed into it. The status
|
|
105
|
+
# code itself is logged (not attacker-controlled, not a credential).
|
|
106
|
+
Rails.logger.error("Bulkrax: cloud file download failed for #{file['file_name']} with status #{response.code}")
|
|
107
|
+
raise Bulkrax::UnsafeCloudSourceError, 'download failed: non-success response'
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
File.open(temp_file, 'wb') { |io| response.read_body { |chunk| io.write(chunk) } }
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# Resolves `uri`'s host, rejects it unless it has at least one public
|
|
114
|
+
# IP (reusing ssrf_filter's own resolver/blacklist — see above), and
|
|
115
|
+
# connects directly to that IP: with the environment proxy explicitly
|
|
116
|
+
# disabled (`Net::HTTP.new`'s `p_addr` defaults to `:ENV`, which would
|
|
117
|
+
# otherwise route through `http_proxy`/`https_proxy` and hand the
|
|
118
|
+
# pinned connection to a third party), and with the real hostname sent
|
|
119
|
+
# as the `Host` header and used for TLS SNI/certificate verification
|
|
120
|
+
# instead of the IP. Yields the live `Net::HTTPResponse` to the block
|
|
121
|
+
# *before* its body is read, so the caller can stream it.
|
|
122
|
+
def stream_download(uri, headers)
|
|
123
|
+
raise SsrfFilter::InvalidUriScheme, "URI scheme '#{uri.scheme}' not in whitelist" unless
|
|
124
|
+
SsrfFilter::DEFAULT_SCHEME_WHITELIST.include?(uri.scheme)
|
|
125
|
+
|
|
126
|
+
hostname = uri.hostname
|
|
127
|
+
ip_addresses = SsrfFilter::DEFAULT_RESOLVER.call(hostname)
|
|
128
|
+
raise SsrfFilter::UnresolvedHostname, "Could not resolve hostname '#{hostname}'" if ip_addresses.empty?
|
|
129
|
+
|
|
130
|
+
public_addresses = ip_addresses.reject { |ip| unsafe_ip_address?(ip) }
|
|
131
|
+
raise SsrfFilter::PrivateIPAddress, "Hostname '#{hostname}' has no public ip addresses" if public_addresses.empty?
|
|
132
|
+
|
|
133
|
+
request = Net::HTTP::Get.new(uri)
|
|
134
|
+
request['host'] = host_header(hostname, uri)
|
|
135
|
+
headers.each { |key, value| request[key] = value }
|
|
136
|
+
|
|
137
|
+
http = Net::HTTP.new(hostname, uri.port, nil)
|
|
138
|
+
http.ipaddr = public_addresses.sample.to_s
|
|
139
|
+
http.use_ssl = (uri.scheme == 'https')
|
|
140
|
+
http.start { |connection| connection.request(request) { |response| yield response } }
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# Mirrors `SsrfFilter.unsafe_ip_address?`, but against its public
|
|
144
|
+
# `IPV4_BLACKLIST`/`IPV6_BLACKLIST` constants directly rather than
|
|
145
|
+
# calling that private method — we only ever check single resolved
|
|
146
|
+
# addresses here (never a CIDR range), so the masked-range guard it
|
|
147
|
+
# also carries doesn't apply.
|
|
148
|
+
def unsafe_ip_address?(ip_address)
|
|
149
|
+
return SsrfFilter::IPV4_BLACKLIST.any? { |range| range.include?(ip_address) } if ip_address.ipv4?
|
|
150
|
+
return SsrfFilter::IPV6_BLACKLIST.any? { |range| range.include?(ip_address) } if ip_address.ipv6?
|
|
151
|
+
|
|
152
|
+
true
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# Matches `SsrfFilter.host_header`: the `Host` header should carry the
|
|
156
|
+
# real hostname (not the pinned IP we actually connect to), with the
|
|
157
|
+
# port suffixed only when it isn't the scheme's default.
|
|
158
|
+
def host_header(hostname, uri)
|
|
159
|
+
if (uri.port == 80 && uri.scheme == 'http') || (uri.port == 443 && uri.scheme == 'https')
|
|
160
|
+
hostname
|
|
161
|
+
else
|
|
162
|
+
"#{hostname}:#{uri.port}"
|
|
27
163
|
end
|
|
28
|
-
Rails.logger.info "Download complete: #{file['url']} to #{target_file}"
|
|
29
164
|
end
|
|
30
165
|
end
|
|
31
166
|
end
|
|
@@ -472,27 +472,29 @@ module Bulkrax
|
|
|
472
472
|
# Zip Slip preflight — reject entries whose names are obviously unsafe
|
|
473
473
|
# (absolute paths, `..` segments) before we touch the filesystem.
|
|
474
474
|
# {#safe_extract_path} is the final line of defense; this check just
|
|
475
|
-
# fails fast with a clear message.
|
|
475
|
+
# fails fast with a clear message. Delegates to {Bulkrax::SafePath} so
|
|
476
|
+
# cloud-file destinations and sources share the same rules.
|
|
476
477
|
#
|
|
477
478
|
# @raise [Bulkrax::UnzipError] if the entry name is unsafe
|
|
478
|
-
def reject_unsafe_entry!(name)
|
|
479
|
-
|
|
480
|
-
|
|
479
|
+
def self.reject_unsafe_entry!(name)
|
|
480
|
+
Bulkrax::SafePath.reject_unsafe_entry!(name)
|
|
481
|
+
rescue Bulkrax::UnsafePathError
|
|
482
|
+
raise Bulkrax::UnzipError, I18n.t('bulkrax.importer.unzip.errors.unsafe_entry', name: name.dup.force_encoding(Encoding::UTF_8).scrub)
|
|
481
483
|
end
|
|
484
|
+
# CsvParser#real_zip_entries calls this on the parser instance.
|
|
485
|
+
delegate :reject_unsafe_entry!, to: :class
|
|
482
486
|
|
|
483
487
|
# Zip Slip chokepoint. Resolves `relative_dest` against `dest_dir` and
|
|
484
488
|
# returns the absolute destination path — but only if it stays inside
|
|
485
|
-
# `dest_dir
|
|
486
|
-
# own path with `File.join`, so the
|
|
487
|
-
# construction.
|
|
489
|
+
# `dest_dir`, including through any symlink. Callers must use this
|
|
490
|
+
# value rather than building their own path with `File.join`, so the
|
|
491
|
+
# path returned is always safe by construction.
|
|
488
492
|
#
|
|
489
493
|
# @return [String] absolute destination path, validated to be inside `dest_dir`
|
|
490
494
|
# @raise [Bulkrax::UnzipError] if `relative_dest` escapes `dest_dir`
|
|
491
495
|
def safe_extract_path(dest_dir, relative_dest)
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
return dest_path if dest_path == expanded_dest_dir
|
|
495
|
-
return dest_path if dest_path.start_with?("#{expanded_dest_dir}#{File::SEPARATOR}")
|
|
496
|
+
Bulkrax::SafePath.confine!(dest_dir, relative_dest)
|
|
497
|
+
rescue Bulkrax::UnsafePathError
|
|
496
498
|
raise Bulkrax::UnzipError, I18n.t('bulkrax.importer.unzip.errors.unsafe_entry', name: relative_dest)
|
|
497
499
|
end
|
|
498
500
|
|
|
@@ -64,7 +64,7 @@ unless ENV.fetch('BULKRAX_NO_BAGIT', 'false').to_s == 'true'
|
|
|
64
64
|
record_data = entry_class.data_for_entry(data_row, source_identifier, self)
|
|
65
65
|
next record_data if importerexporter.metadata_only?
|
|
66
66
|
|
|
67
|
-
record_data[:file] = bag.bag_files.join('|') if
|
|
67
|
+
record_data[:file] = bag.bag_files.join('|') if curation_concern?(record_data[:model])
|
|
68
68
|
record_data
|
|
69
69
|
end
|
|
70
70
|
else
|
|
@@ -178,17 +178,31 @@ unless ENV.fetch('BULKRAX_NO_BAGIT', 'false').to_s == 'true'
|
|
|
178
178
|
# @todo - investigate getting directory structure
|
|
179
179
|
# @todo - investigate using perform_later, and having the importer check for
|
|
180
180
|
# DownloadCloudFileJob before it starts
|
|
181
|
-
def retrieve_cloud_files(files,
|
|
181
|
+
def retrieve_cloud_files(files, importer)
|
|
182
182
|
# There should only be one zip file for Bagit, take the first
|
|
183
183
|
return if files['0'].blank?
|
|
184
|
-
|
|
184
|
+
|
|
185
|
+
file = files['0']
|
|
186
|
+
# Checked on the raw file_name before any normalization — see
|
|
187
|
+
# Bulkrax::CsvParser#plan_cloud_file for why this must come first.
|
|
188
|
+
Bulkrax::CloudSourceValidator.preflight!(file)
|
|
189
|
+
|
|
190
|
+
relative_filename = file['file_name'].tr(' ', '_')
|
|
191
|
+
target_file = Bulkrax::SafePath.confine!(path_for_import, relative_filename, require_file: true)
|
|
185
192
|
# Now because we want the files in place before the importer runs
|
|
186
|
-
Bulkrax::DownloadCloudFileJob.perform_now(
|
|
193
|
+
Bulkrax::DownloadCloudFileJob.perform_now(file, importer_id: importer.id, relative_filename: relative_filename)
|
|
187
194
|
return target_file
|
|
188
195
|
end
|
|
189
196
|
|
|
190
197
|
private
|
|
191
198
|
|
|
199
|
+
# Both sides resolve the same way, so a registered Work matches a row
|
|
200
|
+
# the importer creates as a WorkResource.
|
|
201
|
+
def curation_concern?(model_name)
|
|
202
|
+
klass = FactoryClassFinder.resolve(model_name) if model_name.present?
|
|
203
|
+
klass.present? && Bulkrax.curation_concerns.any? { |concern| FactoryClassFinder.resolve(concern.to_s) == klass }
|
|
204
|
+
end
|
|
205
|
+
|
|
192
206
|
def bags
|
|
193
207
|
return @bags if @bags.present?
|
|
194
208
|
new_bag = bag(import_file_path)
|
|
@@ -205,24 +205,55 @@ module Bulkrax
|
|
|
205
205
|
# @todo - investigate using perform_later, and having the importer check for
|
|
206
206
|
# DownloadCloudFileJob before it starts
|
|
207
207
|
def retrieve_cloud_files(files, importer)
|
|
208
|
+
plan = plan_cloud_files(files)
|
|
209
|
+
dispatch_cloud_files!(plan, importer)
|
|
210
|
+
importer[:parser_fields]['original_file_paths'] = plan.map { |_file, _relative_filename, target_file| target_file }
|
|
211
|
+
return nil
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
# Validates and resolves the whole batch, without enqueueing anything
|
|
215
|
+
# yet. Otherwise an earlier, valid file's job would already be running
|
|
216
|
+
# by the time a later file in the same batch is found to be unsafe.
|
|
217
|
+
# Split out from {#retrieve_cloud_files} so a caller (the importers
|
|
218
|
+
# controller) can persist the resolved paths before dispatching.
|
|
219
|
+
#
|
|
220
|
+
# @return [Array<Array(Hash, String, String)>] one entry per file: the
|
|
221
|
+
# file spec, its relative destination filename, and the resolved
|
|
222
|
+
# absolute target path
|
|
223
|
+
def plan_cloud_files(files)
|
|
208
224
|
files_path = File.join(path_for_import, 'files')
|
|
209
225
|
FileUtils.mkdir_p(files_path) unless File.exist?(files_path)
|
|
210
|
-
|
|
211
|
-
files.
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
226
|
+
|
|
227
|
+
files.values.map { |file| plan_cloud_file(file) }
|
|
228
|
+
end
|
|
229
|
+
|
|
230
|
+
# Enqueues a download job for each entry of an already-validated plan
|
|
231
|
+
# (see {#plan_cloud_files}).
|
|
232
|
+
def dispatch_cloud_files!(plan, importer)
|
|
233
|
+
plan.each { |file, relative_filename, _target_file| Bulkrax::DownloadCloudFileJob.perform_later(file, importer_id: importer.id, relative_filename: relative_filename) }
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# Validates one cloud-file spec and resolves its destination, without
|
|
237
|
+
# enqueueing anything yet.
|
|
238
|
+
#
|
|
239
|
+
# @return [Array(Hash, String, String)] the file spec, its relative
|
|
240
|
+
# destination filename, and the resolved absolute target path
|
|
241
|
+
def plan_cloud_file(file)
|
|
242
|
+
# fixes bug where auth headers do not get attached properly
|
|
243
|
+
if file['auth_header'].present?
|
|
244
|
+
file['headers'] ||= {}
|
|
245
|
+
file['headers'].merge!(file['auth_header'])
|
|
223
246
|
end
|
|
224
|
-
|
|
225
|
-
|
|
247
|
+
|
|
248
|
+
# Checked on the raw file_name, before it's joined under 'files/':
|
|
249
|
+
# that join would otherwise neutralize a leading `/` (File.join
|
|
250
|
+
# doesn't treat it as absolute once it's not the first argument).
|
|
251
|
+
Bulkrax::CloudSourceValidator.preflight!(file)
|
|
252
|
+
|
|
253
|
+
# this only works for uniquely named files
|
|
254
|
+
relative_filename = File.join('files', file['file_name'].tr(' ', '_'))
|
|
255
|
+
target_file = Bulkrax::SafePath.confine!(path_for_import, relative_filename, require_file: true)
|
|
256
|
+
[file, relative_filename, target_file]
|
|
226
257
|
end
|
|
227
258
|
|
|
228
259
|
# export methods
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bulkrax
|
|
4
|
+
# Validates a cloud-file source (the Hash a user selected via
|
|
5
|
+
# browse-everything, or supplied directly in importer params) before
|
|
6
|
+
# Bulkrax downloads it. Destination confinement (see {Bulkrax::SafePath})
|
|
7
|
+
# stops a malicious filename from writing outside the importer's
|
|
8
|
+
# workspace; this validator stops a malicious `url` from reading a local
|
|
9
|
+
# file outside the configured filesystem-provider root, or from reaching
|
|
10
|
+
# a private/internal network over HTTP(S) (SSRF).
|
|
11
|
+
#
|
|
12
|
+
# Called twice by design: once before enqueueing, so an obviously unsafe
|
|
13
|
+
# batch never reaches a job queue, and again inside the download job,
|
|
14
|
+
# so a legacy or tampered job argument can't bypass validation.
|
|
15
|
+
class CloudSourceValidator
|
|
16
|
+
LOCAL_FILE_HOSTS = ['', 'localhost'].freeze
|
|
17
|
+
|
|
18
|
+
# Lightweight preflight for a single cloud-file selection: checks the
|
|
19
|
+
# raw file name and the source's safety, without resolving anything
|
|
20
|
+
# against an importer's workspace. Shared by CsvParser#plan_cloud_file,
|
|
21
|
+
# BagitParser#retrieve_cloud_files, and ImportersController's pre-save
|
|
22
|
+
# check, so a selection is judged unsafe the same way whether or not an
|
|
23
|
+
# importer has been persisted yet.
|
|
24
|
+
#
|
|
25
|
+
# @param file [Hash] a single cloud-file spec with at least `url` and `file_name` keys
|
|
26
|
+
# @raise [Bulkrax::UnsafePathError] if the raw file name is unsafe
|
|
27
|
+
# @raise [Bulkrax::UnsafeCloudSourceError] if the source isn't safe to download
|
|
28
|
+
# @return [true]
|
|
29
|
+
def self.preflight!(file)
|
|
30
|
+
name = file['file_name'] || file[:file_name]
|
|
31
|
+
raise Bulkrax::UnsafePathError, 'cloud file name must not be blank' if name.blank?
|
|
32
|
+
Bulkrax::SafePath.reject_unsafe_entry!(name)
|
|
33
|
+
validate!(file)
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# @param file [Hash] a single cloud-file spec with at least a `url` key
|
|
37
|
+
# @raise [Bulkrax::UnsafeCloudSourceError] if the source isn't safe to download
|
|
38
|
+
# @return [true]
|
|
39
|
+
def self.validate!(file)
|
|
40
|
+
url = file['url'] || file[:url]
|
|
41
|
+
raise Bulkrax::UnsafeCloudSourceError, 'the cloud file is missing a url' if url.blank?
|
|
42
|
+
|
|
43
|
+
uri = parse_uri(url)
|
|
44
|
+
case uri.scheme
|
|
45
|
+
when 'file'
|
|
46
|
+
validate_file_scheme!(uri)
|
|
47
|
+
when 'http', 'https'
|
|
48
|
+
validate_http_scheme!(uri, file)
|
|
49
|
+
else
|
|
50
|
+
raise Bulkrax::UnsafeCloudSourceError, 'unsupported source scheme'
|
|
51
|
+
end
|
|
52
|
+
true
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
def self.parse_uri(url)
|
|
56
|
+
Addressable::URI.parse(url.to_s)
|
|
57
|
+
rescue Addressable::URI::InvalidURIError
|
|
58
|
+
raise Bulkrax::UnsafeCloudSourceError, 'the cloud file url is malformed'
|
|
59
|
+
end
|
|
60
|
+
private_class_method :parse_uri
|
|
61
|
+
|
|
62
|
+
def self.validate_file_scheme!(uri)
|
|
63
|
+
raise Bulkrax::UnsafeCloudSourceError, 'a file: source must not specify a remote host' unless LOCAL_FILE_HOSTS.include?(uri.host.to_s)
|
|
64
|
+
|
|
65
|
+
home = file_system_home
|
|
66
|
+
raise Bulkrax::UnsafeCloudSourceError, 'the filesystem provider is not configured' if home.blank?
|
|
67
|
+
|
|
68
|
+
decoded_path = URI::DEFAULT_PARSER.unescape(uri.path.to_s)
|
|
69
|
+
Bulkrax::SafePath.confine!(home, decoded_path, require_file: true, allow_absolute: true)
|
|
70
|
+
rescue Bulkrax::UnsafePathError => e
|
|
71
|
+
raise Bulkrax::UnsafeCloudSourceError, e.message
|
|
72
|
+
end
|
|
73
|
+
private_class_method :validate_file_scheme!
|
|
74
|
+
|
|
75
|
+
# Enforced at connection time, not by a DNS preflight: SsrfFilter
|
|
76
|
+
# resolves the hostname, rejects private/loopback/link-local/metadata
|
|
77
|
+
# addresses, and then connects directly to the validated IP (with TLS
|
|
78
|
+
# verified against the original hostname), closing the gap a
|
|
79
|
+
# resolve-then-connect check would leave open to DNS rebinding.
|
|
80
|
+
# Redirects are disabled outright (rather than re-validated per hop)
|
|
81
|
+
# so a header carrying provider credentials is never resent to a
|
|
82
|
+
# different host.
|
|
83
|
+
def self.validate_http_scheme!(uri, file)
|
|
84
|
+
raise Bulkrax::UnsafeCloudSourceError, 'no remote cloud provider is configured' unless remote_provider_configured?
|
|
85
|
+
raise Bulkrax::UnsafeCloudSourceError, 'the cloud file url must include a host' if uri.host.blank?
|
|
86
|
+
raise Bulkrax::UnsafeCloudSourceError, 'the cloud file url must not include credentials' if uri.userinfo.present?
|
|
87
|
+
|
|
88
|
+
SsrfFilter.head(uri.to_s, headers: request_headers(file), max_redirects: 0)
|
|
89
|
+
rescue SsrfFilter::Error, SocketError, SystemCallError, Timeout::Error, OpenSSL::SSL::SSLError
|
|
90
|
+
# Static and class-agnostic on purpose: SsrfFilter's own exception
|
|
91
|
+
# message can include the resolved IP or hostname it rejected, and
|
|
92
|
+
# this error is shown to the importing user / written to the
|
|
93
|
+
# importer's status, not just an ops log.
|
|
94
|
+
raise Bulkrax::UnsafeCloudSourceError, 'blocked unsafe remote source'
|
|
95
|
+
end
|
|
96
|
+
private_class_method :validate_http_scheme!
|
|
97
|
+
|
|
98
|
+
# Merges the caller-supplied headers (used for provider auth) but
|
|
99
|
+
# strips any transport-control header a malicious selection could use
|
|
100
|
+
# to smuggle a different Host past SsrfFilter's own Host header.
|
|
101
|
+
def self.request_headers(file)
|
|
102
|
+
headers = {}
|
|
103
|
+
headers.merge!(file['headers'] || file[:headers] || {})
|
|
104
|
+
headers.merge!(file['auth_header'] || file[:auth_header] || {})
|
|
105
|
+
headers.reject { |key, _| key.to_s.casecmp('host').zero? }
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
def self.file_system_home
|
|
109
|
+
config = provider_config('file_system')
|
|
110
|
+
config && (config['home'] || config[:home])
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def self.remote_provider_configured?
|
|
114
|
+
BrowseEverything.config.any? { |key, value| key.to_s != 'file_system' && value.present? }
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def self.provider_config(name)
|
|
118
|
+
config = BrowseEverything.config
|
|
119
|
+
config[name] || config[name.to_sym]
|
|
120
|
+
end
|
|
121
|
+
private_class_method :provider_config
|
|
122
|
+
end
|
|
123
|
+
end
|
|
@@ -11,13 +11,7 @@ module Bulkrax
|
|
|
11
11
|
end
|
|
12
12
|
|
|
13
13
|
def self.determine_klass_for(model_name)
|
|
14
|
-
|
|
15
|
-
Valkyrie.config.resource_class_resolver.call(model_name)
|
|
16
|
-
else
|
|
17
|
-
model_name.constantize
|
|
18
|
-
end
|
|
19
|
-
rescue StandardError
|
|
20
|
-
nil
|
|
14
|
+
FactoryClassFinder.resolve(model_name)
|
|
21
15
|
end
|
|
22
16
|
|
|
23
17
|
private
|
|
@@ -27,18 +21,10 @@ module Bulkrax
|
|
|
27
21
|
when Array
|
|
28
22
|
return all_available_models if models.empty?
|
|
29
23
|
return all_available_models if models.include?('all')
|
|
30
|
-
models.
|
|
24
|
+
models.select { |model| FactoryClassFinder.resolve(model) }
|
|
31
25
|
else
|
|
32
26
|
all_available_models
|
|
33
27
|
end
|
|
34
|
-
rescue StandardError
|
|
35
|
-
[]
|
|
36
|
-
end
|
|
37
|
-
|
|
38
|
-
def safe_constantize(model_name)
|
|
39
|
-
model_name.constantize && model_name
|
|
40
|
-
rescue NameError
|
|
41
|
-
nil
|
|
42
28
|
end
|
|
43
29
|
|
|
44
30
|
def all_available_models
|
|
@@ -48,6 +48,37 @@ module Bulkrax
|
|
|
48
48
|
new(entry: entry, coercer: coercer).find
|
|
49
49
|
end
|
|
50
50
|
|
|
51
|
+
##
|
|
52
|
+
# @param name [String] a model name as a sheet or export spells it
|
|
53
|
+
# @return [Class] the class import creates for that name
|
|
54
|
+
# @return [Nil] when no class matches the name
|
|
55
|
+
def self.resolve(name, coercer: Bulkrax.factory_class_name_coercer || DefaultCoercer)
|
|
56
|
+
name = normalize_class_name(name)
|
|
57
|
+
configured_model_class_for(name) || coercer.call(name)
|
|
58
|
+
rescue NameError
|
|
59
|
+
nil
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Sheets and exports spell file set and collection models either way, and
|
|
63
|
+
# the factories and CsvEntry pick those paths by exact comparison with the
|
|
64
|
+
# configured class.
|
|
65
|
+
def self.configured_model_class_for(name)
|
|
66
|
+
return Bulkrax.file_model_class if Bulkrax.file_model_name?(name)
|
|
67
|
+
Bulkrax.collection_model_class if Bulkrax.collection_model_name?(name)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
##
|
|
71
|
+
# Normalize a class name string to proper format
|
|
72
|
+
# @param name [String] the class name to normalize
|
|
73
|
+
# @return [String] the normalized class name
|
|
74
|
+
def self.normalize_class_name(name)
|
|
75
|
+
name = name.to_s
|
|
76
|
+
name = name.tr(' ', '_')
|
|
77
|
+
name = name.downcase if name.match?(/[-_]/)
|
|
78
|
+
name.camelcase
|
|
79
|
+
end
|
|
80
|
+
private_class_method :configured_model_class_for, :normalize_class_name
|
|
81
|
+
|
|
51
82
|
def initialize(entry:, coercer:)
|
|
52
83
|
@entry = entry
|
|
53
84
|
@coercer = coercer
|
|
@@ -59,9 +90,7 @@ module Bulkrax
|
|
|
59
90
|
# @return [Nil] when we encounter errors with constantizing the {#name}.
|
|
60
91
|
# @see #name
|
|
61
92
|
def find
|
|
62
|
-
|
|
63
|
-
rescue NameError
|
|
64
|
-
nil
|
|
93
|
+
self.class.resolve(name, coercer: coercer)
|
|
65
94
|
rescue
|
|
66
95
|
entry.default_work_type.constantize
|
|
67
96
|
end
|
|
@@ -73,10 +102,7 @@ module Bulkrax
|
|
|
73
102
|
# @return [String]
|
|
74
103
|
def name
|
|
75
104
|
# Try each strategy in order until one returns a value
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
# Normalize the string format
|
|
79
|
-
normalize_class_name(fc)
|
|
105
|
+
find_factory_class_name || entry.default_work_type
|
|
80
106
|
rescue
|
|
81
107
|
entry.default_work_type
|
|
82
108
|
end
|
|
@@ -118,16 +144,5 @@ module Bulkrax
|
|
|
118
144
|
field = entry.parser.model_field_mappings.find { |f| entry.raw_metadata&.[](f).present? }
|
|
119
145
|
Array.wrap(entry.raw_metadata[field]).first
|
|
120
146
|
end
|
|
121
|
-
|
|
122
|
-
##
|
|
123
|
-
# Normalize a class name string to proper format
|
|
124
|
-
# @param name [String] the class name to normalize
|
|
125
|
-
# @return [String] the normalized class name
|
|
126
|
-
def normalize_class_name(name)
|
|
127
|
-
name = name.to_s
|
|
128
|
-
name = name.tr(' ', '_')
|
|
129
|
-
name = name.downcase if name.match?(/[-_]/)
|
|
130
|
-
name.camelcase
|
|
131
|
-
end
|
|
132
147
|
end
|
|
133
148
|
end
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bulkrax
|
|
4
|
+
# Shared path-confinement checks used anywhere Bulkrax resolves a
|
|
5
|
+
# caller-supplied relative path against a trusted root directory: ZIP
|
|
6
|
+
# extraction, cloud-file destinations, and filesystem cloud sources.
|
|
7
|
+
#
|
|
8
|
+
# Lexical checks alone (rejecting `..` and absolute paths) don't catch a
|
|
9
|
+
# symlink planted inside the root that points back out of it, so
|
|
10
|
+
# {.confine!} also resolves the longest existing ancestor of the
|
|
11
|
+
# candidate path and checks *that* for escape.
|
|
12
|
+
#
|
|
13
|
+
# @raise [Bulkrax::UnsafePathError] from any public method, never a bare
|
|
14
|
+
# StandardError, so callers can rescue one error class.
|
|
15
|
+
class SafePath
|
|
16
|
+
# Built via Integer#chr, not a literal escape, so this source
|
|
17
|
+
# file never contains a raw NUL byte (which some tools,
|
|
18
|
+
# including `git diff`, treat as a signal to classify the
|
|
19
|
+
# whole file as binary).
|
|
20
|
+
NUL = 0.chr.freeze
|
|
21
|
+
|
|
22
|
+
# Preflight check for a raw, caller-supplied name — a ZIP entry name,
|
|
23
|
+
# or a cloud-file's uploaded filename — before any join, space
|
|
24
|
+
# normalization, or filesystem access. Callers must run this on the
|
|
25
|
+
# *raw* name: joining it under a prefix first (e.g. `File.join('files',
|
|
26
|
+
# name)`) can silently neutralize a leading `/`, which would defeat
|
|
27
|
+
# this check if run afterward. {.confine!} runs it again on the
|
|
28
|
+
# resolved candidate as the final authority.
|
|
29
|
+
#
|
|
30
|
+
# @param name [String] a raw entry/file name
|
|
31
|
+
# @raise [Bulkrax::UnsafePathError] if the name is an absolute path, has
|
|
32
|
+
# a `..` segment, or contains a NUL byte
|
|
33
|
+
def self.reject_unsafe_entry!(name)
|
|
34
|
+
name = name.to_s
|
|
35
|
+
raise Bulkrax::UnsafePathError, 'path must not contain a NUL byte' if name.include?(NUL)
|
|
36
|
+
raise Bulkrax::UnsafePathError, 'path must not contain a parent-directory reference' if name.split('/').include?('..')
|
|
37
|
+
raise Bulkrax::UnsafePathError, 'path must not be an absolute path' if name.start_with?('/')
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Resolves `candidate` against `root` and returns the absolute result,
|
|
41
|
+
# but only if it stays inside `root` once both symlinks and `..`
|
|
42
|
+
# segments are resolved.
|
|
43
|
+
#
|
|
44
|
+
# By default `candidate` is held to the same lexical rule as
|
|
45
|
+
# {.reject_unsafe_entry!}: no `..` segment and no leading `/`, even if
|
|
46
|
+
# the fully-resolved result would happen to land inside `root` — a
|
|
47
|
+
# destination filename that only *looks* safe after normalization is
|
|
48
|
+
# still rejected outright, per the plan, rather than silently
|
|
49
|
+
# corrected. The one legitimate exception is a `file:` *source* path
|
|
50
|
+
# (always given as an absolute path by the filesystem provider);
|
|
51
|
+
# pass `allow_absolute: true` for that case. `..` segments are never
|
|
52
|
+
# allowed, even then.
|
|
53
|
+
#
|
|
54
|
+
# @param root [String] trusted directory that the result must stay inside
|
|
55
|
+
# @param candidate [String] a relative (or, with `allow_absolute`, absolute) path to resolve
|
|
56
|
+
# @param require_file [Boolean] when true, reject a result equal to `root` itself
|
|
57
|
+
# @param allow_absolute [Boolean] when true, permit `candidate` to be an absolute path
|
|
58
|
+
# @return [String] absolute path, validated to be inside `root`
|
|
59
|
+
# @raise [Bulkrax::UnsafePathError] if `candidate` is blank, contains a
|
|
60
|
+
# NUL byte, has a `..` segment, is an absolute path (unless
|
|
61
|
+
# `allow_absolute`), escapes `root`, or escapes `root` via a symlink
|
|
62
|
+
def self.confine!(root, candidate, require_file: false, allow_absolute: false)
|
|
63
|
+
raise Bulkrax::UnsafePathError, 'path must not be blank' if candidate.blank?
|
|
64
|
+
|
|
65
|
+
candidate = candidate.to_s
|
|
66
|
+
if allow_absolute
|
|
67
|
+
raise Bulkrax::UnsafePathError, 'path must not contain a NUL byte' if candidate.include?(NUL)
|
|
68
|
+
raise Bulkrax::UnsafePathError, 'path must not contain a parent-directory reference' if candidate.split('/').include?('..')
|
|
69
|
+
else
|
|
70
|
+
reject_unsafe_entry!(candidate)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
expanded_root = File.expand_path(root)
|
|
74
|
+
expanded_path = File.expand_path(candidate, expanded_root)
|
|
75
|
+
|
|
76
|
+
raise Bulkrax::UnsafePathError, 'path escapes the confined root' unless expanded_path == expanded_root || expanded_path.start_with?("#{expanded_root}#{File::SEPARATOR}")
|
|
77
|
+
raise Bulkrax::UnsafePathError, 'a file path is required' if require_file && expanded_path == expanded_root
|
|
78
|
+
|
|
79
|
+
reject_symlink_escape!(expanded_root, expanded_path)
|
|
80
|
+
expanded_path
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# True if a filesystem entry exists at `path` — including a dangling
|
|
84
|
+
# symlink. File.exist? follows symlinks and reports `false` for one
|
|
85
|
+
# whose target doesn't exist yet, which is exactly the entry a caller
|
|
86
|
+
# is about to write through, so it can't be the only check here.
|
|
87
|
+
def self.present?(path)
|
|
88
|
+
File.exist?(path) || File.symlink?(path)
|
|
89
|
+
end
|
|
90
|
+
private_class_method :present?
|
|
91
|
+
|
|
92
|
+
# Resolves `path` to its real, final location, tolerating a dangling
|
|
93
|
+
# symlink (one whose target doesn't exist) by following the link
|
|
94
|
+
# lexically instead of raising the way File.realpath would. Bounded
|
|
95
|
+
# to 32 hops so a symlink cycle fails closed rather than hanging.
|
|
96
|
+
def self.resolve_fully(path)
|
|
97
|
+
current = path
|
|
98
|
+
32.times do
|
|
99
|
+
return File.realpath(current) if File.exist?(current)
|
|
100
|
+
return current unless File.symlink?(current)
|
|
101
|
+
current = File.expand_path(File.readlink(current), File.dirname(current))
|
|
102
|
+
end
|
|
103
|
+
raise Bulkrax::UnsafePathError, 'path has too many levels of symbolic links'
|
|
104
|
+
end
|
|
105
|
+
private_class_method :resolve_fully
|
|
106
|
+
|
|
107
|
+
# Resolves the longest existing-or-dangling-symlink ancestor of
|
|
108
|
+
# `expanded_path` (which may be `expanded_path` itself) and checks it
|
|
109
|
+
# for a symlink escape. Path components that aren't present at all
|
|
110
|
+
# (not even as a symlink) can't be symlinks, so this is the final
|
|
111
|
+
# line of defense without racing the filesystem. As the plan assumes,
|
|
112
|
+
# this is not a guard against a *concurrent* write to the same path —
|
|
113
|
+
# only against a symlink already planted in an application-controlled
|
|
114
|
+
# staging directory.
|
|
115
|
+
def self.reject_symlink_escape!(expanded_root, expanded_path)
|
|
116
|
+
real_root = present?(expanded_root) ? resolve_fully(expanded_root) : expanded_root
|
|
117
|
+
|
|
118
|
+
existing_ancestor = expanded_path
|
|
119
|
+
existing_ancestor = File.dirname(existing_ancestor) until present?(existing_ancestor) || existing_ancestor == File.dirname(existing_ancestor)
|
|
120
|
+
return unless present?(existing_ancestor)
|
|
121
|
+
|
|
122
|
+
real_existing = resolve_fully(existing_ancestor)
|
|
123
|
+
return if real_existing == real_root || real_existing.start_with?("#{real_root}#{File::SEPARATOR}")
|
|
124
|
+
|
|
125
|
+
raise Bulkrax::UnsafePathError, 'path escapes the confined root via a symlink'
|
|
126
|
+
end
|
|
127
|
+
private_class_method :reject_symlink_escape!
|
|
128
|
+
end
|
|
129
|
+
end
|
|
@@ -91,6 +91,8 @@ en:
|
|
|
91
91
|
public: Public
|
|
92
92
|
browse_everything:
|
|
93
93
|
add_cloud_files: Add Cloud Files
|
|
94
|
+
errors:
|
|
95
|
+
missing_destination_context: This cloud file download is missing required destination information and can no longer be safely processed. Please re-select the file and try the import again.
|
|
94
96
|
csv:
|
|
95
97
|
add_csv_to_import: 'Add CSV or ZIP File to Import:'
|
|
96
98
|
add_files_hint: Choose files to upload. The filenames must be unique, and the filenames must be referenced in a column called 'file' in the accompanying CSV file.
|
data/lib/bulkrax/version.rb
CHANGED
data/lib/bulkrax.rb
CHANGED
metadata
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: bulkrax
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 10.0.
|
|
4
|
+
version: 10.0.2
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Rob Kaufman
|
|
8
|
+
autorequire:
|
|
8
9
|
bindir: bin
|
|
9
10
|
cert_chain: []
|
|
10
|
-
date:
|
|
11
|
+
date: 2026-11-24 00:00:00.000000000 Z
|
|
11
12
|
dependencies:
|
|
12
13
|
- !ruby/object:Gem::Dependency
|
|
13
14
|
name: rails
|
|
@@ -257,6 +258,26 @@ dependencies:
|
|
|
257
258
|
- - ">="
|
|
258
259
|
- !ruby/object:Gem::Version
|
|
259
260
|
version: '0'
|
|
261
|
+
- !ruby/object:Gem::Dependency
|
|
262
|
+
name: ssrf_filter
|
|
263
|
+
requirement: !ruby/object:Gem::Requirement
|
|
264
|
+
requirements:
|
|
265
|
+
- - ">="
|
|
266
|
+
- !ruby/object:Gem::Version
|
|
267
|
+
version: '1.0'
|
|
268
|
+
- - "<"
|
|
269
|
+
- !ruby/object:Gem::Version
|
|
270
|
+
version: '2.0'
|
|
271
|
+
type: :runtime
|
|
272
|
+
prerelease: false
|
|
273
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
274
|
+
requirements:
|
|
275
|
+
- - ">="
|
|
276
|
+
- !ruby/object:Gem::Version
|
|
277
|
+
version: '1.0'
|
|
278
|
+
- - "<"
|
|
279
|
+
- !ruby/object:Gem::Version
|
|
280
|
+
version: '2.0'
|
|
260
281
|
- !ruby/object:Gem::Dependency
|
|
261
282
|
name: dry-monads
|
|
262
283
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -384,6 +405,8 @@ files:
|
|
|
384
405
|
- app/controllers/concerns/bulkrax/download_behavior.rb
|
|
385
406
|
- app/controllers/concerns/bulkrax/guided_import_demo_scenarios.rb
|
|
386
407
|
- app/controllers/concerns/bulkrax/importer_file_handler.rb
|
|
408
|
+
- app/errors/bulkrax/unsafe_cloud_source_error.rb
|
|
409
|
+
- app/errors/bulkrax/unsafe_path_error.rb
|
|
387
410
|
- app/errors/bulkrax/unzip_error.rb
|
|
388
411
|
- app/factories/bulkrax/object_factory.rb
|
|
389
412
|
- app/factories/bulkrax/object_factory_interface.rb
|
|
@@ -461,6 +484,7 @@ files:
|
|
|
461
484
|
- app/parsers/concerns/bulkrax/csv_parser/csv_validation_helpers.rb
|
|
462
485
|
- app/parsers/concerns/bulkrax/csv_parser/csv_validation_hierarchy.rb
|
|
463
486
|
- app/search_builders/bulkrax/export_search_builder.rb
|
|
487
|
+
- app/services/bulkrax/cloud_source_validator.rb
|
|
464
488
|
- app/services/bulkrax/csv_template/column_builder.rb
|
|
465
489
|
- app/services/bulkrax/csv_template/column_descriptor.rb
|
|
466
490
|
- app/services/bulkrax/csv_template/csv_builder.rb
|
|
@@ -476,6 +500,7 @@ files:
|
|
|
476
500
|
- app/services/bulkrax/csv_template/value_determiner.rb
|
|
477
501
|
- app/services/bulkrax/factory_class_finder.rb
|
|
478
502
|
- app/services/bulkrax/remove_relationships_for_importer.rb
|
|
503
|
+
- app/services/bulkrax/safe_path.rb
|
|
479
504
|
- app/services/bulkrax/split_pattern_coercion.rb
|
|
480
505
|
- app/services/bulkrax/stepper_response_formatter.rb
|
|
481
506
|
- app/services/bulkrax/validation_error_csv_builder.rb
|
|
@@ -591,6 +616,7 @@ homepage: https://github.com/samvera-labs/bulkrax
|
|
|
591
616
|
licenses:
|
|
592
617
|
- Apache-2.0
|
|
593
618
|
metadata: {}
|
|
619
|
+
post_install_message:
|
|
594
620
|
rdoc_options: []
|
|
595
621
|
require_paths:
|
|
596
622
|
- lib
|
|
@@ -605,7 +631,8 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
605
631
|
- !ruby/object:Gem::Version
|
|
606
632
|
version: '0'
|
|
607
633
|
requirements: []
|
|
608
|
-
rubygems_version:
|
|
634
|
+
rubygems_version: 3.5.16
|
|
635
|
+
signing_key:
|
|
609
636
|
specification_version: 4
|
|
610
637
|
summary: Import and export tool for Hyrax and Hyku
|
|
611
638
|
test_files: []
|