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