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