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