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