api: Accept JSON-formatted reader token array.
[arvados.git] / services / api / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3   include ThemesForRails::ActionController
4
5   ERROR_ACTIONS = [:render_error, :render_not_found]
6
7   respond_to :json
8   protect_from_forgery
9
10   around_filter :thread_with_auth_info, except: ERROR_ACTIONS
11   before_filter :respond_with_json_by_default
12   before_filter :remote_ip
13   before_filter :load_read_auths
14   before_filter :require_auth_scope, except: ERROR_ACTIONS
15
16   before_filter :catch_redirect_hint
17   before_filter(:find_object_by_uuid,
18                 except: [:index, :create] + ERROR_ACTIONS)
19   before_filter :load_limit_offset_order_params, only: [:index, :owned_items]
20   before_filter :load_where_param, only: [:index, :owned_items]
21   before_filter :load_filters_param, only: [:index, :owned_items]
22   before_filter :find_objects_for_index, :only => :index
23   before_filter :reload_object_before_update, :only => :update
24   before_filter(:render_404_if_no_object,
25                 except: [:index, :create] + ERROR_ACTIONS)
26
27   theme :select_theme
28
29   attr_accessor :resource_attrs
30
31   DEFAULT_LIMIT = 100
32
33   def index
34     @objects.uniq!(&:id)
35     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
36       @objects.each(&:eager_load_associations)
37     end
38     render_list
39   end
40
41   def show
42     render json: @object.as_api_response
43   end
44
45   def create
46     @object = model_class.new resource_attrs
47     @object.save!
48     show
49   end
50
51   def update
52     attrs_to_update = resource_attrs.reject { |k,v|
53       [:kind, :etag, :href].index k
54     }
55     @object.update_attributes! attrs_to_update
56     show
57   end
58
59   def destroy
60     @object.destroy
61     show
62   end
63
64   def self._owned_items_requires_parameters
65     _index_requires_parameters.
66       merge({
67               include_linked: {
68                 type: 'boolean', required: false, default: false
69               },
70             })
71   end
72
73   def owned_items
74     all_objects = []
75     all_available = 0
76
77     # Trick apply_where_limit_order_params into applying suitable
78     # per-table values. *_all are the real ones we'll apply to the
79     # aggregate set.
80     limit_all = @limit
81     offset_all = @offset
82     @orders = []
83
84     ArvadosModel.descendants.
85       reject(&:abstract_class?).
86       sort_by(&:to_s).
87       each do |klass|
88       case klass.to_s
89         # We might expect klass==Link etc. here, but we would be
90         # disappointed: when Rails reloads model classes, we get two
91         # distinct classes called Link which do not equal each
92         # other. But we can still rely on klass.to_s to be "Link".
93       when 'ApiClientAuthorization'
94         # Do not want.
95       else
96         @objects = klass.readable_by(*@read_users)
97         cond_sql = "#{klass.table_name}.owner_uuid = ?"
98         cond_params = [@object.uuid]
99         if params[:include_linked]
100           @objects = @objects.
101             joins("LEFT JOIN links mng_links"\
102                   " ON mng_links.link_class=#{klass.sanitize 'permission'}"\
103                   "    AND mng_links.name=#{klass.sanitize 'can_manage'}"\
104                   "    AND mng_links.tail_uuid=#{klass.sanitize @object.uuid}"\
105                   "    AND mng_links.head_uuid=#{klass.table_name}.uuid")
106           cond_sql += " OR mng_links.uuid IS NOT NULL"
107         end
108         @objects = @objects.where(cond_sql, *cond_params).order(:uuid)
109         @limit = limit_all - all_objects.count
110         apply_where_limit_order_params
111         items_available = @objects.
112           except(:limit).except(:offset).
113           count(:id, distinct: true)
114         all_available += items_available
115         @offset = [@offset - items_available, 0].max
116
117         all_objects += @objects.to_a
118       end
119     end
120     @objects = all_objects || []
121     @object_list = {
122       :kind  => "arvados#objectList",
123       :etag => "",
124       :self_link => "",
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(*@read_users)
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 load_read_auths
396     @read_auths = []
397     if current_api_client_authorization
398       @read_auths << current_api_client_authorization
399     end
400     # Load reader tokens if this is a read request.
401     # If there are too many reader tokens, assume the request is malicious
402     # and ignore it.
403     if request.get? and params[:reader_tokens] and
404         params[:reader_tokens].size < 100
405       @read_auths += ApiClientAuthorization
406         .includes(:user)
407         .where('api_token IN (?) AND
408                 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
409                params[:reader_tokens])
410         .all
411     end
412     @read_auths.select! { |auth| auth.scopes_allow_request? request }
413     @read_users = @read_auths.map { |auth| auth.user }.uniq
414   end
415
416   def require_login
417     if not current_user
418       respond_to do |format|
419         format.json {
420           render :json => { errors: ['Not logged in'] }.to_json, status: 401
421         }
422         format.html {
423           redirect_to '/auth/joshid'
424         }
425       end
426       false
427     end
428   end
429
430   def admin_required
431     unless current_user and current_user.is_admin
432       render :json => { errors: ['Forbidden'] }.to_json, status: 403
433     end
434   end
435
436   def require_auth_scope
437     if @read_auths.empty?
438       if require_login != false
439         render :json => { errors: ['Forbidden'] }.to_json, status: 403
440       end
441       false
442     end
443   end
444
445   def thread_with_auth_info
446     Thread.current[:request_starttime] = Time.now
447     Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
448     begin
449       user = nil
450       api_client = nil
451       api_client_auth = nil
452       supplied_token =
453         params[:api_token] ||
454         params[:oauth_token] ||
455         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
456       if supplied_token
457         api_client_auth = ApiClientAuthorization.
458           includes(:api_client, :user).
459           where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
460           first
461         if api_client_auth.andand.user
462           session[:user_id] = api_client_auth.user.id
463           session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
464           session[:api_client_authorization_id] = api_client_auth.id
465           user = api_client_auth.user
466           api_client = api_client_auth.api_client
467         else
468           # Token seems valid, but points to a non-existent (deleted?) user.
469           api_client_auth = nil
470         end
471       elsif session[:user_id]
472         user = User.find(session[:user_id]) rescue nil
473         api_client = ApiClient.
474           where('uuid=?',session[:api_client_uuid]).
475           first rescue nil
476         if session[:api_client_authorization_id] then
477           api_client_auth = ApiClientAuthorization.
478             find session[:api_client_authorization_id]
479         end
480       end
481       Thread.current[:api_client_ip_address] = remote_ip
482       Thread.current[:api_client_authorization] = api_client_auth
483       Thread.current[:api_client_uuid] = api_client.andand.uuid
484       Thread.current[:api_client] = api_client
485       Thread.current[:user] = user
486       if api_client_auth
487         api_client_auth.last_used_at = Time.now
488         api_client_auth.last_used_by_ip_address = remote_ip
489         api_client_auth.save validate: false
490       end
491       yield
492     ensure
493       Thread.current[:api_client_ip_address] = nil
494       Thread.current[:api_client_authorization] = nil
495       Thread.current[:api_client_uuid] = nil
496       Thread.current[:api_client] = nil
497       Thread.current[:user] = nil
498     end
499   end
500   # /Authentication
501
502   def respond_with_json_by_default
503     html_index = request.accepts.index(Mime::HTML)
504     if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
505       request.format = :json
506     end
507   end
508
509   def model_class
510     controller_name.classify.constantize
511   end
512
513   def resource_name             # params[] key used by client
514     controller_name.singularize
515   end
516
517   def table_name
518     controller_name
519   end
520
521   def find_object_by_uuid
522     if params[:id] and params[:id].match /\D/
523       params[:uuid] = params.delete :id
524     end
525     @where = { uuid: params[:uuid] }
526     @offset = 0
527     @limit = 1
528     @orders = []
529     @filters = []
530     @objects = nil
531     find_objects_for_index
532     @object = @objects.first
533   end
534
535   def reload_object_before_update
536     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
537     # error when updating an object which was retrieved using a join.
538     if @object.andand.readonly?
539       @object = model_class.find_by_uuid(@objects.first.uuid)
540     end
541   end
542
543   def load_json_value(hash, key, must_be_class=nil)
544     if hash[key].is_a? String
545       hash[key] = Oj.load(hash[key], symbol_keys: false)
546       if must_be_class and !hash[key].is_a? must_be_class
547         raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
548       end
549     end
550   end
551
552   def self.accept_attribute_as_json(attr, must_be_class=nil)
553     before_filter lambda { accept_attribute_as_json attr, must_be_class }
554   end
555   accept_attribute_as_json :properties, Hash
556   accept_attribute_as_json :info, Hash
557   def accept_attribute_as_json(attr, must_be_class)
558     if params[resource_name] and resource_attrs.is_a? Hash
559       if resource_attrs[attr].is_a? Hash
560         # Convert symbol keys to strings (in hashes provided by
561         # resource_attrs)
562         resource_attrs[attr] = resource_attrs[attr].
563           with_indifferent_access.to_hash
564       else
565         load_json_value(resource_attrs, attr, must_be_class)
566       end
567     end
568   end
569
570   def self.accept_param_as_json(key, must_be_class=nil)
571     prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
572   end
573   accept_param_as_json :reader_tokens, Array
574
575   def render_list
576     @object_list = {
577       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
578       :etag => "",
579       :self_link => "",
580       :offset => @offset,
581       :limit => @limit,
582       :items => @objects.as_api_response(nil)
583     }
584     if @objects.respond_to? :except
585       @object_list[:items_available] = @objects.
586         except(:limit).except(:offset).
587         count(:id, distinct: true)
588     end
589     render json: @object_list
590   end
591
592   def remote_ip
593     # Caveat: this is highly dependent on the proxy setup. YMMV.
594     if request.headers.has_key?('HTTP_X_REAL_IP') then
595       # We're behind a reverse proxy
596       @remote_ip = request.headers['HTTP_X_REAL_IP']
597     else
598       # Hopefully, we are not!
599       @remote_ip = request.env['REMOTE_ADDR']
600     end
601   end
602
603   def self._index_requires_parameters
604     {
605       filters: { type: 'array', required: false },
606       where: { type: 'object', required: false },
607       order: { type: 'string', required: false },
608       limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
609       offset: { type: 'integer', required: false, default: 0 },
610     }
611   end
612
613   def client_accepts_plain_text_stream
614     (request.headers['Accept'].split(' ') &
615      ['text/plain', '*/*']).count > 0
616   end
617
618   def render *opts
619     if opts.first
620       response = opts.first[:json]
621       if response.is_a?(Hash) &&
622           params[:_profile] &&
623           Thread.current[:request_starttime]
624         response[:_profile] = {
625           request_time: Time.now - Thread.current[:request_starttime]
626         }
627       end
628     end
629     super *opts
630   end
631
632   def select_theme
633     return Rails.configuration.arvados_theme
634   end
635 end