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