8784: Fix test for latest firefox.
[arvados.git] / services / api / app / models / collection.rb
1 require 'arvados/keep'
2 require 'sweep_trashed_collections'
3
4 class Collection < ArvadosModel
5   extend CurrentApiClient
6   extend DbCurrentTime
7   include HasUuid
8   include KindAndEtag
9   include CommonApiTemplate
10
11   serialize :properties, Hash
12
13   before_validation :set_validation_timestamp
14   before_validation :default_empty_manifest
15   before_validation :check_encoding
16   before_validation :check_manifest_validity
17   before_validation :check_signatures
18   before_validation :strip_signatures_and_update_replication_confirmed
19   before_validation :ensure_trash_at_not_in_past
20   before_validation :sync_trash_state
21   before_validation :default_trash_interval
22   validate :ensure_pdh_matches_manifest_text
23   validate :validate_trash_and_delete_timing
24   before_save :set_file_names
25
26   # Query only untrashed collections by default.
27   default_scope { where("is_trashed = false") }
28
29   api_accessible :user, extend: :common do |t|
30     t.add :name
31     t.add :description
32     t.add :properties
33     t.add :portable_data_hash
34     t.add :signed_manifest_text, as: :manifest_text
35     t.add :manifest_text, as: :unsigned_manifest_text
36     t.add :replication_desired
37     t.add :replication_confirmed
38     t.add :replication_confirmed_at
39     t.add :delete_at
40     t.add :trash_at
41     t.add :is_trashed
42   end
43
44   after_initialize do
45     @signatures_checked = false
46     @computed_pdh_for_manifest_text = false
47   end
48
49   def self.attributes_required_columns
50     super.merge(
51                 # If we don't list manifest_text explicitly, the
52                 # params[:select] code gets confused by the way we
53                 # expose signed_manifest_text as manifest_text in the
54                 # API response, and never let clients select the
55                 # manifest_text column.
56                 #
57                 # We need trash_at and is_trashed to determine the
58                 # correct timestamp in signed_manifest_text.
59                 'manifest_text' => ['manifest_text', 'trash_at', 'is_trashed'],
60                 'unsigned_manifest_text' => ['manifest_text'],
61                 )
62   end
63
64   def self.ignored_select_attributes
65     super + ["updated_at", "file_names"]
66   end
67
68   def self.limit_index_columns_read
69     ["manifest_text"]
70   end
71
72   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
73   def check_signatures
74     return false if self.manifest_text.nil?
75
76     return true if current_user.andand.is_admin
77
78     # Provided the manifest_text hasn't changed materially since an
79     # earlier validation, it's safe to pass this validation on
80     # subsequent passes without checking any signatures. This is
81     # important because the signatures have probably been stripped off
82     # by the time we get to a second validation pass!
83     if @signatures_checked && @signatures_checked == computed_pdh
84       return true
85     end
86
87     if self.manifest_text_changed?
88       # Check permissions on the collection manifest.
89       # If any signature cannot be verified, raise PermissionDeniedError
90       # which will return 403 Permission denied to the client.
91       api_token = current_api_client_authorization.andand.api_token
92       signing_opts = {
93         api_token: api_token,
94         now: @validation_timestamp.to_i,
95       }
96       self.manifest_text.each_line do |entry|
97         entry.split.each do |tok|
98           if tok == '.' or tok.starts_with? './'
99             # Stream name token.
100           elsif tok =~ FILE_TOKEN
101             # This is a filename token, not a blob locator. Note that we
102             # keep checking tokens after this, even though manifest
103             # format dictates that all subsequent tokens will also be
104             # filenames. Safety first!
105           elsif Blob.verify_signature tok, signing_opts
106             # OK.
107           elsif Keep::Locator.parse(tok).andand.signature
108             # Signature provided, but verify_signature did not like it.
109             logger.warn "Invalid signature on locator #{tok}"
110             raise ArvadosModel::PermissionDeniedError
111           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
112             # No signature provided, but we are running in insecure mode.
113             logger.debug "Missing signature on locator #{tok} ignored"
114           elsif Blob.new(tok).empty?
115             # No signature provided -- but no data to protect, either.
116           else
117             logger.warn "Missing signature on locator #{tok}"
118             raise ArvadosModel::PermissionDeniedError
119           end
120         end
121       end
122     end
123     @signatures_checked = computed_pdh
124   end
125
126   def strip_signatures_and_update_replication_confirmed
127     if self.manifest_text_changed?
128       in_old_manifest = {}
129       if not self.replication_confirmed.nil?
130         self.class.each_manifest_locator(manifest_text_was) do |match|
131           in_old_manifest[match[1]] = true
132         end
133       end
134
135       stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
136         if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
137           # If the new manifest_text contains locators whose hashes
138           # weren't in the old manifest_text, storage replication is no
139           # longer confirmed.
140           self.replication_confirmed_at = nil
141           self.replication_confirmed = nil
142         end
143
144         # Return the locator with all permission signatures removed,
145         # but otherwise intact.
146         match[0].gsub(/\+A[^+]*/, '')
147       end
148
149       if @computed_pdh_for_manifest_text == manifest_text
150         # If the cached PDH was valid before stripping, it is still
151         # valid after stripping.
152         @computed_pdh_for_manifest_text = stripped_manifest.dup
153       end
154
155       self[:manifest_text] = stripped_manifest
156     end
157     true
158   end
159
160   def ensure_pdh_matches_manifest_text
161     if not manifest_text_changed? and not portable_data_hash_changed?
162       true
163     elsif portable_data_hash.nil? or not portable_data_hash_changed?
164       self.portable_data_hash = computed_pdh
165     elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
166       errors.add(:portable_data_hash, "is not a valid locator")
167       false
168     elsif portable_data_hash[0..31] != computed_pdh[0..31]
169       errors.add(:portable_data_hash,
170                  "'#{portable_data_hash}' does not match computed hash '#{computed_pdh}'")
171       false
172     else
173       # Ignore the client-provided size part: always store
174       # computed_pdh in the database.
175       self.portable_data_hash = computed_pdh
176     end
177   end
178
179   def set_file_names
180     if self.manifest_text_changed?
181       self.file_names = manifest_files
182     end
183     true
184   end
185
186   def manifest_files
187     names = ''
188     if self.manifest_text
189       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
190         names << name.first.gsub('\040',' ') + "\n"
191         break if names.length > 2**12
192       end
193     end
194
195     if self.manifest_text and names.length < 2**12
196       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
197         names << stream_name.first.gsub('\040',' ') + "\n"
198         break if names.length > 2**12
199       end
200     end
201
202     names[0,2**12]
203   end
204
205   def default_empty_manifest
206     self.manifest_text ||= ''
207   end
208
209   def check_encoding
210     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
211       true
212     else
213       begin
214         # If Ruby thinks the encoding is something else, like 7-bit
215         # ASCII, but its stored bytes are equal to the (valid) UTF-8
216         # encoding of the same string, we declare it to be a UTF-8
217         # string.
218         utf8 = manifest_text
219         utf8.force_encoding Encoding::UTF_8
220         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
221           self.manifest_text = utf8
222           return true
223         end
224       rescue
225       end
226       errors.add :manifest_text, "must use UTF-8 encoding"
227       false
228     end
229   end
230
231   def check_manifest_validity
232     begin
233       Keep::Manifest.validate! manifest_text
234       true
235     rescue ArgumentError => e
236       errors.add :manifest_text, e.message
237       false
238     end
239   end
240
241   def signed_manifest_text
242     if !has_attribute? :manifest_text
243       return nil
244     elsif is_trashed
245       return manifest_text
246     else
247       token = current_api_client_authorization.andand.api_token
248       exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
249              trash_at].compact.map(&:to_i).min
250       self.class.sign_manifest manifest_text, token, exp
251     end
252   end
253
254   def self.sign_manifest manifest, token, exp=nil
255     if exp.nil?
256       exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
257     end
258     signing_opts = {
259       api_token: token,
260       expire: exp,
261     }
262     m = munge_manifest_locators(manifest) do |match|
263       Blob.sign_locator(match[0], signing_opts)
264     end
265     return m
266   end
267
268   def self.munge_manifest_locators manifest
269     # Given a manifest text and a block, yield the regexp MatchData
270     # for each locator. Return a new manifest in which each locator
271     # has been replaced by the block's return value.
272     return nil if !manifest
273     return '' if manifest == ''
274
275     new_lines = []
276     manifest.each_line do |line|
277       line.rstrip!
278       new_words = []
279       line.split(' ').each do |word|
280         if new_words.empty?
281           new_words << word
282         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
283           new_words << yield(match)
284         else
285           new_words << word
286         end
287       end
288       new_lines << new_words.join(' ')
289     end
290     new_lines.join("\n") + "\n"
291   end
292
293   def self.each_manifest_locator manifest
294     # Given a manifest text and a block, yield the regexp match object
295     # for each locator.
296     manifest.each_line do |line|
297       # line will have a trailing newline, but the last token is never
298       # a locator, so it's harmless here.
299       line.split(' ').each do |word|
300         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
301           yield(match)
302         end
303       end
304     end
305   end
306
307   def self.normalize_uuid uuid
308     hash_part = nil
309     size_part = nil
310     uuid.split('+').each do |token|
311       if token.match(/^[0-9a-f]{32,}$/)
312         raise "uuid #{uuid} has multiple hash parts" if hash_part
313         hash_part = token
314       elsif token.match(/^\d+$/)
315         raise "uuid #{uuid} has multiple size parts" if size_part
316         size_part = token
317       end
318     end
319     raise "uuid #{uuid} has no hash part" if !hash_part
320     [hash_part, size_part].compact.join '+'
321   end
322
323   def self.get_compatible_images(readers, pattern, collections)
324     if collections.empty?
325       return []
326     end
327
328     migrations = Hash[
329       Link.where('tail_uuid in (?) AND link_class=? AND links.owner_uuid=?',
330                  collections.map(&:portable_data_hash),
331                  'docker_image_migration',
332                  system_user_uuid).
333       order('links.created_at asc').
334       map { |l|
335         [l.tail_uuid, l.head_uuid]
336       }]
337
338     migrated_collections = Hash[
339       Collection.readable_by(*readers).
340       where('portable_data_hash in (?)', migrations.values).
341       map { |c|
342         [c.portable_data_hash, c]
343       }]
344
345     collections.map { |c|
346       # Check if the listed image is compatible first, if not, then try the
347       # migration link.
348       manifest = Keep::Manifest.new(c.manifest_text)
349       if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
350         c
351       elsif m = migrated_collections[migrations[c.portable_data_hash]]
352         manifest = Keep::Manifest.new(m.manifest_text)
353         if manifest.exact_file_count?(1) and manifest.files[0][1] =~ pattern
354           m
355         end
356       end
357     }.compact
358   end
359
360   # Resolve a Docker repo+tag, hash, or collection PDH to an array of
361   # Collection objects, sorted by timestamp starting with the most recent
362   # match.
363   #
364   # If filter_compatible_format is true (the default), only return image
365   # collections which are support by the installation as indicated by
366   # Rails.configuration.docker_image_formats.  Will follow
367   # 'docker_image_migration' links if search_term resolves to an incompatible
368   # image, but an equivalent compatible image is available.
369   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil, filter_compatible_format: true)
370     readers ||= [Thread.current[:user]]
371     base_search = Link.
372       readable_by(*readers).
373       readable_by(*readers, table_name: "collections").
374       joins("JOIN collections ON links.head_uuid = collections.uuid").
375       order("links.created_at DESC")
376
377     if (Rails.configuration.docker_image_formats.include? 'v1' and
378         Rails.configuration.docker_image_formats.include? 'v2') or filter_compatible_format == false
379       pattern = /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/
380     elsif Rails.configuration.docker_image_formats.include? 'v2'
381       pattern = /^(sha256:)[0-9A-Fa-f]{64}\.tar$/
382     elsif Rails.configuration.docker_image_formats.include? 'v1'
383       pattern = /^[0-9A-Fa-f]{64}\.tar$/
384     else
385       raise "Unrecognized configuration for docker_image_formats #{Rails.configuration.docker_image_formats}"
386     end
387
388     # If the search term is a Collection locator that contains one file
389     # that looks like a Docker image, return it.
390     if loc = Keep::Locator.parse(search_term)
391       loc.strip_hints!
392       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1)
393       return get_compatible_images(readers, pattern, coll_match)
394     end
395
396     if search_tag.nil? and (n = search_term.index(":"))
397       search_tag = search_term[n+1..-1]
398       search_term = search_term[0..n-1]
399     end
400
401     # Find Collections with matching Docker image repository+tag pairs.
402     matches = base_search.
403       where(link_class: "docker_image_repo+tag",
404             name: "#{search_term}:#{search_tag || 'latest'}")
405
406     # If that didn't work, find Collections with matching Docker image hashes.
407     if matches.empty?
408       matches = base_search.
409         where("link_class = ? and links.name LIKE ?",
410               "docker_image_hash", "#{search_term}%")
411     end
412
413     # Generate an order key for each result.  We want to order the results
414     # so that anything with an image timestamp is considered more recent than
415     # anything without; then we use the link's created_at as a tiebreaker.
416     uuid_timestamps = {}
417     matches.each do |link|
418       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
419        -link.created_at.to_i]
420      end
421
422     sorted = Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c|
423       uuid_timestamps[c.uuid]
424     }
425     compatible = get_compatible_images(readers, pattern, sorted)
426     if sorted.length > 0 and compatible.empty?
427       raise ArvadosModel::UnresolvableContainerError.new "Matching Docker image is incompatible with 'docker_image_formats' configuration."
428     end
429     compatible
430   end
431
432   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
433     find_all_for_docker_image(search_term, search_tag, readers).first
434   end
435
436   def self.searchable_columns operator
437     super - ["manifest_text"]
438   end
439
440   def self.full_text_searchable_columns
441     super - ["manifest_text"]
442   end
443
444   def self.where *args
445     SweepTrashedCollections.sweep_if_stale
446     super
447   end
448
449   protected
450   def portable_manifest_text
451     self.class.munge_manifest_locators(manifest_text) do |match|
452       if match[2] # size
453         match[1] + match[2]
454       else
455         match[1]
456       end
457     end
458   end
459
460   def compute_pdh
461     portable_manifest = portable_manifest_text
462     (Digest::MD5.hexdigest(portable_manifest) +
463      '+' +
464      portable_manifest.bytesize.to_s)
465   end
466
467   def computed_pdh
468     if @computed_pdh_for_manifest_text == manifest_text
469       return @computed_pdh
470     end
471     @computed_pdh = compute_pdh
472     @computed_pdh_for_manifest_text = manifest_text.dup
473     @computed_pdh
474   end
475
476   def ensure_permission_to_save
477     if (not current_user.andand.is_admin and
478         (replication_confirmed_at_changed? or replication_confirmed_changed?) and
479         not (replication_confirmed_at.nil? and replication_confirmed.nil?))
480       raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
481     end
482     super
483   end
484
485   # Use a single timestamp for all validations, even though each
486   # validation runs at a different time.
487   def set_validation_timestamp
488     @validation_timestamp = db_current_time
489   end
490
491   # If trash_at is being changed to a time in the past, change it to
492   # now. This allows clients to say "expires {client-current-time}"
493   # without failing due to clock skew, while avoiding odd log entries
494   # like "expiry date changed to {1 year ago}".
495   def ensure_trash_at_not_in_past
496     if trash_at_changed? && trash_at
497       self.trash_at = [@validation_timestamp, trash_at].max
498     end
499   end
500
501   # Caller can move into/out of trash by setting/clearing is_trashed
502   # -- however, if the caller also changes trash_at, then any changes
503   # to is_trashed are ignored.
504   def sync_trash_state
505     if is_trashed_changed? && !trash_at_changed?
506       if is_trashed
507         self.trash_at = @validation_timestamp
508       else
509         self.trash_at = nil
510         self.delete_at = nil
511       end
512     end
513     self.is_trashed = trash_at && trash_at <= @validation_timestamp || false
514     true
515   end
516
517   def default_trash_interval
518     if trash_at_changed? && !delete_at_changed?
519       # If trash_at is updated without touching delete_at,
520       # automatically update delete_at to a sensible value.
521       if trash_at.nil?
522         self.delete_at = nil
523       else
524         self.delete_at = trash_at + Rails.configuration.default_trash_lifetime.seconds
525       end
526     elsif !trash_at || !delete_at || trash_at > delete_at
527       # Not trash, or bogus arguments? Just validate in
528       # validate_trash_and_delete_timing.
529     elsif delete_at_changed? && delete_at >= trash_at
530       # Fix delete_at if needed, so it's not earlier than the expiry
531       # time on any permission tokens that might have been given out.
532
533       # In any case there are no signatures expiring after now+TTL.
534       # Also, if the existing trash_at time has already passed, we
535       # know we haven't given out any signatures since then.
536       earliest_delete = [
537         @validation_timestamp,
538         trash_at_was,
539       ].compact.min + Rails.configuration.blob_signature_ttl.seconds
540
541       # The previous value of delete_at is also an upper bound on the
542       # longest-lived permission token. For example, if TTL=14,
543       # trash_at_was=now-7, delete_at_was=now+7, then it is safe to
544       # set trash_at=now+6, delete_at=now+8.
545       earliest_delete = [earliest_delete, delete_at_was].compact.min
546
547       # If delete_at is too soon, use the earliest possible time.
548       if delete_at < earliest_delete
549         self.delete_at = earliest_delete
550       end
551     end
552   end
553
554   def validate_trash_and_delete_timing
555     if trash_at.nil? != delete_at.nil?
556       errors.add :delete_at, "must be set if trash_at is set, and must be nil otherwise"
557     elsif delete_at && delete_at < trash_at
558       errors.add :delete_at, "must not be earlier than trash_at"
559     end
560     true
561   end
562 end