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