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