11002: Merge branch 'master' into 11002-arvput-crash-fix
[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   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
69   def check_signatures
70     return false if self.manifest_text.nil?
71
72     return true if current_user.andand.is_admin
73
74     # Provided the manifest_text hasn't changed materially since an
75     # earlier validation, it's safe to pass this validation on
76     # subsequent passes without checking any signatures. This is
77     # important because the signatures have probably been stripped off
78     # by the time we get to a second validation pass!
79     if @signatures_checked && @signatures_checked == computed_pdh
80       return true
81     end
82
83     if self.manifest_text_changed?
84       # Check permissions on the collection manifest.
85       # If any signature cannot be verified, raise PermissionDeniedError
86       # which will return 403 Permission denied to the client.
87       api_token = current_api_client_authorization.andand.api_token
88       signing_opts = {
89         api_token: api_token,
90         now: @validation_timestamp.to_i,
91       }
92       self.manifest_text.each_line do |entry|
93         entry.split.each do |tok|
94           if tok == '.' or tok.starts_with? './'
95             # Stream name token.
96           elsif tok =~ FILE_TOKEN
97             # This is a filename token, not a blob locator. Note that we
98             # keep checking tokens after this, even though manifest
99             # format dictates that all subsequent tokens will also be
100             # filenames. Safety first!
101           elsif Blob.verify_signature tok, signing_opts
102             # OK.
103           elsif Keep::Locator.parse(tok).andand.signature
104             # Signature provided, but verify_signature did not like it.
105             logger.warn "Invalid signature on locator #{tok}"
106             raise ArvadosModel::PermissionDeniedError
107           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
108             # No signature provided, but we are running in insecure mode.
109             logger.debug "Missing signature on locator #{tok} ignored"
110           elsif Blob.new(tok).empty?
111             # No signature provided -- but no data to protect, either.
112           else
113             logger.warn "Missing signature on locator #{tok}"
114             raise ArvadosModel::PermissionDeniedError
115           end
116         end
117       end
118     end
119     @signatures_checked = computed_pdh
120   end
121
122   def strip_signatures_and_update_replication_confirmed
123     if self.manifest_text_changed?
124       in_old_manifest = {}
125       if not self.replication_confirmed.nil?
126         self.class.each_manifest_locator(manifest_text_was) do |match|
127           in_old_manifest[match[1]] = true
128         end
129       end
130
131       stripped_manifest = self.class.munge_manifest_locators(manifest_text) do |match|
132         if not self.replication_confirmed.nil? and not in_old_manifest[match[1]]
133           # If the new manifest_text contains locators whose hashes
134           # weren't in the old manifest_text, storage replication is no
135           # longer confirmed.
136           self.replication_confirmed_at = nil
137           self.replication_confirmed = nil
138         end
139
140         # Return the locator with all permission signatures removed,
141         # but otherwise intact.
142         match[0].gsub(/\+A[^+]*/, '')
143       end
144
145       if @computed_pdh_for_manifest_text == manifest_text
146         # If the cached PDH was valid before stripping, it is still
147         # valid after stripping.
148         @computed_pdh_for_manifest_text = stripped_manifest.dup
149       end
150
151       self[:manifest_text] = stripped_manifest
152     end
153     true
154   end
155
156   def ensure_pdh_matches_manifest_text
157     if not manifest_text_changed? and not portable_data_hash_changed?
158       true
159     elsif portable_data_hash.nil? or not portable_data_hash_changed?
160       self.portable_data_hash = computed_pdh
161     elsif portable_data_hash !~ Keep::Locator::LOCATOR_REGEXP
162       errors.add(:portable_data_hash, "is not a valid locator")
163       false
164     elsif portable_data_hash[0..31] != computed_pdh[0..31]
165       errors.add(:portable_data_hash,
166                  "does not match computed hash #{computed_pdh}")
167       false
168     else
169       # Ignore the client-provided size part: always store
170       # computed_pdh in the database.
171       self.portable_data_hash = computed_pdh
172     end
173   end
174
175   def set_file_names
176     if self.manifest_text_changed?
177       self.file_names = manifest_files
178     end
179     true
180   end
181
182   def manifest_files
183     names = ''
184     if self.manifest_text
185       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
186         names << name.first.gsub('\040',' ') + "\n"
187         break if names.length > 2**12
188       end
189     end
190
191     if self.manifest_text and names.length < 2**12
192       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
193         names << stream_name.first.gsub('\040',' ') + "\n"
194         break if names.length > 2**12
195       end
196     end
197
198     names[0,2**12]
199   end
200
201   def default_empty_manifest
202     self.manifest_text ||= ''
203   end
204
205   def check_encoding
206     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
207       true
208     else
209       begin
210         # If Ruby thinks the encoding is something else, like 7-bit
211         # ASCII, but its stored bytes are equal to the (valid) UTF-8
212         # encoding of the same string, we declare it to be a UTF-8
213         # string.
214         utf8 = manifest_text
215         utf8.force_encoding Encoding::UTF_8
216         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
217           self.manifest_text = utf8
218           return true
219         end
220       rescue
221       end
222       errors.add :manifest_text, "must use UTF-8 encoding"
223       false
224     end
225   end
226
227   def check_manifest_validity
228     begin
229       Keep::Manifest.validate! manifest_text
230       true
231     rescue ArgumentError => e
232       errors.add :manifest_text, e.message
233       false
234     end
235   end
236
237   def signed_manifest_text
238     if !has_attribute? :manifest_text
239       return nil
240     elsif is_trashed
241       return manifest_text
242     else
243       token = current_api_client_authorization.andand.api_token
244       exp = [db_current_time.to_i + Rails.configuration.blob_signature_ttl,
245              trash_at].compact.map(&:to_i).min
246       self.class.sign_manifest manifest_text, token, exp
247     end
248   end
249
250   def self.sign_manifest manifest, token, exp=nil
251     if exp.nil?
252       exp = db_current_time.to_i + Rails.configuration.blob_signature_ttl
253     end
254     signing_opts = {
255       api_token: token,
256       expire: exp,
257     }
258     m = munge_manifest_locators(manifest) do |match|
259       Blob.sign_locator(match[0], signing_opts)
260     end
261     return m
262   end
263
264   def self.munge_manifest_locators manifest
265     # Given a manifest text and a block, yield the regexp MatchData
266     # for each locator. Return a new manifest in which each locator
267     # has been replaced by the block's return value.
268     return nil if !manifest
269     return '' if manifest == ''
270
271     new_lines = []
272     manifest.each_line do |line|
273       line.rstrip!
274       new_words = []
275       line.split(' ').each do |word|
276         if new_words.empty?
277           new_words << word
278         elsif match = Keep::Locator::LOCATOR_REGEXP.match(word)
279           new_words << yield(match)
280         else
281           new_words << word
282         end
283       end
284       new_lines << new_words.join(' ')
285     end
286     new_lines.join("\n") + "\n"
287   end
288
289   def self.each_manifest_locator manifest
290     # Given a manifest text and a block, yield the regexp match object
291     # for each locator.
292     manifest.each_line do |line|
293       # line will have a trailing newline, but the last token is never
294       # a locator, so it's harmless here.
295       line.split(' ').each do |word|
296         if match = Keep::Locator::LOCATOR_REGEXP.match(word)
297           yield(match)
298         end
299       end
300     end
301   end
302
303   def self.normalize_uuid uuid
304     hash_part = nil
305     size_part = nil
306     uuid.split('+').each do |token|
307       if token.match(/^[0-9a-f]{32,}$/)
308         raise "uuid #{uuid} has multiple hash parts" if hash_part
309         hash_part = token
310       elsif token.match(/^\d+$/)
311         raise "uuid #{uuid} has multiple size parts" if size_part
312         size_part = token
313       end
314     end
315     raise "uuid #{uuid} has no hash part" if !hash_part
316     [hash_part, size_part].compact.join '+'
317   end
318
319   # Return array of Collection objects
320   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
321     readers ||= [Thread.current[:user]]
322     base_search = Link.
323       readable_by(*readers).
324       readable_by(*readers, table_name: "collections").
325       joins("JOIN collections ON links.head_uuid = collections.uuid").
326       order("links.created_at DESC")
327
328     # If the search term is a Collection locator that contains one file
329     # that looks like a Docker image, return it.
330     if loc = Keep::Locator.parse(search_term)
331       loc.strip_hints!
332       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
333       if coll_match
334         # Check if the Collection contains exactly one file whose name
335         # looks like a saved Docker image.
336         manifest = Keep::Manifest.new(coll_match.manifest_text)
337         if manifest.exact_file_count?(1) and
338             (manifest.files[0][1] =~ /^(sha256:)?[0-9A-Fa-f]{64}\.tar$/)
339           return [coll_match]
340         end
341       end
342     end
343
344     if search_tag.nil? and (n = search_term.index(":"))
345       search_tag = search_term[n+1..-1]
346       search_term = search_term[0..n-1]
347     end
348
349     # Find Collections with matching Docker image repository+tag pairs.
350     matches = base_search.
351       where(link_class: "docker_image_repo+tag",
352             name: "#{search_term}:#{search_tag || 'latest'}")
353
354     # If that didn't work, find Collections with matching Docker image hashes.
355     if matches.empty?
356       matches = base_search.
357         where("link_class = ? and links.name LIKE ?",
358               "docker_image_hash", "#{search_term}%")
359     end
360
361     # Generate an order key for each result.  We want to order the results
362     # so that anything with an image timestamp is considered more recent than
363     # anything without; then we use the link's created_at as a tiebreaker.
364     uuid_timestamps = {}
365     matches.all.map do |link|
366       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
367        -link.created_at.to_i]
368     end
369     Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
370   end
371
372   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
373     find_all_for_docker_image(search_term, search_tag, readers).first
374   end
375
376   # If the given pdh is an old-format docker image, old-format images
377   # aren't supported by the compute nodes according to site config,
378   # and a migrated new-format image is available, return the migrated
379   # image's pdh. Otherwise, just return pdh.
380   def self.docker_migration_pdh(read_users, pdh)
381     if Rails.configuration.docker_image_formats.include?('v1')
382       return pdh
383     end
384     Collection.readable_by(*read_users).
385       joins('INNER JOIN links ON head_uuid=portable_data_hash').
386       where('tail_uuid=? AND link_class=? AND links.owner_uuid=?',
387             pdh, 'docker_image_migration', system_user_uuid).
388       order('links.created_at desc').
389       select('portable_data_hash').
390       first.andand.portable_data_hash || pdh
391   end
392
393   def self.searchable_columns operator
394     super - ["manifest_text"]
395   end
396
397   def self.full_text_searchable_columns
398     super - ["manifest_text"]
399   end
400
401   def self.where *args
402     SweepTrashedCollections.sweep_if_stale
403     super
404   end
405
406   protected
407   def portable_manifest_text
408     self.class.munge_manifest_locators(manifest_text) do |match|
409       if match[2] # size
410         match[1] + match[2]
411       else
412         match[1]
413       end
414     end
415   end
416
417   def compute_pdh
418     portable_manifest = portable_manifest_text
419     (Digest::MD5.hexdigest(portable_manifest) +
420      '+' +
421      portable_manifest.bytesize.to_s)
422   end
423
424   def computed_pdh
425     if @computed_pdh_for_manifest_text == manifest_text
426       return @computed_pdh
427     end
428     @computed_pdh = compute_pdh
429     @computed_pdh_for_manifest_text = manifest_text.dup
430     @computed_pdh
431   end
432
433   def ensure_permission_to_save
434     if (not current_user.andand.is_admin and
435         (replication_confirmed_at_changed? or replication_confirmed_changed?) and
436         not (replication_confirmed_at.nil? and replication_confirmed.nil?))
437       raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
438     end
439     super
440   end
441
442   # Use a single timestamp for all validations, even though each
443   # validation runs at a different time.
444   def set_validation_timestamp
445     @validation_timestamp = db_current_time
446   end
447
448   # If trash_at is being changed to a time in the past, change it to
449   # now. This allows clients to say "expires {client-current-time}"
450   # without failing due to clock skew, while avoiding odd log entries
451   # like "expiry date changed to {1 year ago}".
452   def ensure_trash_at_not_in_past
453     if trash_at_changed? && trash_at
454       self.trash_at = [@validation_timestamp, trash_at].max
455     end
456   end
457
458   # Caller can move into/out of trash by setting/clearing is_trashed
459   # -- however, if the caller also changes trash_at, then any changes
460   # to is_trashed are ignored.
461   def sync_trash_state
462     if is_trashed_changed? && !trash_at_changed?
463       if is_trashed
464         self.trash_at = @validation_timestamp
465       else
466         self.trash_at = nil
467         self.delete_at = nil
468       end
469     end
470     self.is_trashed = trash_at && trash_at <= @validation_timestamp || false
471     true
472   end
473
474   # If trash_at is updated without touching delete_at, automatically
475   # update delete_at to a sensible value.
476   def default_trash_interval
477     if trash_at_changed? && !delete_at_changed?
478       if trash_at.nil?
479         self.delete_at = nil
480       else
481         self.delete_at = trash_at + Rails.configuration.default_trash_lifetime.seconds
482       end
483     end
484   end
485
486   def validate_trash_and_delete_timing
487     if trash_at.nil? != delete_at.nil?
488       errors.add :delete_at, "must be set if trash_at is set, and must be nil otherwise"
489     end
490
491     earliest_delete = ([@validation_timestamp, trash_at_was].compact.min +
492                        Rails.configuration.blob_signature_ttl.seconds)
493     if delete_at && delete_at < earliest_delete
494       errors.add :delete_at, "#{delete_at} is too soon: earliest allowed is #{earliest_delete}"
495     end
496
497     if delete_at && delete_at < trash_at
498       errors.add :delete_at, "must not be earlier than trash_at"
499     end
500
501     true
502   end
503 end