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