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