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