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