4232: remove "dependencies" entries from examples in the tutorials if the API is...
[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       self.file_names = manifest_files
133     end
134     true
135   end
136
137   def manifest_files
138     names = ''
139     if self.manifest_text
140       self.manifest_text.scan(/ \d+:\d+:(\S+)/) do |name|
141         names << name.first.gsub('\040',' ') + "\n"
142         break if names.length > 2**12
143       end
144     end
145
146     if self.manifest_text and names.length < 2**12
147       self.manifest_text.scan(/^\.\/(\S+)/m) do |stream_name|
148         names << stream_name.first.gsub('\040',' ') + "\n"
149         break if names.length > 2**12
150       end
151     end
152
153     names[0,2**12]
154   end
155
156   def check_encoding
157     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
158       true
159     else
160       begin
161         # If Ruby thinks the encoding is something else, like 7-bit
162         # ASCII, but its stored bytes are equal to the (valid) UTF-8
163         # encoding of the same string, we declare it to be a UTF-8
164         # string.
165         utf8 = manifest_text
166         utf8.force_encoding Encoding::UTF_8
167         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
168           manifest_text = utf8
169           return true
170         end
171       rescue
172       end
173       errors.add :manifest_text, "must use UTF-8 encoding"
174       false
175     end
176   end
177
178   def redundancy_status
179     if redundancy_confirmed_as.nil?
180       'unconfirmed'
181     elsif redundancy_confirmed_as < redundancy
182       'degraded'
183     else
184       if redundancy_confirmed_at.nil?
185         'unconfirmed'
186       elsif Time.now - redundancy_confirmed_at < 7.days
187         'OK'
188       else
189         'stale'
190       end
191     end
192   end
193
194   def signed_manifest_text
195     if has_attribute? :manifest_text
196       token = current_api_client_authorization.andand.api_token
197       @signed_manifest_text = self.class.sign_manifest manifest_text, token
198     end
199   end
200
201   def self.sign_manifest manifest, token
202     signing_opts = {
203       key: Rails.configuration.blob_signing_key,
204       api_token: token,
205       ttl: Rails.configuration.blob_signing_ttl,
206     }
207     m = manifest.dup
208     munge_manifest_locators!(m) do |loc|
209       Blob.sign_locator(loc.to_s, signing_opts)
210     end
211     return m
212   end
213
214   def self.munge_manifest_locators! manifest
215     # Given a manifest text and a block, yield each locator,
216     # and replace it with whatever the block returns.
217     manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
218       if loc = Keep::Locator.parse(word.strip)
219         " " + yield(loc)
220       else
221         " " + word
222       end
223     end
224   end
225
226   def self.normalize_uuid uuid
227     hash_part = nil
228     size_part = nil
229     uuid.split('+').each do |token|
230       if token.match /^[0-9a-f]{32,}$/
231         raise "uuid #{uuid} has multiple hash parts" if hash_part
232         hash_part = token
233       elsif token.match /^\d+$/
234         raise "uuid #{uuid} has multiple size parts" if size_part
235         size_part = token
236       end
237     end
238     raise "uuid #{uuid} has no hash part" if !hash_part
239     [hash_part, size_part].compact.join '+'
240   end
241
242   # Return array of Collection objects
243   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
244     readers ||= [Thread.current[:user]]
245     base_search = Link.
246       readable_by(*readers).
247       readable_by(*readers, table_name: "collections").
248       joins("JOIN collections ON links.head_uuid = collections.uuid").
249       order("links.created_at DESC")
250
251     # If the search term is a Collection locator that contains one file
252     # that looks like a Docker image, return it.
253     if loc = Keep::Locator.parse(search_term)
254       loc.strip_hints!
255       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
256       if coll_match
257         # Check if the Collection contains exactly one file whose name
258         # looks like a saved Docker image.
259         manifest = Keep::Manifest.new(coll_match.manifest_text)
260         if manifest.exact_file_count?(1) and
261             (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
262           return [coll_match]
263         end
264       end
265     end
266
267     if search_tag.nil? and (n = search_term.index(":"))
268       search_tag = search_term[n+1..-1]
269       search_term = search_term[0..n-1]
270     end
271
272     # Find Collections with matching Docker image repository+tag pairs.
273     matches = base_search.
274       where(link_class: "docker_image_repo+tag",
275             name: "#{search_term}:#{search_tag || 'latest'}")
276
277     # If that didn't work, find Collections with matching Docker image hashes.
278     if matches.empty?
279       matches = base_search.
280         where("link_class = ? and links.name LIKE ?",
281               "docker_image_hash", "#{search_term}%")
282     end
283
284     # Generate an order key for each result.  We want to order the results
285     # so that anything with an image timestamp is considered more recent than
286     # anything without; then we use the link's created_at as a tiebreaker.
287     uuid_timestamps = {}
288     matches.all.map do |link|
289       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
290        -link.created_at.to_i]
291     end
292     Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
293   end
294
295   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
296     find_all_for_docker_image(search_term, search_tag, readers).first
297   end
298
299   def self.searchable_columns operator
300     super - ["manifest_text"]
301   end
302
303   protected
304   def portable_manifest_text
305     portable_manifest = self[:manifest_text].dup
306     self.class.munge_manifest_locators!(portable_manifest) do |loc|
307       loc.hash + '+' + loc.size.to_s
308     end
309     portable_manifest
310   end
311
312   def compute_pdh
313     portable_manifest = portable_manifest_text
314     (Digest::MD5.hexdigest(portable_manifest) +
315      '+' +
316      portable_manifest.bytesize.to_s)
317   end
318 end