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