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