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