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