6203: compute_pdh, computed_pdh etc etc etc confusion. clean up to make it easier...
[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   before_validation :set_portable_data_hash
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   LOCATOR_REGEXP = /^([[:xdigit:]]{32})(\+([[:digit:]]+))?(\+([[:upper:]][[:alnum:]+@_-]*))?$/
33
34   def self.attributes_required_columns
35     super.merge(
36                 # If we don't list manifest_text explicitly, the
37                 # params[:select] code gets confused by the way we
38                 # expose signed_manifest_text as manifest_text in the
39                 # API response, and never let clients select the
40                 # manifest_text column.
41                 'manifest_text' => ['manifest_text'],
42                 )
43   end
44
45   FILE_TOKEN = /^[[:digit:]]+:[[:digit:]]+:/
46   def check_signatures
47     return false if self.manifest_text.nil?
48
49     return true if current_user.andand.is_admin
50
51     # Provided the manifest_text hasn't changed materially since an
52     # earlier validation, it's safe to pass this validation on
53     # subsequent passes without checking any signatures. This is
54     # important because the signatures have probably been stripped off
55     # by the time we get to a second validation pass!
56     return true if @signatures_checked and @signatures_checked == computed_pdh
57
58     if self.manifest_text_changed?
59       # Check permissions on the collection manifest.
60       # If any signature cannot be verified, raise PermissionDeniedError
61       # which will return 403 Permission denied to the client.
62       api_token = current_api_client_authorization.andand.api_token
63       signing_opts = {
64         api_token: api_token,
65         now: db_current_time.to_i,
66       }
67       self.manifest_text.lines.each do |entry|
68         entry.split[1..-1].each do |tok|
69           if 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       self.class.munge_manifest_locators!(manifest_text_was) do |match|
99         in_old_manifest[match[1]] = true
100       end
101
102       cleared_replication_confirmed = false
103
104       # Remove any permission signatures from the manifest.
105       self[:manifest_text] = self.class.munge_manifest_locators!(self[:manifest_text]) do |match|
106         if not cleared_replication_confirmed  and not in_old_manifest[match[1]]
107           self.replication_confirmed_at = nil
108           self.replication_confirmed = nil
109           cleared_replication_confirmed = true
110         end
111         self.class.locator_without_signature(match)
112       end
113     end
114     @computed_pdh_for_manifest_text = self[:manifest_text] if @computed_pdh_for_manifest_text
115     true
116   end
117
118   def self.locator_without_signature match
119     without_signature = match[1]
120     without_signature += match[2] if match[2]
121     if match[4]
122       hints = match[4].split('+').reject { |hint| hint.start_with?("A") }
123       without_signature += hints.join('+')
124     end
125     without_signature
126   end
127
128   def set_portable_data_hash
129     if (portable_data_hash.nil? or
130         portable_data_hash == "" or
131         (manifest_text_changed? and !portable_data_hash_changed?))
132       self.portable_data_hash = computed_pdh
133     elsif portable_data_hash_changed?
134       begin
135         loc = Keep::Locator.parse!(self.portable_data_hash)
136         loc.strip_hints!
137         if loc.size
138           self.portable_data_hash = loc.to_s
139         else
140           self.portable_data_hash = "#{loc.hash}+#{portable_manifest_text.bytesize}"
141         end
142       rescue ArgumentError => e
143         errors.add(:portable_data_hash, "#{e}")
144         return false
145       end
146     end
147     true
148   end
149
150   def ensure_pdh_matches_manifest_text
151     return true unless manifest_text_changed? or portable_data_hash_changed?
152     # No need verify it if :set_portable_data_hash just computed it!
153     expect_pdh = computed_pdh
154     if expect_pdh != portable_data_hash
155       errors.add(:portable_data_hash,
156                  "does not match computed hash #{expect_pdh}")
157       return false
158     end
159   end
160
161   def set_file_names
162     if self.manifest_text_changed?
163       self.file_names = manifest_files
164     end
165     true
166   end
167
168   def manifest_files
169     names = ''
170     if self.manifest_text
171       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
172         names << name.first.gsub('\040',' ') + "\n"
173         break if names.length > 2**12
174       end
175     end
176
177     if self.manifest_text and names.length < 2**12
178       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
179         names << stream_name.first.gsub('\040',' ') + "\n"
180         break if names.length > 2**12
181       end
182     end
183
184     names[0,2**12]
185   end
186
187   def check_encoding
188     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
189       true
190     else
191       begin
192         # If Ruby thinks the encoding is something else, like 7-bit
193         # ASCII, but its stored bytes are equal to the (valid) UTF-8
194         # encoding of the same string, we declare it to be a UTF-8
195         # string.
196         utf8 = manifest_text
197         utf8.force_encoding Encoding::UTF_8
198         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
199           manifest_text = utf8
200           return true
201         end
202       rescue
203       end
204       errors.add :manifest_text, "must use UTF-8 encoding"
205       false
206     end
207   end
208
209   def signed_manifest_text
210     if has_attribute? :manifest_text
211       token = current_api_client_authorization.andand.api_token
212       @signed_manifest_text = self.class.sign_manifest manifest_text, token
213     end
214   end
215
216   def self.sign_manifest manifest, token
217     signing_opts = {
218       api_token: token,
219       expire: db_current_time.to_i + Rails.configuration.blob_signature_ttl,
220     }
221     m = manifest.dup
222     m = munge_manifest_locators!(m) do |match|
223       Blob.sign_locator(locator_without_signature(match), signing_opts)
224     end
225     return m
226   end
227
228   def self.munge_manifest_locators! manifest
229     # Given a manifest text and a block, yield each locator,
230     # and replace it with whatever the block returns.
231     new_lines = []
232     lines = manifest.andand.split("\n")
233     lines.andand.each do |line|
234       words = line.split(' ')
235       new_words = []
236       words.each do |word|
237         if match = LOCATOR_REGEXP.match(word.strip)
238           new_words << yield(match)
239         else
240           new_words << word.strip
241         end
242       end
243       new_lines << new_words.join(' ')
244     end
245
246     if !new_lines.empty?
247       ends_with_newline = manifest.end_with?("\n")
248       manifest = new_lines.join("\n")
249       manifest += "\n" if ends_with_newline
250     end
251
252     manifest
253   end
254
255   def self.normalize_uuid uuid
256     hash_part = nil
257     size_part = nil
258     uuid.split('+').each do |token|
259       if token.match /^[0-9a-f]{32,}$/
260         raise "uuid #{uuid} has multiple hash parts" if hash_part
261         hash_part = token
262       elsif token.match /^\d+$/
263         raise "uuid #{uuid} has multiple size parts" if size_part
264         size_part = token
265       end
266     end
267     raise "uuid #{uuid} has no hash part" if !hash_part
268     [hash_part, size_part].compact.join '+'
269   end
270
271   # Return array of Collection objects
272   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
273     readers ||= [Thread.current[:user]]
274     base_search = Link.
275       readable_by(*readers).
276       readable_by(*readers, table_name: "collections").
277       joins("JOIN collections ON links.head_uuid = collections.uuid").
278       order("links.created_at DESC")
279
280     # If the search term is a Collection locator that contains one file
281     # that looks like a Docker image, return it.
282     if loc = Keep::Locator.parse(search_term)
283       loc.strip_hints!
284       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
285       if coll_match
286         # Check if the Collection contains exactly one file whose name
287         # looks like a saved Docker image.
288         manifest = Keep::Manifest.new(coll_match.manifest_text)
289         if manifest.exact_file_count?(1) and
290             (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
291           return [coll_match]
292         end
293       end
294     end
295
296     if search_tag.nil? and (n = search_term.index(":"))
297       search_tag = search_term[n+1..-1]
298       search_term = search_term[0..n-1]
299     end
300
301     # Find Collections with matching Docker image repository+tag pairs.
302     matches = base_search.
303       where(link_class: "docker_image_repo+tag",
304             name: "#{search_term}:#{search_tag || 'latest'}")
305
306     # If that didn't work, find Collections with matching Docker image hashes.
307     if matches.empty?
308       matches = base_search.
309         where("link_class = ? and links.name LIKE ?",
310               "docker_image_hash", "#{search_term}%")
311     end
312
313     # Generate an order key for each result.  We want to order the results
314     # so that anything with an image timestamp is considered more recent than
315     # anything without; then we use the link's created_at as a tiebreaker.
316     uuid_timestamps = {}
317     matches.all.map do |link|
318       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
319        -link.created_at.to_i]
320     end
321     Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
322   end
323
324   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
325     find_all_for_docker_image(search_term, search_tag, readers).first
326   end
327
328   def self.searchable_columns operator
329     super - ["manifest_text"]
330   end
331
332   def self.full_text_searchable_columns
333     super - ["manifest_text"]
334   end
335
336   protected
337   def portable_manifest_text
338     portable_manifest = self[:manifest_text].dup
339     portable_manifest = self.class.munge_manifest_locators!(portable_manifest) do |match|
340       if match[2] # size
341         match[1] + match[2]
342       else
343         match[1]
344       end
345     end
346     portable_manifest
347   end
348
349   def compute_pdh
350     portable_manifest = portable_manifest_text
351     (Digest::MD5.hexdigest(portable_manifest) +
352      '+' +
353      portable_manifest.bytesize.to_s)
354   end
355
356   def computed_pdh
357     if @computed_pdh_for_manifest_text == manifest_text
358       return @computed_pdh
359     end
360     @computed_pdh = compute_pdh
361     @computed_pdh_for_manifest_text = manifest_text.dup
362     @computed_pdh
363   end
364
365   def ensure_permission_to_save
366     if (not current_user.andand.is_admin and
367         (replication_confirmed_at_changed? or replication_confirmed_changed?) and
368         not (replication_confirmed_at.nil? and replication_confirmed.nil?))
369       raise ArvadosModel::PermissionDeniedError.new("replication_confirmed and replication_confirmed_at attributes cannot be changed, except by setting both to nil")
370     end
371     super
372   end
373 end