tus-server 2.3.0 → 3.0.0

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.
data/lib/tus/server.rb CHANGED
@@ -4,6 +4,7 @@ require "roda"
4
4
  require "rack/rewindable_input"
5
5
 
6
6
  require "tus/storage/filesystem"
7
+ require "tus/locker"
7
8
  require "tus/info"
8
9
  require "tus/input"
9
10
  require "tus/checksum"
@@ -18,7 +19,7 @@ module Tus
18
19
  class Server < Roda
19
20
  SUPPORTED_VERSIONS = ["1.0.0"]
20
21
  SUPPORTED_EXTENSIONS = [
21
- "creation", "creation-defer-length",
22
+ "creation", "creation-defer-length", "creation-with-upload",
22
23
  "termination",
23
24
  "expiration",
24
25
  "concatenation",
@@ -33,6 +34,8 @@ module Tus
33
34
  opts[:disposition] = "inline"
34
35
  opts[:redirect_download] = nil
35
36
  opts[:hooks] = {}
37
+ opts[:locker] = nil
38
+ opts[:lock_timeout] = 20
36
39
 
37
40
  plugin :all_verbs
38
41
  plugin :default_headers, {"Content-Type" => ""}
@@ -64,20 +67,12 @@ module Tus
64
67
 
65
68
  r.is ['', true] do
66
69
  # OPTIONS /
67
- r.options do
68
- response.headers.update(
69
- "Tus-Version" => SUPPORTED_VERSIONS.join(","),
70
- "Tus-Extension" => SUPPORTED_EXTENSIONS.join(","),
71
- "Tus-Max-Size" => max_size.to_s,
72
- "Tus-Checksum-Algorithm" => SUPPORTED_CHECKSUM_ALGORITHMS.join(","),
73
- )
74
-
75
- no_content!
76
- end
70
+ r.options { server_info! }
77
71
 
78
72
  # POST /
79
73
  r.post do
80
- validate_upload_length! unless request.headers["Upload-Concat"].to_s.start_with?("final") || request.headers["Upload-Defer-Length"] == "1"
74
+ validate_upload_defer_length! if request.headers["Upload-Defer-Length"]
75
+ validate_upload_length! unless request.headers["Upload-Concat"].to_s.start_with?("final") || request.headers["Upload-Defer-Length"]
81
76
  validate_upload_metadata! if request.headers["Upload-Metadata"]
82
77
  validate_upload_concat! if request.headers["Upload-Concat"]
83
78
 
@@ -93,6 +88,16 @@ module Tus
93
88
 
94
89
  before_create(uid, info)
95
90
 
91
+ # creation-with-upload: the request body holds the first chunk of data
92
+ upload_data = request.content_type == RESUMABLE_CONTENT_TYPE &&
93
+ request.content_length != "0" &&
94
+ info.length != 0
95
+
96
+ if upload_data
97
+ error!(400, "Cannot upload data to a final upload") if info.final?
98
+ validate_content_length!(request.content_length.to_i, info) if request.content_length
99
+ end
100
+
96
101
  if info.final?
97
102
  length = validate_partial_uploads!(info.partial_uploads)
98
103
 
@@ -105,84 +110,47 @@ module Tus
105
110
 
106
111
  after_create(uid, info)
107
112
 
108
- storage.update_info(uid, info.to_h)
109
- response.headers.update(info.headers)
110
-
111
- file_url = "#{request.url.chomp("/")}/#{uid}"
112
- created!(file_url)
113
- end
114
- end
115
-
116
- r.is String do |uid|
117
- # OPTIONS /{uid}
118
- r.options do
119
- response.headers.update(
120
- "Tus-Version" => SUPPORTED_VERSIONS.join(","),
121
- "Tus-Extension" => SUPPORTED_EXTENSIONS.join(","),
122
- "Tus-Max-Size" => max_size.to_s,
123
- "Tus-Checksum-Algorithm" => SUPPORTED_CHECKSUM_ALGORITHMS.join(","),
124
- )
125
-
126
- no_content!
127
- end
128
-
129
- begin
130
- info = Tus::Info.new(storage.read_info(uid))
131
- rescue Tus::NotFound
132
- error!(404, "Upload Not Found")
133
- end
134
-
135
- # HEAD /{uid}
136
- r.head do
137
- response.headers.update(info.headers)
138
- response.headers["Cache-Control"] = "no-store"
139
-
140
- no_content!
141
- end
113
+ # an empty upload is complete as soon as it's created
114
+ finish_upload!(uid, info) if info.length == 0 && !info.final?
142
115
 
143
- # PATCH /{uid}
144
- r.patch do
145
- if info.defer_length? && request.headers["Upload-Length"]
146
- validate_upload_length!
147
-
148
- info["Upload-Length"] = request.headers["Upload-Length"]
149
- info["Upload-Defer-Length"] = nil
150
- end
151
-
152
- input = get_input(info)
153
-
154
- validate_content_type!
155
- validate_upload_offset!(info)
156
- validate_content_length!(request.content_length.to_i, info) if request.content_length
116
+ storage.update_info(uid, info.to_h)
157
117
 
158
- begin
159
- if request.headers["Upload-Checksum"]
160
- input = Rack::RewindableInput.new(input) unless input.rewindable?
161
- validate_upload_checksum!(input)
118
+ if upload_data
119
+ uploaded = false
120
+
121
+ begin
122
+ upload_data!(uid, info)
123
+ uploaded = true
124
+ ensure
125
+ # When the data is rejected the client doesn't get the upload URL,
126
+ # so we remove the upload instead of leaving it behind.
127
+ unless uploaded
128
+ storage.delete_file(uid, info.to_h)
129
+ after_terminate(uid, info)
130
+ end
162
131
  end
163
132
 
164
- bytes_uploaded = storage.patch_file(uid, input, info.to_h)
165
- rescue Tus::MaxSizeExceeded
166
- validate_content_length!(input.pos, info)
167
- end
168
-
169
- info["Upload-Offset"] = (info.offset + bytes_uploaded).to_s
170
- info["Upload-Expires"] = (Time.now + expiration_time).httpdate
171
-
172
- if info.offset == info.length # last chunk
173
- storage.finalize_file(uid, info.to_h) if storage.respond_to?(:finalize_file)
174
-
175
- after_finish(uid, info)
133
+ storage.update_info(uid, info.to_h)
176
134
  end
177
135
 
178
- storage.update_info(uid, info.to_h)
179
136
  response.headers.update(info.headers)
180
137
 
181
- no_content!
138
+ # without the query string, which Rack::Request#url includes
139
+ file_url = "#{request.base_url}#{request.path.chomp("/")}/#{uid}"
140
+ created!(file_url)
182
141
  end
142
+ end
143
+
144
+ # Upload ids are generated by the server, so anything that isn't made of
145
+ # word characters (e.g. "..") cannot be an upload.
146
+ r.is(/(\w+)/) do |uid|
147
+ # OPTIONS /{uid}
148
+ r.options { server_info! }
183
149
 
184
150
  # GET /{uid}
185
151
  r.get do
152
+ info = read_info!(uid)
153
+
186
154
  validate_upload_finished!(info)
187
155
 
188
156
  if redirect_download
@@ -205,25 +173,128 @@ module Tus
205
173
  end
206
174
  end
207
175
 
208
- # DELETE /{uid}
209
- r.delete do
210
- storage.delete_file(uid, info.to_h)
176
+ # HEAD, PATCH and DELETE run while holding the upload's lock, and read
177
+ # the upload info only once they have it.
178
+ lock_upload(uid) do
179
+ info = read_info!(uid)
180
+
181
+ # HEAD /{uid}
182
+ r.head do
183
+ response.headers.update(info.headers)
184
+ response.headers["Cache-Control"] = "no-store"
185
+
186
+ no_content!
187
+ end
188
+
189
+ # PATCH /{uid}
190
+ r.patch do
191
+ error!(403, "Cannot modify a final upload") if info.final?
192
+
193
+ validate_content_type!
194
+ validate_upload_offset!(info)
195
+
196
+ error!(403, "Cannot modify completed upload") if info.offset == info.length
197
+
198
+ # The length of a deferred-length upload can also be set by a request
199
+ # without data, once the upload already has all of its data.
200
+ if info.defer_length? && request.headers["Upload-Length"]
201
+ validate_upload_length!
202
+
203
+ info["Upload-Length"] = request.headers["Upload-Length"]
204
+ info["Upload-Defer-Length"] = nil
205
+ end
211
206
 
212
- after_terminate(uid, info)
207
+ upload_data!(uid, info)
213
208
 
214
- no_content!
209
+ storage.update_info(uid, info.to_h)
210
+ response.headers.update(info.headers)
211
+
212
+ no_content!
213
+ end
214
+
215
+ # DELETE /{uid}
216
+ r.delete do
217
+ storage.delete_file(uid, info.to_h)
218
+
219
+ after_terminate(uid, info)
220
+
221
+ no_content!
222
+ end
223
+ end
224
+ end
225
+ end
226
+
227
+ # Yields while holding the lock for the given upload. If another request in
228
+ # this process holds the lock, it's asked to stop reading its request body
229
+ # and save what it received. Responds with 423 Locked if the lock isn't
230
+ # released within the lock timeout.
231
+ def lock_upload(uid, &block)
232
+ locker.lock(uid, timeout: lock_timeout, release: method(:interrupt_upload), &block)
233
+ rescue Tus::Locked
234
+ response.headers["Retry-After"] = "1"
235
+ error!(423, "Upload is locked by another request")
236
+ end
237
+
238
+ # Called when another request wants the lock this request holds. Makes the
239
+ # request body appear finished, so that the data received so far is saved
240
+ # and the lock is released.
241
+ def interrupt_upload
242
+ @upload_interrupted = true
243
+ @upload_input.interrupt! if @upload_input
244
+ end
245
+
246
+ def read_info!(uid)
247
+ Tus::Info.new(storage.read_info(uid))
248
+ rescue Tus::NotFound
249
+ error!(404, "Upload Not Found")
250
+ end
251
+
252
+ # Writes the request body to the upload at its current offset, then updates
253
+ # the offset and expiration, and finalizes the upload if it's complete.
254
+ # Shared by PATCH and creation-with-upload POST requests.
255
+ def upload_data!(uid, info)
256
+ input = get_input(info)
257
+
258
+ validate_content_length!(request.content_length.to_i, info) if request.content_length
259
+
260
+ begin
261
+ body = input
262
+
263
+ if request.headers["Upload-Checksum"]
264
+ body = Rack::RewindableInput.new(input) unless input.rewindable?
265
+ validate_upload_checksum!(body)
215
266
  end
267
+
268
+ bytes_uploaded = storage.patch_file(uid, body, info.to_h)
269
+ rescue Tus::MaxSizeExceeded
270
+ validate_content_length!(input.pos, info)
271
+ rescue Tus::NotFound
272
+ error!(404, "Upload Not Found")
216
273
  end
274
+
275
+ info["Upload-Offset"] = (info.offset + bytes_uploaded).to_s
276
+ info["Upload-Expires"] = (Time.now + expiration_time).httpdate
277
+
278
+ finish_upload!(uid, info) if info.offset == info.length # last chunk
279
+ end
280
+
281
+ def finish_upload!(uid, info)
282
+ storage.finalize_file(uid, info.to_h) if storage.respond_to?(:finalize_file)
283
+
284
+ after_finish(uid, info)
217
285
  end
218
286
 
219
287
  # Wraps the Rack input (request body) into a Tus::Input object, applying a
220
- # size limit if one exists.
288
+ # size limit if one exists. Rack 3 allows a request without a body to have
289
+ # no Rack input (e.g. over HTTP/2 on Falcon).
221
290
  def get_input(info)
222
291
  offset = info.offset
223
292
  total = info.length || max_size
224
293
  limit = total - offset if total
225
294
 
226
- Tus::Input.new(request.body, limit: limit)
295
+ @upload_input = Tus::Input.new(request.body || StringIO.new, limit: limit)
296
+ @upload_input.interrupt! if @upload_interrupted
297
+ @upload_input
227
298
  end
228
299
 
229
300
  def validate_content_type!
@@ -243,8 +314,7 @@ module Tus
243
314
  upload_length = request.headers["Upload-Length"]
244
315
 
245
316
  error!(400, "Missing Upload-Length header") if upload_length.to_s == ""
246
- error!(400, "Invalid Upload-Length header") if upload_length =~ /\D/
247
- error!(400, "Invalid Upload-Length header") if upload_length.to_i < 0
317
+ error!(400, "Invalid Upload-Length header") if upload_length.to_s =~ /\D/
248
318
 
249
319
  if max_size && upload_length.to_i > max_size
250
320
  error!(413, "Upload-Length header too large")
@@ -256,7 +326,6 @@ module Tus
256
326
 
257
327
  error!(400, "Missing Upload-Offset header") if upload_offset.to_s == ""
258
328
  error!(400, "Invalid Upload-Offset header") if upload_offset =~ /\D/
259
- error!(400, "Invalid Upload-Offset header") if upload_offset.to_i < 0
260
329
 
261
330
  if upload_offset.to_i != info.offset
262
331
  error!(409, "Upload-Offset header doesn't match current offset")
@@ -265,7 +334,6 @@ module Tus
265
334
 
266
335
  def validate_content_length!(size, info)
267
336
  if info.length
268
- error!(403, "Cannot modify completed upload") if info.offset == info.length
269
337
  error!(413, "Size of this chunk surpasses Upload-Length") if info.offset + size > info.length
270
338
  elsif max_size
271
339
  error!(413, "Size of this chunk surpasses Tus-Max-Size") if info.offset + size > max_size
@@ -279,14 +347,27 @@ module Tus
279
347
  def validate_upload_metadata!
280
348
  upload_metadata = request.headers["Upload-Metadata"]
281
349
 
282
- upload_metadata.split(",").each do |string|
350
+ keys = upload_metadata.split(",").map do |string|
283
351
  key, value = string.split(" ", 2)
284
352
 
285
353
  error!(400, "Invalid Upload-Metadata header") if key.nil?
286
- error!(400, "Invalid Upload-Metadata header") if key.ord > 127
287
- error!(400, "Invalid Upload-Metadata header") if key =~ /,| /
354
+ error!(400, "Invalid Upload-Metadata header") unless key.ascii_only?
288
355
 
289
356
  error!(400, "Invalid Upload-Metadata header") if value =~ /[^a-zA-Z0-9+\/=]/
357
+
358
+ key
359
+ end
360
+
361
+ error!(400, "Duplicate key in Upload-Metadata header") if keys.uniq.size != keys.size
362
+ end
363
+
364
+ def validate_upload_defer_length!
365
+ upload_defer_length = request.headers["Upload-Defer-Length"]
366
+
367
+ error!(400, "Invalid Upload-Defer-Length header") if upload_defer_length != "1"
368
+
369
+ if request.headers["Upload-Length"]
370
+ error!(400, "Upload-Length and Upload-Defer-Length headers can't both be set")
290
371
  end
291
372
  end
292
373
 
@@ -346,11 +427,7 @@ module Tus
346
427
  # Handles partial responses requested in the "Range" header. Implementation
347
428
  # is mostly copied from Rack::File.
348
429
  def handle_range_request!(length)
349
- if Rack.release >= "2.0"
350
- ranges = Rack::Utils.get_byte_ranges(request.headers["Range"], length)
351
- else
352
- ranges = Rack::Utils.byte_ranges(request.env, length)
353
- end
430
+ ranges = Rack::Utils.get_byte_ranges(request.headers["Range"], length)
354
431
 
355
432
  # we support ranged requests
356
433
  response.headers["Accept-Ranges"] = "bytes"
@@ -376,12 +453,6 @@ module Tus
376
453
 
377
454
  def redirect_download
378
455
  value = opts[:redirect_download]
379
-
380
- if opts[:download_url]
381
- value ||= opts[:download_url]
382
- warn "[TUS-RUBY-SERVER DEPRECATION] The :download_url option has been renamed to :redirect_download."
383
- end
384
-
385
456
  value = storage.method(:file_url) if value == true
386
457
 
387
458
  value
@@ -396,13 +467,25 @@ module Tus
396
467
 
397
468
  if request.options?
398
469
  response.headers["Access-Control-Allow-Methods"] = "POST, GET, HEAD, PATCH, DELETE, OPTIONS"
399
- response.headers["Access-Control-Allow-Headers"] = "Origin, X-Requested-With, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat"
470
+ response.headers["Access-Control-Allow-Headers"] = "Authorization, Origin, X-Requested-With, X-Request-ID, X-HTTP-Method-Override, Content-Type, Upload-Length, Upload-Offset, Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat, Upload-Checksum"
400
471
  response.headers["Access-Control-Max-Age"] = "86400"
401
472
  else
402
- response.headers["Access-Control-Expose-Headers"] = "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat"
473
+ response.headers["Access-Control-Expose-Headers"] = "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat, Upload-Expires, Tus-Checksum-Algorithm"
403
474
  end
404
475
  end
405
476
 
477
+ # Responds with the protocol versions, extensions and limits of the server.
478
+ def server_info!
479
+ response.headers.update(
480
+ "Tus-Version" => SUPPORTED_VERSIONS.join(","),
481
+ "Tus-Extension" => SUPPORTED_EXTENSIONS.join(","),
482
+ "Tus-Max-Size" => max_size.to_s,
483
+ "Tus-Checksum-Algorithm" => SUPPORTED_CHECKSUM_ALGORITHMS.join(","),
484
+ )
485
+
486
+ no_content!
487
+ end
488
+
406
489
  def no_content!
407
490
  response.status = 204
408
491
  request.halt
@@ -425,6 +508,14 @@ module Tus
425
508
  opts[:storage] || Tus::Storage::Filesystem.new("data")
426
509
  end
427
510
 
511
+ def locker
512
+ opts[:locker] || Tus::Locker.new
513
+ end
514
+
515
+ def lock_timeout
516
+ opts[:lock_timeout]
517
+ end
518
+
428
519
  def max_size
429
520
  opts[:max_size]
430
521
  end
@@ -432,9 +523,5 @@ module Tus
432
523
  def expiration_time
433
524
  opts[:expiration_time]
434
525
  end
435
-
436
- def expiration_interval
437
- opts[:expiration_interval]
438
- end
439
526
  end
440
527
  end
@@ -56,10 +56,24 @@ module Tus
56
56
  delete(part_uids)
57
57
  end
58
58
 
59
- # Appends data to the specified upload in a streaming fashion, and
59
+ # Writes data to the specified upload in a streaming fashion, and
60
60
  # returns the number of bytes it managed to save.
61
+ #
62
+ # Data is written at the upload's offset rather than appended, so a
63
+ # retried request that overlaps an earlier one writes the same bytes to
64
+ # the same place instead of duplicating them. Without an offset in the
65
+ # info, data is appended.
66
+ #
67
+ # Raises Tus::NotFound if the upload was deleted.
61
68
  def patch_file(uid, input, info = {})
62
- file_path(uid).open("ab") { |file| IO.copy_stream(input, file) }
69
+ file_path(uid).open("r+b") do |file|
70
+ offset = info["Upload-Offset"] ? Integer(info["Upload-Offset"]) : file.size
71
+ file.seek(offset)
72
+
73
+ IO.copy_stream(input, file)
74
+ end
75
+ rescue Errno::ENOENT
76
+ raise Tus::NotFound
63
77
  end
64
78
 
65
79
  # Returns info of the specified upload. Raises Tus::NotFound if the upload
@@ -70,9 +84,15 @@ module Tus
70
84
  JSON.parse(info_path(uid).binread)
71
85
  end
72
86
 
73
- # Updates info of the specified upload.
87
+ # Updates info of the specified upload. The info file is replaced
88
+ # atomically, so concurrent readers never see a partially written file.
74
89
  def update_info(uid, info)
75
- info_path(uid).binwrite(JSON.generate(info))
90
+ temp_path = directory.join("#{uid}.info.tmp")
91
+ temp_path.binwrite(JSON.generate(info))
92
+ temp_path.chmod(@permissions)
93
+ temp_path.rename(info_path(uid))
94
+ ensure
95
+ temp_path.unlink if temp_path && temp_path.exist?
76
96
  end
77
97
 
78
98
  # Returns a Tus::Response object through which data of the specified
@@ -107,7 +127,7 @@ module Tus
107
127
  # Deletes data and info files of uploads older than the specified date.
108
128
  def expire_files(expiration_date)
109
129
  uids = directory.children
110
- .select { |pathname| pathname.mtime <= expiration_date }
130
+ .select { |pathname| pathname.file? && pathname.mtime <= expiration_date }
111
131
  .map { |pathname| pathname.basename(".*").to_s }
112
132
 
113
133
  delete(uids)