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