8784: Fix test for latest firefox.
[arvados.git] / apps / workbench / app / controllers / collections_controller.rb
1 require "arvados/keep"
2 require "arvados/collection"
3 require "uri"
4
5 class CollectionsController < ApplicationController
6   include ActionController::Live
7
8   skip_around_filter :require_thread_api_token, if: proc { |ctrl|
9     Rails.configuration.anonymous_user_token and
10     'show' == ctrl.action_name
11   }
12   skip_around_filter(:require_thread_api_token,
13                      only: [:show_file, :show_file_links])
14   skip_before_filter(:find_object_by_uuid,
15                      only: [:provenance, :show_file, :show_file_links])
16   # We depend on show_file to display the user agreement:
17   skip_before_filter :check_user_agreements, only: :show_file
18   skip_before_filter :check_user_profile, only: :show_file
19
20   RELATION_LIMIT = 5
21
22   def show_pane_list
23     panes = %w(Files Upload Provenance_graph Used_by Advanced)
24     panes = panes - %w(Upload) unless (@object.editable? rescue false)
25     panes
26   end
27
28   def set_persistent
29     case params[:value]
30     when 'persistent', 'cache'
31       persist_links = Link.filter([['owner_uuid', '=', current_user.uuid],
32                                    ['link_class', '=', 'resources'],
33                                    ['name', '=', 'wants'],
34                                    ['tail_uuid', '=', current_user.uuid],
35                                    ['head_uuid', '=', @object.uuid]])
36       logger.debug persist_links.inspect
37     else
38       return unprocessable "Invalid value #{value.inspect}"
39     end
40     if params[:value] == 'persistent'
41       if not persist_links.any?
42         Link.create(link_class: 'resources',
43                     name: 'wants',
44                     tail_uuid: current_user.uuid,
45                     head_uuid: @object.uuid)
46       end
47     else
48       persist_links.each do |link|
49         link.destroy || raise
50       end
51     end
52
53     respond_to do |f|
54       f.json { render json: @object }
55     end
56   end
57
58   def index
59     # API server index doesn't return manifest_text by default, but our
60     # callers want it unless otherwise specified.
61     @select ||= Collection.columns.map(&:name)
62     base_search = Collection.select(@select)
63     if params[:search].andand.length.andand > 0
64       tags = Link.where(any: ['contains', params[:search]])
65       @objects = (base_search.where(uuid: tags.collect(&:head_uuid)) |
66                       base_search.where(any: ['contains', params[:search]])).
67         uniq { |c| c.uuid }
68     else
69       if params[:limit]
70         limit = params[:limit].to_i
71       else
72         limit = 100
73       end
74
75       if params[:offset]
76         offset = params[:offset].to_i
77       else
78         offset = 0
79       end
80
81       @objects = base_search.limit(limit).offset(offset)
82     end
83     @links = Link.where(head_uuid: @objects.collect(&:uuid))
84     @collection_info = {}
85     @objects.each do |c|
86       @collection_info[c.uuid] = {
87         tag_links: [],
88         wanted: false,
89         wanted_by_me: false,
90         provenance: [],
91         links: []
92       }
93     end
94     @links.each do |link|
95       @collection_info[link.head_uuid] ||= {}
96       info = @collection_info[link.head_uuid]
97       case link.link_class
98       when 'tag'
99         info[:tag_links] << link
100       when 'resources'
101         info[:wanted] = true
102         info[:wanted_by_me] ||= link.tail_uuid == current_user.uuid
103       when 'provenance'
104         info[:provenance] << link.name
105       end
106       info[:links] << link
107     end
108     @request_url = request.url
109
110     render_index
111   end
112
113   def show_file_links
114     if Rails.configuration.keep_web_url || Rails.configuration.keep_web_download_url
115       # show_file will redirect to keep-web's directory listing
116       return show_file
117     end
118     Thread.current[:reader_tokens] = [params[:reader_token]]
119     return if false.equal?(find_object_by_uuid)
120     render layout: false
121   end
122
123   def show_file
124     # We pipe from arv-get to send the file to the user.  Before we start it,
125     # we ask the API server if the file actually exists.  This serves two
126     # purposes: it lets us return a useful status code for common errors, and
127     # helps us figure out which token to provide to arv-get.
128     # The order of searched tokens is important: because the anonymous user
129     # token is passed along with every API request, we have to check it first.
130     # Otherwise, it's impossible to know whether any other request succeeded
131     # because of the reader token.
132     coll = nil
133     tokens = [(Rails.configuration.anonymous_user_token || nil),
134               params[:reader_token],
135               Thread.current[:arvados_api_token]].compact
136     usable_token = find_usable_token(tokens) do
137       coll = Collection.find(params[:uuid])
138     end
139     if usable_token.nil?
140       # Response already rendered.
141       return
142     end
143
144     # If we are configured to use a keep-web server, just redirect to
145     # the appropriate URL.
146     if Rails.configuration.keep_web_url or
147         Rails.configuration.keep_web_download_url
148       opts = {}
149       if usable_token == params[:reader_token]
150         opts[:path_token] = usable_token
151       elsif usable_token == Rails.configuration.anonymous_user_token
152         # Don't pass a token at all
153       else
154         # We pass the current user's real token only if it's necessary
155         # to read the collection.
156         opts[:query_token] = usable_token
157       end
158       opts[:disposition] = params[:disposition] if params[:disposition]
159       return redirect_to keep_web_url(params[:uuid], params[:file], opts)
160     end
161
162     # No keep-web server available. Get the file data with arv-get,
163     # and serve it through Rails.
164
165     file_name = params[:file].andand.sub(/^(\.\/|\/|)/, './')
166     if file_name.nil? or not coll.manifest.has_file?(file_name)
167       return render_not_found
168     end
169
170     opts = params.merge(arvados_api_token: usable_token)
171
172     # Handle Range requests. Currently we support only 'bytes=0-....'
173     if request.headers.include? 'HTTP_RANGE'
174       if m = /^bytes=0-(\d+)/.match(request.headers['HTTP_RANGE'])
175         opts[:maxbytes] = m[1]
176         size = params[:size] || '*'
177         self.response.status = 206
178         self.response.headers['Content-Range'] = "bytes 0-#{m[1]}/#{size}"
179       end
180     end
181
182     ext = File.extname(params[:file])
183     self.response.headers['Content-Type'] =
184       Rack::Mime::MIME_TYPES[ext] || 'application/octet-stream'
185     if params[:size]
186       size = params[:size].to_i
187       if opts[:maxbytes]
188         size = [size, opts[:maxbytes].to_i].min
189       end
190       self.response.headers['Content-Length'] = size.to_s
191     end
192     self.response.headers['Content-Disposition'] = params[:disposition] if params[:disposition]
193     begin
194       file_enumerator(opts).each do |bytes|
195         response.stream.write bytes
196       end
197     ensure
198       response.stream.close
199     end
200   end
201
202   def sharing_scopes
203     ["GET /arvados/v1/collections/#{@object.uuid}", "GET /arvados/v1/collections/#{@object.uuid}/", "GET /arvados/v1/keep_services/accessible"]
204   end
205
206   def search_scopes
207     begin
208       ApiClientAuthorization.filter([['scopes', '=', sharing_scopes]]).results
209     rescue ArvadosApiClient::AccessForbiddenException
210       nil
211     end
212   end
213
214   def find_object_by_uuid
215     if not Keep::Locator.parse params[:id]
216       super
217     end
218   end
219
220   def show
221     return super if !@object
222
223     @logs = []
224
225     if params["tab_pane"] == "Provenance_graph"
226       @prov_svg = ProvenanceHelper::create_provenance_graph(@object.provenance, "provenance_svg",
227                                                             {:request => request,
228                                                              :direction => :top_down,
229                                                              :combine_jobs => :script_only}) rescue nil
230     end
231
232     if current_user
233       if Keep::Locator.parse params["uuid"]
234         @same_pdh = Collection.filter([["portable_data_hash", "=", @object.portable_data_hash]]).limit(20)
235         if @same_pdh.results.size == 1
236           redirect_to collection_path(@same_pdh[0]["uuid"])
237           return
238         end
239         owners = @same_pdh.map(&:owner_uuid).to_a.uniq
240         preload_objects_for_dataclass Group, owners
241         preload_objects_for_dataclass User, owners
242         uuids = @same_pdh.map(&:uuid).to_a.uniq
243         preload_links_for_objects uuids
244         render 'hash_matches'
245         return
246       else
247         if Job.api_exists?(:index)
248           jobs_with = lambda do |conds|
249             Job.limit(RELATION_LIMIT).where(conds)
250               .results.sort_by { |j| j.finished_at || j.created_at }
251           end
252           @output_of = jobs_with.call(output: @object.portable_data_hash)
253           @log_of = jobs_with.call(log: @object.portable_data_hash)
254         end
255
256         @project_links = Link.limit(RELATION_LIMIT).order("modified_at DESC")
257           .where(head_uuid: @object.uuid, link_class: 'name').results
258         project_hash = Group.where(uuid: @project_links.map(&:tail_uuid)).to_hash
259         @projects = project_hash.values
260
261         @permissions = Link.limit(RELATION_LIMIT).order("modified_at DESC")
262           .where(head_uuid: @object.uuid, link_class: 'permission',
263                  name: 'can_read').results
264         @search_sharing = search_scopes
265
266         if params["tab_pane"] == "Used_by"
267           @used_by_svg = ProvenanceHelper::create_provenance_graph(@object.used_by, "used_by_svg",
268                                                                    {:request => request,
269                                                                     :direction => :top_down,
270                                                                     :combine_jobs => :script_only,
271                                                                     :pdata_only => true}) rescue nil
272         end
273       end
274     end
275     super
276   end
277
278   def sharing_popup
279     @search_sharing = search_scopes
280     render("sharing_popup.js", content_type: "text/javascript")
281   end
282
283   helper_method :download_link
284
285   def download_link
286     token = @search_sharing.first.api_token
287     if Rails.configuration.keep_web_url || Rails.configuration.keep_web_download_url
288       keep_web_url(@object.uuid, nil, {path_token: token})
289     else
290       collections_url + "/download/#{@object.uuid}/#{token}/"
291     end
292   end
293
294   def share
295     ApiClientAuthorization.create(scopes: sharing_scopes)
296     sharing_popup
297   end
298
299   def unshare
300     search_scopes.each do |s|
301       s.destroy
302     end
303     sharing_popup
304   end
305
306   def remove_selected_files
307     uuids, source_paths = selected_collection_files params
308
309     arv_coll = Arv::Collection.new(@object.manifest_text)
310     source_paths[uuids[0]].each do |p|
311       arv_coll.rm "."+p
312     end
313
314     if @object.update_attributes manifest_text: arv_coll.manifest_text
315       show
316     else
317       self.render_error status: 422
318     end
319   end
320
321   def update
322     updated_attr = params[:collection].each.select {|a| a[0].andand.start_with? 'rename-file-path:'}
323
324     if updated_attr.size > 0
325       # Is it file rename?
326       file_path = updated_attr[0][0].split('rename-file-path:')[-1]
327
328       new_file_path = updated_attr[0][1]
329       if new_file_path.start_with?('./')
330         # looks good
331       elsif new_file_path.start_with?('/')
332         new_file_path = '.' + new_file_path
333       else
334         new_file_path = './' + new_file_path
335       end
336
337       arv_coll = Arv::Collection.new(@object.manifest_text)
338
339       if arv_coll.exist?(new_file_path)
340         @errors = 'Duplicate file path. Please use a different name.'
341         self.render_error status: 422
342       else
343         arv_coll.rename "./"+file_path, new_file_path
344
345         if @object.update_attributes manifest_text: arv_coll.manifest_text
346           show
347         else
348           self.render_error status: 422
349         end
350       end
351     else
352       # Not a file rename; use default
353       super
354     end
355   end
356
357   protected
358
359   def find_usable_token(token_list)
360     # Iterate over every given token to make it the current token and
361     # yield the given block.
362     # If the block succeeds, return the token it used.
363     # Otherwise, render an error response based on the most specific
364     # error we encounter, and return nil.
365     most_specific_error = [401]
366     token_list.each do |api_token|
367       begin
368         # We can't load the corresponding user, because the token may not
369         # be scoped for that.
370         using_specific_api_token(api_token, load_user: false) do
371           yield
372           return api_token
373         end
374       rescue ArvadosApiClient::ApiError => error
375         if error.api_status >= most_specific_error.first
376           most_specific_error = [error.api_status, error]
377         end
378       end
379     end
380     case most_specific_error.shift
381     when 401, 403
382       redirect_to_login
383     when 404
384       render_not_found(*most_specific_error)
385     end
386     return nil
387   end
388
389   def keep_web_url(uuid_or_pdh, file, opts)
390     munged_id = uuid_or_pdh.sub('+', '-')
391     fmt = {uuid_or_pdh: munged_id}
392
393     tmpl = Rails.configuration.keep_web_url
394     if Rails.configuration.keep_web_download_url and
395         (!tmpl or opts[:disposition] == 'attachment')
396       # Prefer the attachment-only-host when we want an attachment
397       # (and when there is no preview link configured)
398       tmpl = Rails.configuration.keep_web_download_url
399     elsif not Rails.configuration.trust_all_content
400       check_uri = URI.parse(tmpl % fmt)
401       if opts[:query_token] and
402           not check_uri.host.start_with?(munged_id + "--") and
403           not check_uri.host.start_with?(munged_id + ".")
404         # We're about to pass a token in the query string, but
405         # keep-web can't accept that safely at a single-origin URL
406         # template (unless it's -attachment-only-host).
407         tmpl = Rails.configuration.keep_web_download_url
408         if not tmpl
409           raise ArgumentError, "Download precluded by site configuration"
410         end
411         logger.warn("Using download link, even though inline content " \
412                     "was requested: #{check_uri.to_s}")
413       end
414     end
415
416     if tmpl == Rails.configuration.keep_web_download_url
417       # This takes us to keep-web's -attachment-only-host so there is
418       # no need to add ?disposition=attachment.
419       opts.delete :disposition
420     end
421
422     uri = URI.parse(tmpl % fmt)
423     uri.path += '/' unless uri.path.end_with? '/'
424     if opts[:path_token]
425       uri.path += 't=' + opts[:path_token] + '/'
426     end
427     uri.path += '_/'
428     uri.path += URI.escape(file) if file
429
430     query = Hash[URI.decode_www_form(uri.query || '')]
431     { query_token: 'api_token',
432       disposition: 'disposition' }.each do |opt, param|
433       if opts.include? opt
434         query[param] = opts[opt]
435       end
436     end
437     unless query.empty?
438       uri.query = URI.encode_www_form(query)
439     end
440
441     uri.to_s
442   end
443
444   # Note: several controller and integration tests rely on stubbing
445   # file_enumerator to return fake file content.
446   def file_enumerator opts
447     FileStreamer.new opts
448   end
449
450   class FileStreamer
451     include ArvadosApiClientHelper
452     def initialize(opts={})
453       @opts = opts
454     end
455     def each
456       return unless @opts[:uuid] && @opts[:file]
457
458       env = Hash[ENV].dup
459
460       require 'uri'
461       u = URI.parse(arvados_api_client.arvados_v1_base)
462       env['ARVADOS_API_HOST'] = "#{u.host}:#{u.port}"
463       env['ARVADOS_API_TOKEN'] = @opts[:arvados_api_token]
464       env['ARVADOS_API_HOST_INSECURE'] = "true" if Rails.configuration.arvados_insecure_https
465
466       bytesleft = @opts[:maxbytes].andand.to_i || 2**16
467       io = IO.popen([env, 'arv-get', "#{@opts[:uuid]}/#{@opts[:file]}"], 'rb')
468       while bytesleft > 0 && (buf = io.read([bytesleft, 2**16].min)) != nil
469         # shrink the bytesleft count, if we were given a maximum byte
470         # count to read
471         if @opts.include? :maxbytes
472           bytesleft = bytesleft - buf.length
473         end
474         yield buf
475       end
476       io.close
477       # "If ios is opened by IO.popen, close sets $?."
478       # http://www.ruby-doc.org/core-2.1.3/IO.html#method-i-close
479       Rails.logger.warn("#{@opts[:uuid]}/#{@opts[:file]}: #{$?}") if $? != 0
480     end
481   end
482 end