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