Merge branch 'master' into 6203-collection-perf-api
[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_manifest_text_and_clear_replication_confirmed
14   before_validation :set_portable_data_hash
15   validate :ensure_hash_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   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     computed_pdh = compute_pdh
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 /^[[:digit:]]+:[[:digit:]]+:/.match tok
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_manifest_text_and_clear_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     true
115   end
116
117   def self.locator_without_signature match
118     without_signature = match[1]
119     without_signature += match[2] if match[2]
120     if match[4]
121       hints = match[4].split('+').reject { |hint| hint.start_with?("A") }
122       without_signature += hints.join('+')
123     end
124     without_signature
125   end
126
127   def set_portable_data_hash
128     if (portable_data_hash.nil? or
129         portable_data_hash == "" or
130         (manifest_text_changed? and !portable_data_hash_changed?))
131       @need_pdh_validation = false
132       self.portable_data_hash = compute_pdh
133     elsif portable_data_hash_changed?
134       @need_pdh_validation = true
135       begin
136         loc = Keep::Locator.parse!(self.portable_data_hash)
137         loc.strip_hints!
138         if loc.size
139           self.portable_data_hash = loc.to_s
140         else
141           self.portable_data_hash = "#{loc.hash}+#{portable_manifest_text.bytesize}"
142         end
143       rescue ArgumentError => e
144         errors.add(:portable_data_hash, "#{e}")
145         return false
146       end
147     end
148     true
149   end
150
151   def ensure_hash_matches_manifest_text
152     return true unless manifest_text_changed? or portable_data_hash_changed?
153     # No need verify it if :set_portable_data_hash just computed it!
154     return true if not @need_pdh_validation
155     expect_pdh = compute_pdh
156     if expect_pdh != portable_data_hash
157       errors.add(:portable_data_hash,
158                  "does not match computed hash #{expect_pdh}")
159       return false
160     end
161   end
162
163   def set_file_names
164     if self.manifest_text_changed?
165       self.file_names = manifest_files
166     end
167     true
168   end
169
170   def manifest_files
171     names = ''
172     if self.manifest_text
173       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
174         names << name.first.gsub('\040',' ') + "\n"
175         break if names.length > 2**12
176       end
177     end
178
179     if self.manifest_text and names.length < 2**12
180       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
181         names << stream_name.first.gsub('\040',' ') + "\n"
182         break if names.length > 2**12
183       end
184     end
185
186     names[0,2**12]
187   end
188
189   def check_encoding
190     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
191       true
192     else
193       begin
194         # If Ruby thinks the encoding is something else, like 7-bit
195         # ASCII, but its stored bytes are equal to the (valid) UTF-8
196         # encoding of the same string, we declare it to be a UTF-8
197         # string.
198         utf8 = manifest_text
199         utf8.force_encoding Encoding::UTF_8
200         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
201           manifest_text = utf8
202           return true
203         end
204       rescue
205       end
206       errors.add :manifest_text, "must use UTF-8 encoding"
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 = manifest.dup
224     m = munge_manifest_locators!(m) do |match|
225       Blob.sign_locator(locator_without_signature(match), signing_opts)
226     end
227     return m
228   end
229
230   def self.munge_manifest_locators! manifest
231     # Given a manifest text and a block, yield each locator,
232     # and replace it with whatever the block returns.
233     new_lines = []
234     lines = manifest.andand.split("\n")
235     lines.andand.each do |line|
236       words = line.split(' ')
237       new_words = []
238       words.each do |word|
239         if match = LOCATOR_REGEXP.match(word.strip)
240           new_words << yield(match)
241         else
242           new_words << word.strip
243         end
244       end
245       new_lines << new_words.join(' ')
246     end
247
248     if !new_lines.empty?
249       ends_with_newline = manifest.end_with?("\n")
250       manifest = new_lines.join("\n")
251       manifest += "\n" if ends_with_newline
252     end
253
254     manifest
255   end
256
257   def self.normalize_uuid uuid
258     hash_part = nil
259     size_part = nil
260     uuid.split('+').each do |token|
261       if token.match /^[0-9a-f]{32,}$/
262         raise "uuid #{uuid} has multiple hash parts" if hash_part
263         hash_part = token
264       elsif token.match /^\d+$/
265         raise "uuid #{uuid} has multiple size parts" if size_part
266         size_part = token
267       end
268     end
269     raise "uuid #{uuid} has no hash part" if !hash_part
270     [hash_part, size_part].compact.join '+'
271   end
272
273   # Return array of Collection objects
274   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
275     readers ||= [Thread.current[:user]]
276     base_search = Link.
277       readable_by(*readers).
278       readable_by(*readers, table_name: "collections").
279       joins("JOIN collections ON links.head_uuid = collections.uuid").
280       order("links.created_at DESC")
281
282     # If the search term is a Collection locator that contains one file
283     # that looks like a Docker image, return it.
284     if loc = Keep::Locator.parse(search_term)
285       loc.strip_hints!
286       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
287       if coll_match
288         # Check if the Collection contains exactly one file whose name
289         # looks like a saved Docker image.
290         manifest = Keep::Manifest.new(coll_match.manifest_text)
291         if manifest.exact_file_count?(1) and
292             (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
293           return [coll_match]
294         end
295       end
296     end
297
298     if search_tag.nil? and (n = search_term.index(":"))
299       search_tag = search_term[n+1..-1]
300       search_term = search_term[0..n-1]
301     end
302
303     # Find Collections with matching Docker image repository+tag pairs.
304     matches = base_search.
305       where(link_class: "docker_image_repo+tag",
306             name: "#{search_term}:#{search_tag || 'latest'}")
307
308     # If that didn't work, find Collections with matching Docker image hashes.
309     if matches.empty?
310       matches = base_search.
311         where("link_class = ? and links.name LIKE ?",
312               "docker_image_hash", "#{search_term}%")
313     end
314
315     # Generate an order key for each result.  We want to order the results
316     # so that anything with an image timestamp is considered more recent than
317     # anything without; then we use the link's created_at as a tiebreaker.
318     uuid_timestamps = {}
319     matches.all.map do |link|
320       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
321        -link.created_at.to_i]
322     end
323     Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
324   end
325
326   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
327     find_all_for_docker_image(search_term, search_tag, readers).first
328   end
329
330   def self.searchable_columns operator
331     super - ["manifest_text"]
332   end
333
334   def self.full_text_searchable_columns
335     super - ["manifest_text"]
336   end
337
338   protected
339   def portable_manifest_text
340     portable_manifest = self[:manifest_text].dup
341     portable_manifest = self.class.munge_manifest_locators!(portable_manifest) do |match|
342       if match[2] # size
343         match[1] + match[2]
344       else
345         match[1]
346       end
347     end
348     portable_manifest
349   end
350
351   def compute_pdh
352     return @computed_pdh if @computed_pdh
353     portable_manifest = portable_manifest_text
354     @computed_pdh = (Digest::MD5.hexdigest(portable_manifest) +
355                      '+' +
356                      portable_manifest.bytesize.to_s)
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