Merge branch 'master' into 3036-collection-uuids
[arvados.git] / services / api / app / controllers / arvados / v1 / collections_controller.rb
1 class Arvados::V1::CollectionsController < ApplicationController
2   def create
3     if !resource_attrs[:manifest_text]
4       return send_error("'manifest_text' attribute must be specified",
5                         status: :unprocessable_entity)
6     end
7
8     # Check permissions on the collection manifest.
9     # If any signature cannot be verified, return 403 Permission denied.
10     api_token = current_api_client_authorization.andand.api_token
11     signing_opts = {
12       key: Rails.configuration.blob_signing_key,
13       api_token: api_token,
14       ttl: Rails.configuration.blob_signing_ttl,
15     }
16     resource_attrs[:manifest_text].lines.each do |entry|
17       entry.split[1..-1].each do |tok|
18         if /^[[:digit:]]+:[[:digit:]]+:/.match tok
19           # This is a filename token, not a blob locator. Note that we
20           # keep checking tokens after this, even though manifest
21           # format dictates that all subsequent tokens will also be
22           # filenames. Safety first!
23         elsif Blob.verify_signature tok, signing_opts
24           # OK.
25         elsif Locator.parse(tok).andand.signature
26           # Signature provided, but verify_signature did not like it.
27           logger.warn "Invalid signature on locator #{tok}"
28           raise ArvadosModel::PermissionDeniedError
29         elsif Rails.configuration.permit_create_collection_with_unsigned_manifest
30           # No signature provided, but we are running in insecure mode.
31           logger.debug "Missing signature on locator #{tok} ignored"
32         elsif Blob.new(tok).empty?
33           # No signature provided -- but no data to protect, either.
34         else
35           logger.warn "Missing signature on locator #{tok}"
36           raise ArvadosModel::PermissionDeniedError
37         end
38       end
39     end
40
41     # Remove any permission signatures from the manifest.
42     munge_manifest_locators(resource_attrs[:manifest_text]) do |loc|
43       loc.without_signature.to_s
44     end
45
46     super
47   end
48
49   def find_object_by_uuid
50     if loc = Locator.parse(params[:id])
51       loc.strip_hints!
52       if c = Collection.readable_by(*@read_users).where({ portable_data_hash: loc.to_s }).limit(1).first
53         @object = {
54           portable_data_hash: c.portable_data_hash,
55           manifest_text: c.manifest_text,
56           files: c.files,
57           data_size: c.data_size
58         }
59       end
60     else
61       super
62     end
63     true
64   end
65
66   def show
67     sign_manifests(@object[:manifest_text])
68     super
69   end
70
71   def index
72     sign_manifests(*@objects.map { |c| c[:manifest_text] })
73     super
74   end
75
76   def script_param_edges(visited, sp)
77     case sp
78     when Hash
79       sp.each do |k, v|
80         script_param_edges(visited, v)
81       end
82     when Array
83       sp.each do |v|
84         script_param_edges(visited, v)
85       end
86     when String
87       return if sp.empty?
88       if loc = Locator.parse(sp)
89         search_edges(visited, loc.to_s, :search_up)
90       end
91     end
92   end
93
94   def search_edges(visited, uuid, direction)
95     if uuid.nil? or uuid.empty? or visited[uuid]
96       return
97     end
98
99     if loc = Locator.parse(uuid)
100       loc.strip_hints!
101       return if visited[loc.to_s]
102     end
103
104     logger.debug "visiting #{uuid}"
105
106     if loc
107       # uuid is a portable_data_hash
108       if c = Collection.readable_by(*@read_users).where(portable_data_hash: loc.to_s).limit(1).first
109         visited[loc.to_s] = {
110           portable_data_hash: c.portable_data_hash,
111           files: c.files,
112           data_size: c.data_size
113         }
114       end
115
116       if direction == :search_up
117         # Search upstream for jobs where this locator is the output of some job
118         Job.readable_by(*@read_users).where(output: loc.to_s).each do |job|
119           search_edges(visited, job.uuid, :search_up)
120         end
121
122         Job.readable_by(*@read_users).where(log: loc.to_s).each do |job|
123           search_edges(visited, job.uuid, :search_up)
124         end
125       elsif direction == :search_down
126         if loc.to_s == "d41d8cd98f00b204e9800998ecf8427e+0"
127           # Special case, don't follow the empty collection.
128           return
129         end
130
131         # Search downstream for jobs where this locator is in script_parameters
132         Job.readable_by(*@read_users).where(["jobs.script_parameters like ?", "%#{loc.to_s}%"]).each do |job|
133           search_edges(visited, job.uuid, :search_down)
134         end
135       end
136     else
137       # uuid is a regular Arvados UUID
138       rsc = ArvadosModel::resource_class_for_uuid uuid
139       if rsc == Job
140         Job.readable_by(*@read_users).where(uuid: uuid).each do |job|
141           visited[uuid] = job.as_api_response
142           if direction == :search_up
143             # Follow upstream collections referenced in the script parameters
144             script_param_edges(visited, job.script_parameters)
145           elsif direction == :search_down
146             # Follow downstream job output
147             search_edges(visited, job.output, direction)
148           end
149         end
150       elsif rsc == Collection
151         if c = Collection.readable_by(*@read_users).where(uuid: uuid).limit(1).first
152           search_edges(visited, c.portable_data_hash, direction)
153           visited[c.portable_data_hash] = c.as_api_response
154         end
155       elsif rsc != nil
156         rsc.where(uuid: uuid).each do |r|
157           visited[uuid] = r.as_api_response
158         end
159       end
160     end
161
162     if direction == :search_up
163       # Search for provenance links pointing to the current uuid
164       Link.readable_by(*@read_users).
165         where(head_uuid: uuid, link_class: "provenance").
166         each do |link|
167         visited[link.uuid] = link.as_api_response
168         search_edges(visited, link.tail_uuid, direction)
169       end
170     elsif direction == :search_down
171       # Search for provenance links emanating from the current uuid
172       Link.readable_by(current_user).
173         where(tail_uuid: uuid, link_class: "provenance").
174         each do |link|
175         visited[link.uuid] = link.as_api_response
176         search_edges(visited, link.head_uuid, direction)
177       end
178     end
179   end
180
181   def provenance
182     visited = {}
183     search_edges(visited, @object[:uuid] || @object[:portable_data_hash], :search_up)
184     render json: visited
185   end
186
187   def used_by
188     visited = {}
189     search_edges(visited, @object[:uuid] || @object[:portable_data_hash], :search_down)
190     render json: visited
191   end
192
193   def self.munge_manifest_locators(manifest)
194     # Given a manifest text and a block, yield each locator,
195     # and replace it with whatever the block returns.
196     manifest.andand.gsub!(/ [[:xdigit:]]{32}(\+[[:digit:]]+)?(\+\S+)/) do |word|
197       if loc = Locator.parse(word.strip)
198         " " + yield(loc)
199       else
200         " " + word
201       end
202     end
203   end
204
205   protected
206
207   def find_objects_for_index
208     # Omit manifest_text from index results unless expressly selected.
209     @select ||= model_class.api_accessible_attributes(:user).
210       map { |attr_spec| attr_spec.first.to_s } - ["manifest_text"]
211     super
212   end
213
214   def find_object_by_uuid
215     super
216     if !@object and !params[:uuid].match(/^[0-9a-f]+\+\d+$/)
217       # Normalize the given uuid and search again.
218       hash_part = params[:uuid].match(/^([0-9a-f]*)/)[1]
219       collection = Collection.where('uuid like ?', hash_part + '+%').first
220       if collection
221         # We know the collection exists, and what its real uuid is in
222         # the database. Now, throw out @objects and repeat the usual
223         # lookup procedure. (Returning the collection at this point
224         # would bypass permission checks.)
225         @objects = nil
226         @where = { uuid: collection.uuid }
227         find_objects_for_index
228         @object = @objects.first
229       end
230     end
231   end
232
233   def munge_manifest_locators(manifest, &block)
234     self.class.munge_manifest_locators(manifest, &block)
235   end
236
237   def sign_manifests(*manifests)
238     if current_api_client_authorization
239       signing_opts = {
240         key: Rails.configuration.blob_signing_key,
241         api_token: current_api_client_authorization.api_token,
242         ttl: Rails.configuration.blob_signing_ttl,
243       }
244       manifests.each do |text|
245         munge_manifest_locators(text) do |loc|
246           Blob.sign_locator(loc.to_s, signing_opts)
247         end
248       end
249     end
250   end
251 end