Do not return Links with group contents
[arvados.git] / services / api / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3   include ThemesForRails::ActionController
4
5   respond_to :json
6   protect_from_forgery
7   around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
8
9   before_filter :respond_with_json_by_default
10   before_filter :remote_ip
11   before_filter :require_auth_scope, :except => :render_not_found
12   before_filter :catch_redirect_hint
13
14   before_filter :find_object_by_uuid, :except => [:index, :create,
15                                                   :render_error,
16                                                   :render_not_found]
17   before_filter :load_limit_offset_order_params, only: [:index, :contents]
18   before_filter :load_where_param, only: [:index, :contents]
19   before_filter :load_filters_param, only: [:index, :contents]
20   before_filter :find_objects_for_index, :only => :index
21   before_filter :reload_object_before_update, :only => :update
22   before_filter :render_404_if_no_object, except: [:index, :create,
23                                                    :render_error,
24                                                    :render_not_found]
25
26   theme :select_theme
27
28   attr_accessor :resource_attrs
29
30   DEFAULT_LIMIT = 100
31
32   def index
33     @objects.uniq!(&:id)
34     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
35       @objects.each(&:eager_load_associations)
36     end
37     render_list
38   end
39
40   def show
41     render json: @object.as_api_response
42   end
43
44   def create
45     @object = model_class.new resource_attrs
46     @object.save!
47     show
48   end
49
50   def update
51     attrs_to_update = resource_attrs.reject { |k,v|
52       [:kind, :etag, :href].index k
53     }
54     @object.update_attributes! attrs_to_update
55     show
56   end
57
58   def destroy
59     @object.destroy
60     show
61   end
62
63   def self._contents_requires_parameters
64     _index_requires_parameters.
65       merge({
66               include_linked: {
67                 type: 'boolean', required: false, default: false
68               },
69             })
70   end
71
72   def contents
73     all_objects = []
74     all_available = 0
75
76     # Trick apply_where_limit_order_params into applying suitable
77     # per-table values. *_all are the real ones we'll apply to the
78     # aggregate set.
79     limit_all = @limit
80     offset_all = @offset
81     @orders = []
82
83     ArvadosModel.descendants.
84       reject(&:abstract_class?).
85       sort_by(&:to_s).
86       each do |klass|
87       case klass.to_s
88         # We might expect klass==Link etc. here, but we would be
89         # disappointed: when Rails reloads model classes, we get two
90         # distinct classes called Link which do not equal each
91         # other. But we can still rely on klass.to_s to be "Link".
92       when 'ApiClientAuthorization', 'UserAgreement', 'Link'
93         # Do not want.
94       else
95         @objects = klass.readable_by(current_user)
96         cond_sql = "#{klass.table_name}.owner_uuid = ?"
97         cond_params = [@object.uuid]
98         if params[:include_linked]
99           cond_sql += " OR #{klass.table_name}.uuid IN (SELECT head_uuid FROM links WHERE link_class=#{klass.sanitize 'name'} AND links.tail_uuid=#{klass.sanitize @object.uuid})"
100         end
101         @objects = @objects.where(cond_sql, *cond_params).order("#{klass.table_name}.uuid")
102         @limit = limit_all - all_objects.count
103         apply_where_limit_order_params
104         items_available = @objects.
105           except(:limit).except(:offset).
106           count(:id, distinct: true)
107         all_available += items_available
108         @offset = [@offset - items_available, 0].max
109
110         all_objects += @objects.to_a
111       end
112     end
113     @objects = all_objects || []
114     @links = Link.where('link_class=? and owner_uuid=?'\
115                         ' and owner_uuid=tail_uuid'\
116                         ' and head_uuid in (?)',
117                         'name',
118                         @object.uuid,
119                         @objects.collect(&:uuid))
120     @object_list = {
121       :kind  => "arvados#objectList",
122       :etag => "",
123       :self_link => "",
124       :links => @links.as_api_response(nil),
125       :offset => offset_all,
126       :limit => limit_all,
127       :items_available => all_available,
128       :items => @objects.as_api_response(nil)
129     }
130     render json: @object_list
131   end
132
133   def catch_redirect_hint
134     if !current_user
135       if params.has_key?('redirect_to') then
136         session[:redirect_to] = params[:redirect_to]
137       end
138     end
139   end
140
141   begin
142     rescue_from Exception,
143     :with => :render_error
144     rescue_from ActiveRecord::RecordNotFound,
145     :with => :render_not_found
146     rescue_from ActionController::RoutingError,
147     :with => :render_not_found
148     rescue_from ActionController::UnknownController,
149     :with => :render_not_found
150     rescue_from AbstractController::ActionNotFound,
151     :with => :render_not_found
152     rescue_from ArvadosModel::PermissionDeniedError,
153     :with => :render_error
154   end
155
156   def render_404_if_no_object
157     render_not_found "Object not found" if !@object
158   end
159
160   def render_error(e)
161     logger.error e.inspect
162     if e.respond_to? :backtrace and e.backtrace
163       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
164     end
165     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
166       errors = @object.errors.full_messages
167     else
168       errors = [e.inspect]
169     end
170     status = e.respond_to?(:http_status) ? e.http_status : 422
171     render json: { errors: errors }, status: status
172   end
173
174   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
175     logger.error e.inspect
176     render json: { errors: ["Path not found"] }, status: 404
177   end
178
179   protected
180
181   def load_where_param
182     if params[:where].nil? or params[:where] == ""
183       @where = {}
184     elsif params[:where].is_a? Hash
185       @where = params[:where]
186     elsif params[:where].is_a? String
187       begin
188         @where = Oj.load(params[:where])
189         raise unless @where.is_a? Hash
190       rescue
191         raise ArgumentError.new("Could not parse \"where\" param as an object")
192       end
193     end
194     @where = @where.with_indifferent_access
195   end
196
197   def load_filters_param
198     @filters ||= []
199     if params[:filters].is_a? Array
200       @filters += params[:filters]
201     elsif params[:filters].is_a? String and !params[:filters].empty?
202       begin
203         f = Oj.load params[:filters]
204         raise unless f.is_a? Array
205         @filters += f
206       rescue
207         raise ArgumentError.new("Could not parse \"filters\" param as an array")
208       end
209     end
210   end
211
212   def default_orders
213     ["#{table_name}.modified_at desc"]
214   end
215
216   def load_limit_offset_order_params
217     if params[:limit]
218       unless params[:limit].to_s.match(/^\d+$/)
219         raise ArgumentError.new("Invalid value for limit parameter")
220       end
221       @limit = params[:limit].to_i
222     else
223       @limit = DEFAULT_LIMIT
224     end
225
226     if params[:offset]
227       unless params[:offset].to_s.match(/^\d+$/)
228         raise ArgumentError.new("Invalid value for offset parameter")
229       end
230       @offset = params[:offset].to_i
231     else
232       @offset = 0
233     end
234
235     @orders = []
236     if params[:order]
237       params[:order].split(',').each do |order|
238         attr, direction = order.strip.split " "
239         direction ||= 'asc'
240         if attr.match /^[a-z][_a-z0-9]+$/ and
241             model_class.columns.collect(&:name).index(attr) and
242             ['asc','desc'].index direction.downcase
243           @orders << "#{table_name}.#{attr} #{direction.downcase}"
244         end
245       end
246     end
247     if @orders.empty?
248       @orders = default_orders
249     end
250   end
251
252   def find_objects_for_index
253     @objects ||= model_class.readable_by(current_user)
254     apply_where_limit_order_params
255   end
256
257   def apply_where_limit_order_params
258     ar_table_name = @objects.table_name
259     if @filters.is_a? Array and @filters.any?
260       cond_out = []
261       param_out = []
262       @filters.each do |filter|
263         attr, operator, operand = filter
264         if !filter.is_a? Array
265           raise ArgumentError.new("Invalid element in filters array: #{filter.inspect} is not an array")
266         elsif !operator.is_a? String
267           raise ArgumentError.new("Invalid operator '#{operator}' (#{operator.class}) in filter")
268         elsif !model_class.searchable_columns(operator).index attr.to_s
269           raise ArgumentError.new("Invalid attribute '#{attr}' in filter")
270         end
271         case operator.downcase
272         when '=', '<', '<=', '>', '>=', 'like'
273           if operand.is_a? String
274             cond_out << "#{ar_table_name}.#{attr} #{operator} ?"
275             if (# any operator that operates on value rather than
276                 # representation:
277                 operator.match(/[<=>]/) and
278                 model_class.attribute_column(attr).type == :datetime)
279               operand = Time.parse operand
280             end
281             param_out << operand
282           elsif operand.nil? and operator == '='
283             cond_out << "#{ar_table_name}.#{attr} is null"
284           else
285             raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
286                                     "for '#{operator}' operator in filters")
287           end
288         when 'in'
289           if operand.is_a? Array
290             cond_out << "#{ar_table_name}.#{attr} IN (?)"
291             param_out << operand
292           else
293             raise ArgumentError.new("Invalid operand type '#{operand.class}' "\
294                                     "for '#{operator}' operator in filters")
295           end
296         when 'is_a'
297           operand = [operand] unless operand.is_a? Array
298           cond = []
299           operand.each do |op|
300               cl = ArvadosModel::kind_class op
301               if cl
302                 cond << "#{ar_table_name}.#{attr} like ?"
303                 param_out << cl.uuid_like_pattern
304               else
305                 cond << "1=0"
306               end
307           end
308           cond_out << cond.join(' OR ')
309         end
310       end
311       if cond_out.any?
312         @objects = @objects.where(cond_out.join(' AND '), *param_out)
313       end
314     end
315     if @where.is_a? Hash and @where.any?
316       conditions = ['1=1']
317       @where.each do |attr,value|
318         if attr.to_s == 'any'
319           if value.is_a?(Array) and
320               value.length == 2 and
321               value[0] == 'contains' then
322             ilikes = []
323             model_class.searchable_columns('ilike').each do |column|
324               # Including owner_uuid in an "any column" search will
325               # probably just return a lot of false positives.
326               next if column == 'owner_uuid'
327               ilikes << "#{ar_table_name}.#{column} ilike ?"
328               conditions << "%#{value[1]}%"
329             end
330             if ilikes.any?
331               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
332             end
333           end
334         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
335             model_class.columns.collect(&:name).index(attr.to_s)
336           if value.nil?
337             conditions[0] << " and #{ar_table_name}.#{attr} is ?"
338             conditions << nil
339           elsif value.is_a? Array
340             if value[0] == 'contains' and value.length == 2
341               conditions[0] << " and #{ar_table_name}.#{attr} like ?"
342               conditions << "%#{value[1]}%"
343             else
344               conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
345               conditions << value
346             end
347           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
348             conditions[0] << " and #{ar_table_name}.#{attr}=?"
349             conditions << value
350           elsif value.is_a? Hash
351             # Not quite the same thing as "equal?" but better than nothing?
352             value.each do |k,v|
353               if v.is_a? String
354                 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
355                 conditions << "%#{k}%#{v}%"
356               end
357             end
358           end
359         end
360       end
361       if conditions.length > 1
362         conditions[0].sub!(/^1=1 and /, '')
363         @objects = @objects.
364           where(*conditions)
365       end
366     end
367
368     @objects = @objects.order(@orders.join ", ") if @orders.any?
369     @objects = @objects.limit(@limit)
370     @objects = @objects.offset(@offset)
371   end
372
373   def resource_attrs
374     return @attrs if @attrs
375     @attrs = params[resource_name]
376     if @attrs.is_a? String
377       @attrs = Oj.load @attrs, symbol_keys: true
378     end
379     unless @attrs.is_a? Hash
380       message = "No #{resource_name}"
381       if resource_name.index('_')
382         message << " (or #{resource_name.camelcase(:lower)})"
383       end
384       message << " hash provided with request"
385       raise ArgumentError.new(message)
386     end
387     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
388       @attrs.delete x.to_sym
389     end
390     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
391     @attrs
392   end
393
394   # Authentication
395   def require_login
396     if current_user
397       true
398     else
399       respond_to do |format|
400         format.json {
401           render :json => { errors: ['Not logged in'] }.to_json, status: 401
402         }
403         format.html  {
404           redirect_to '/auth/joshid'
405         }
406       end
407       false
408     end
409   end
410
411   def admin_required
412     unless current_user and current_user.is_admin
413       render :json => { errors: ['Forbidden'] }.to_json, status: 403
414     end
415   end
416
417   def require_auth_scope
418     return false unless require_login
419     unless current_api_client_auth_has_scope("#{request.method} #{request.path}")
420       render :json => { errors: ['Forbidden'] }.to_json, status: 403
421     end
422   end
423
424   def thread_with_auth_info
425     Thread.current[:request_starttime] = Time.now
426     Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
427     begin
428       user = nil
429       api_client = nil
430       api_client_auth = nil
431       supplied_token =
432         params[:api_token] ||
433         params[:oauth_token] ||
434         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
435       if supplied_token
436         api_client_auth = ApiClientAuthorization.
437           includes(:api_client, :user).
438           where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
439           first
440         if api_client_auth.andand.user
441           session[:user_id] = api_client_auth.user.id
442           session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
443           session[:api_client_authorization_id] = api_client_auth.id
444           user = api_client_auth.user
445           api_client = api_client_auth.api_client
446         else
447           # Token seems valid, but points to a non-existent (deleted?) user.
448           api_client_auth = nil
449         end
450       elsif session[:user_id]
451         user = User.find(session[:user_id]) rescue nil
452         api_client = ApiClient.
453           where('uuid=?',session[:api_client_uuid]).
454           first rescue nil
455         if session[:api_client_authorization_id] then
456           api_client_auth = ApiClientAuthorization.
457             find session[:api_client_authorization_id]
458         end
459       end
460       Thread.current[:api_client_ip_address] = remote_ip
461       Thread.current[:api_client_authorization] = api_client_auth
462       Thread.current[:api_client_uuid] = api_client.andand.uuid
463       Thread.current[:api_client] = api_client
464       Thread.current[:user] = user
465       if api_client_auth
466         api_client_auth.last_used_at = Time.now
467         api_client_auth.last_used_by_ip_address = remote_ip
468         api_client_auth.save validate: false
469       end
470       yield
471     ensure
472       Thread.current[:api_client_ip_address] = nil
473       Thread.current[:api_client_authorization] = nil
474       Thread.current[:api_client_uuid] = nil
475       Thread.current[:api_client] = nil
476       Thread.current[:user] = nil
477     end
478   end
479   # /Authentication
480
481   def respond_with_json_by_default
482     html_index = request.accepts.index(Mime::HTML)
483     if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
484       request.format = :json
485     end
486   end
487
488   def model_class
489     controller_name.classify.constantize
490   end
491
492   def resource_name             # params[] key used by client
493     controller_name.singularize
494   end
495
496   def table_name
497     controller_name
498   end
499
500   def find_object_by_uuid
501     if params[:id] and params[:id].match /\D/
502       params[:uuid] = params.delete :id
503     end
504     @where = { uuid: params[:uuid] }
505     @offset = 0
506     @limit = 1
507     @orders = []
508     @filters = []
509     @objects = nil
510     find_objects_for_index
511     @object = @objects.first
512   end
513
514   def reload_object_before_update
515     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
516     # error when updating an object which was retrieved using a join.
517     if @object.andand.readonly?
518       @object = model_class.find_by_uuid(@objects.first.uuid)
519     end
520   end
521
522   def self.accept_attribute_as_json(attr, force_class=nil)
523     before_filter lambda { accept_attribute_as_json attr, force_class }
524   end
525   accept_attribute_as_json :properties, Hash
526   accept_attribute_as_json :info, Hash
527   def accept_attribute_as_json(attr, force_class)
528     if params[resource_name] and resource_attrs.is_a? Hash
529       if resource_attrs[attr].is_a? String
530         resource_attrs[attr] = Oj.load(resource_attrs[attr],
531                                        symbol_keys: false)
532         if force_class and !resource_attrs[attr].is_a? force_class
533           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
534         end
535       elsif resource_attrs[attr].is_a? Hash
536         # Convert symbol keys to strings (in hashes provided by
537         # resource_attrs)
538         resource_attrs[attr] = resource_attrs[attr].
539           with_indifferent_access.to_hash
540       end
541     end
542   end
543
544   def render_list
545     @object_list = {
546       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
547       :etag => "",
548       :self_link => "",
549       :offset => @offset,
550       :limit => @limit,
551       :items => @objects.as_api_response(nil)
552     }
553     if @objects.respond_to? :except
554       @object_list[:items_available] = @objects.
555         except(:limit).except(:offset).
556         count(:id, distinct: true)
557     end
558     render json: @object_list
559   end
560
561   def remote_ip
562     # Caveat: this is highly dependent on the proxy setup. YMMV.
563     if request.headers.has_key?('HTTP_X_REAL_IP') then
564       # We're behind a reverse proxy
565       @remote_ip = request.headers['HTTP_X_REAL_IP']
566     else
567       # Hopefully, we are not!
568       @remote_ip = request.env['REMOTE_ADDR']
569     end
570   end
571
572   def self._index_requires_parameters
573     {
574       filters: { type: 'array', required: false },
575       where: { type: 'object', required: false },
576       order: { type: 'string', required: false },
577       limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
578       offset: { type: 'integer', required: false, default: 0 },
579     }
580   end
581
582   def client_accepts_plain_text_stream
583     (request.headers['Accept'].split(' ') &
584      ['text/plain', '*/*']).count > 0
585   end
586
587   def render *opts
588     if opts.first
589       response = opts.first[:json]
590       if response.is_a?(Hash) &&
591           params[:_profile] &&
592           Thread.current[:request_starttime]
593         response[:_profile] = {
594           request_time: Time.now - Thread.current[:request_starttime]
595         }
596       end
597     end
598     super *opts
599   end
600
601   def select_theme
602     return Rails.configuration.arvados_theme
603   end
604 end