Merge branch 'master' into 4194-keep-logging
[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
14   # Query only undeleted collections by default.
15   default_scope where("expires_at IS NULL or expires_at > CURRENT_TIMESTAMP")
16
17   api_accessible :user, extend: :common do |t|
18     t.add :name
19     t.add :description
20     t.add :properties
21     t.add :portable_data_hash
22     t.add :manifest_text
23   end
24
25   def check_signatures
26     return false if self.manifest_text.nil?
27
28     return true if current_user.andand.is_admin
29
30     if self.manifest_text_changed?
31       # Check permissions on the collection manifest.
32       # If any signature cannot be verified, raise PermissionDeniedError
33       # which will return 403 Permission denied to the client.
34       api_token = current_api_client_authorization.andand.api_token
35       signing_opts = {
36         key: Rails.configuration.blob_signing_key,
37         api_token: api_token,
38         ttl: Rails.configuration.blob_signing_ttl,
39       }
40       self.manifest_text.lines.each do |entry|
41         entry.split[1..-1].each do |tok|
42           if /^[[:digit:]]+:[[:digit:]]+:/.match tok
43             # This is a filename token, not a blob locator. Note that we
44             # keep checking tokens after this, even though manifest
45             # format dictates that all subsequent tokens will also be
46             # filenames. Safety first!
47           elsif Blob.verify_signature tok, signing_opts
48             # OK.
49           elsif Keep::Locator.parse(tok).andand.signature
50             # Signature provided, but verify_signature did not like it.
51             logger.warn "Invalid signature on locator #{tok}"
52             raise ArvadosModel::PermissionDeniedError
53           elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
54             # No signature provided, but we are running in insecure mode.
55             logger.debug "Missing signature on locator #{tok} ignored"
56           elsif Blob.new(tok).empty?
57             # No signature provided -- but no data to protect, either.
58           else
59             logger.warn "Missing signature on locator #{tok}"
60             raise ArvadosModel::PermissionDeniedError
61           end
62         end
63       end
64     end
65     true
66   end
67
68   def strip_manifest_text
69     if self.manifest_text_changed?
70       # Remove any permission signatures from the manifest.
71       Collection.munge_manifest_locators(self[:manifest_text]) do |loc|
72         loc.without_signature.to_s
73       end
74     end
75     true
76   end
77
78   def set_portable_data_hash
79     if (self.portable_data_hash.nil? or (self.portable_data_hash == "") or (manifest_text_changed? and !portable_data_hash_changed?))
80       self.portable_data_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.bytesize}"
81     elsif portable_data_hash_changed?
82       begin
83         loc = Keep::Locator.parse!(self.portable_data_hash)
84         loc.strip_hints!
85         if loc.size
86           self.portable_data_hash = loc.to_s
87         else
88           self.portable_data_hash = "#{loc.hash}+#{self.manifest_text.bytesize}"
89         end
90       rescue ArgumentError => e
91         errors.add(:portable_data_hash, "#{e}")
92         return false
93       end
94     end
95     true
96   end
97
98   def ensure_hash_matches_manifest_text
99     if manifest_text_changed? or portable_data_hash_changed?
100       computed_hash = "#{Digest::MD5.hexdigest(manifest_text)}+#{manifest_text.bytesize}"
101       unless computed_hash == portable_data_hash
102         logger.debug "(computed) '#{computed_hash}' != '#{portable_data_hash}' (provided)"
103         errors.add(:portable_data_hash, "does not match hash of manifest_text")
104         return false
105       end
106     end
107     true
108   end
109
110   def check_encoding
111     if manifest_text.encoding.name == 'UTF-8' and manifest_text.valid_encoding?
112       true
113     else
114       begin
115         # If Ruby thinks the encoding is something else, like 7-bit
116         # ASCII, but its stored bytes are equal to the (valid) UTF-8
117         # encoding of the same string, we declare it to be a UTF-8
118         # string.
119         utf8 = manifest_text
120         utf8.force_encoding Encoding::UTF_8
121         if utf8.valid_encoding? and utf8 == manifest_text.encode(Encoding::UTF_8)
122           manifest_text = utf8
123           return true
124         end
125       rescue
126       end
127       errors.add :manifest_text, "must use UTF-8 encoding"
128       false
129     end
130   end
131
132   def redundancy_status
133     if redundancy_confirmed_as.nil?
134       'unconfirmed'
135     elsif redundancy_confirmed_as < redundancy
136       'degraded'
137     else
138       if redundancy_confirmed_at.nil?
139         'unconfirmed'
140       elsif Time.now - redundancy_confirmed_at < 7.days
141         'OK'
142       else
143         'stale'
144       end
145     end
146   end
147
148   def self.munge_manifest_locators(manifest)
149     # Given a manifest text and a block, yield each locator,
150     # and replace it with whatever the block returns.
151     manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
152       if loc = Keep::Locator.parse(word.strip)
153         " " + yield(loc)
154       else
155         " " + word
156       end
157     end
158   end
159
160   def self.normalize_uuid uuid
161     hash_part = nil
162     size_part = nil
163     uuid.split('+').each do |token|
164       if token.match /^[0-9a-f]{32,}$/
165         raise "uuid #{uuid} has multiple hash parts" if hash_part
166         hash_part = token
167       elsif token.match /^\d+$/
168         raise "uuid #{uuid} has multiple size parts" if size_part
169         size_part = token
170       end
171     end
172     raise "uuid #{uuid} has no hash part" if !hash_part
173     [hash_part, size_part].compact.join '+'
174   end
175
176   # Return array of Collection objects
177   def self.find_all_for_docker_image(search_term, search_tag=nil, readers=nil)
178     readers ||= [Thread.current[:user]]
179     base_search = Link.
180       readable_by(*readers).
181       readable_by(*readers, table_name: "collections").
182       joins("JOIN collections ON links.head_uuid = collections.uuid").
183       order("links.created_at DESC")
184
185     # If the search term is a Collection locator that contains one file
186     # that looks like a Docker image, return it.
187     if loc = Keep::Locator.parse(search_term)
188       loc.strip_hints!
189       coll_match = readable_by(*readers).where(portable_data_hash: loc.to_s).limit(1).first
190       if coll_match
191         # Check if the Collection contains exactly one file whose name
192         # looks like a saved Docker image.
193         manifest = Keep::Manifest.new(coll_match.manifest_text)
194         if manifest.exact_file_count?(1) and
195             (manifest.files[0][1] =~ /^[0-9A-Fa-f]{64}\.tar$/)
196           return [coll_match]
197         end
198       end
199     end
200
201     if search_tag.nil? and (n = search_term.index(":"))
202       search_tag = search_term[n+1..-1]
203       search_term = search_term[0..n-1]
204     end
205
206     # Find Collections with matching Docker image repository+tag pairs.
207     matches = base_search.
208       where(link_class: "docker_image_repo+tag",
209             name: "#{search_term}:#{search_tag || 'latest'}")
210
211     # If that didn't work, find Collections with matching Docker image hashes.
212     if matches.empty?
213       matches = base_search.
214         where("link_class = ? and links.name LIKE ?",
215               "docker_image_hash", "#{search_term}%")
216     end
217
218     # Generate an order key for each result.  We want to order the results
219     # so that anything with an image timestamp is considered more recent than
220     # anything without; then we use the link's created_at as a tiebreaker.
221     uuid_timestamps = {}
222     matches.all.map do |link|
223       uuid_timestamps[link.head_uuid] = [(-link.properties["image_timestamp"].to_datetime.to_i rescue 0),
224        -link.created_at.to_i]
225     end
226     Collection.where('uuid in (?)', uuid_timestamps.keys).sort_by { |c| uuid_timestamps[c.uuid] }
227   end
228
229   def self.for_latest_docker_image(search_term, search_tag=nil, readers=nil)
230     find_all_for_docker_image(search_term, search_tag, readers).first
231   end
232 end