Add tests to expose some token handling bugs.
[arvados.git] / services / api / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include CurrentApiClient
3
4   respond_to :json
5   protect_from_forgery
6   around_filter :thread_with_auth_info, :except => [:render_error, :render_not_found]
7
8   before_filter :remote_ip
9   before_filter :require_auth_scope_all, :except => :render_not_found
10   before_filter :catch_redirect_hint
11
12   before_filter :load_where_param, :only => :index
13   before_filter :load_filters_param, :only => :index
14   before_filter :find_objects_for_index, :only => :index
15   before_filter :find_object_by_uuid, :except => [:index, :create,
16                                                   :render_error,
17                                                   :render_not_found]
18   before_filter :reload_object_before_update, :only => :update
19   before_filter :render_404_if_no_object, except: [:index, :create,
20                                                    :render_error,
21                                                    :render_not_found]
22
23   attr_accessor :resource_attrs
24
25   def index
26     @objects.uniq!(&:id)
27     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
28       @objects.each(&:eager_load_associations)
29     end
30     render_list
31   end
32
33   def show
34     render json: @object.as_api_response
35   end
36
37   def create
38     @object = model_class.new resource_attrs
39     if @object.save
40       show
41     else
42       raise "Save failed"
43     end
44   end
45
46   def update
47     attrs_to_update = resource_attrs.reject { |k,v|
48       [:kind, :etag, :href].index k
49     }
50     if @object.update_attributes attrs_to_update
51       show
52     else
53       raise "Update failed"
54     end
55   end
56
57   def destroy
58     @object.destroy
59     show
60   end
61
62   def catch_redirect_hint
63     if !current_user
64       if params.has_key?('redirect_to') then
65         session[:redirect_to] = params[:redirect_to]
66       end
67     end
68   end
69
70   begin
71     rescue_from Exception,
72     :with => :render_error
73     rescue_from ActiveRecord::RecordNotFound,
74     :with => :render_not_found
75     rescue_from ActionController::RoutingError,
76     :with => :render_not_found
77     rescue_from ActionController::UnknownController,
78     :with => :render_not_found
79     rescue_from AbstractController::ActionNotFound,
80     :with => :render_not_found
81     rescue_from ArvadosModel::PermissionDeniedError,
82     :with => :render_error
83   end
84
85   def render_404_if_no_object
86     render_not_found "Object not found" if !@object
87   end
88
89   def render_error(e)
90     logger.error e.inspect
91     if e.respond_to? :backtrace and e.backtrace
92       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
93     end
94     if @object and @object.errors and @object.errors.full_messages and not @object.errors.full_messages.empty?
95       errors = @object.errors.full_messages
96     else
97       errors = [e.inspect]
98     end
99     status = e.respond_to?(:http_status) ? e.http_status : 422
100     render json: { errors: errors }, status: status
101   end
102
103   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
104     logger.error e.inspect
105     render json: { errors: ["Path not found"] }, status: 404
106   end
107
108   protected
109
110   def load_where_param
111     if params[:where].nil? or params[:where] == ""
112       @where = {}
113     elsif params[:where].is_a? Hash
114       @where = params[:where]
115     elsif params[:where].is_a? String
116       begin
117         @where = Oj.load(params[:where])
118         raise unless @where.is_a? Hash
119       rescue
120         raise ArgumentError.new("Could not parse \"where\" param as an object")
121       end
122     end
123     @where = @where.with_indifferent_access
124   end
125
126   def load_filters_param
127     if params[:filters].is_a? Array
128       @filters = params[:filters]
129     elsif params[:filters].is_a? String and !params[:filters].empty?
130       begin
131         @filters = Oj.load params[:filters]
132         raise unless @filters.is_a? Array
133       rescue
134         raise ArgumentError.new("Could not parse \"filters\" param as an array")
135       end
136     end
137   end
138
139   def find_objects_for_index
140     @objects ||= model_class.readable_by(current_user)
141     apply_where_limit_order_params
142   end
143
144   def apply_where_limit_order_params
145     if @filters.is_a? Array and @filters.any?
146       cond_out = []
147       param_out = []
148       @filters.each do |attr, operator, operand|
149         if !model_class.searchable_columns(operator).index attr.to_s
150           raise ArgumentError.new("Invalid attribute '#{attr}' in condition")
151         end
152         case operator.downcase
153         when '=', '<', '<=', '>', '>=', 'like'
154           if operand.is_a? String
155             cond_out << "#{table_name}.#{attr} #{operator} ?"
156             if (# any operator that operates on value rather than
157                 # representation:
158                 operator.match(/[<=>]/) and
159                 model_class.attribute_column(attr).type == :datetime)
160               operand = Time.parse operand
161             end
162             param_out << operand
163           end
164         when 'in'
165           if operand.is_a? Array
166             cond_out << "#{table_name}.#{attr} IN (?)"
167             param_out << operand
168           end
169         end
170       end
171       if cond_out.any?
172         @objects = @objects.where(cond_out.join(' AND '), *param_out)
173       end
174     end
175     if @where.is_a? Hash and @where.any?
176       conditions = ['1=1']
177       @where.each do |attr,value|
178         if attr.to_s == 'any'
179           if value.is_a?(Array) and
180               value.length == 2 and
181               value[0] == 'contains' then
182             ilikes = []
183             model_class.searchable_columns('ilike').each do |column|
184               ilikes << "#{table_name}.#{column} ilike ?"
185               conditions << "%#{value[1]}%"
186             end
187             if ilikes.any?
188               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
189             end
190           end
191         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
192             model_class.columns.collect(&:name).index(attr.to_s)
193           if value.nil?
194             conditions[0] << " and #{table_name}.#{attr} is ?"
195             conditions << nil
196           elsif value.is_a? Array
197             if value[0] == 'contains' and value.length == 2
198               conditions[0] << " and #{table_name}.#{attr} like ?"
199               conditions << "%#{value[1]}%"
200             else
201               conditions[0] << " and #{table_name}.#{attr} in (?)"
202               conditions << value
203             end
204           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
205             conditions[0] << " and #{table_name}.#{attr}=?"
206             conditions << value
207           elsif value.is_a? Hash
208             # Not quite the same thing as "equal?" but better than nothing?
209             value.each do |k,v|
210               if v.is_a? String
211                 conditions[0] << " and #{table_name}.#{attr} ilike ?"
212                 conditions << "%#{k}%#{v}%"
213               end
214             end
215           end
216         end
217       end
218       if conditions.length > 1
219         conditions[0].sub!(/^1=1 and /, '')
220         @objects = @objects.
221           where(*conditions)
222       end
223     end
224
225     if params[:limit]
226       begin
227         @limit = params[:limit].to_i
228       rescue
229         raise ArgumentError.new("Invalid value for limit parameter")
230       end
231     else
232       @limit = 100
233     end
234     @objects = @objects.limit(@limit)
235
236     orders = []
237
238     if params[:offset]
239       begin
240         @objects = @objects.offset(params[:offset].to_i)
241         @offset = params[:offset].to_i
242       rescue
243         raise ArgumentError.new("Invalid value for limit parameter")
244       end
245     else
246       @offset = 0
247     end      
248
249     orders = []
250     if params[:order]
251       params[:order].split(',').each do |order|
252         attr, direction = order.strip.split " "
253         direction ||= 'asc'
254         if attr.match /^[a-z][_a-z0-9]+$/ and
255             model_class.columns.collect(&:name).index(attr) and
256             ['asc','desc'].index direction.downcase
257           orders << "#{table_name}.#{attr} #{direction.downcase}"
258         end
259       end
260     end
261     if orders.empty?
262       orders << "#{table_name}.modified_at desc"
263     end
264     @objects = @objects.order(orders.join ", ")
265   end
266
267   def resource_attrs
268     return @attrs if @attrs
269     @attrs = params[resource_name]
270     if @attrs.is_a? String
271       @attrs = Oj.load @attrs, symbol_keys: true
272     end
273     unless @attrs.is_a? Hash
274       message = "No #{resource_name}"
275       if resource_name.index('_')
276         message << " (or #{resource_name.camelcase(:lower)})"
277       end
278       message << " hash provided with request"
279       raise ArgumentError.new(message)
280     end
281     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
282       @attrs.delete x.to_sym
283     end
284     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
285     @attrs
286   end
287
288   # Authentication
289   def require_login
290     if current_user
291       true
292     else
293       respond_to do |format|
294         format.json {
295           render :json => { errors: ['Not logged in'] }.to_json, status: 401
296         }
297         format.html  {
298           redirect_to '/auth/joshid'
299         }
300       end
301       false
302     end
303   end
304
305   def admin_required
306     unless current_user and current_user.is_admin
307       render :json => { errors: ['Forbidden'] }.to_json, status: 403
308     end
309   end
310
311   def require_auth_scope_all
312     require_login and require_auth_scope(['all'])
313   end
314
315   def require_auth_scope(ok_scopes)
316     unless current_api_client_auth_has_scope(ok_scopes)
317       render :json => { errors: ['Forbidden'] }.to_json, status: 403
318     end
319   end
320
321   def thread_with_auth_info
322     Thread.current[:request_starttime] = Time.now
323     Thread.current[:api_url_base] = root_url.sub(/\/$/,'') + '/arvados/v1'
324     begin
325       user = nil
326       api_client = nil
327       api_client_auth = nil
328       supplied_token =
329         params[:api_token] ||
330         params[:oauth_token] ||
331         request.headers["Authorization"].andand.match(/OAuth2 ([a-z0-9]+)/).andand[1]
332       if supplied_token
333         api_client_auth = ApiClientAuthorization.
334           includes(:api_client, :user).
335           where('api_token=? and (expires_at is null or expires_at > CURRENT_TIMESTAMP)', supplied_token).
336           first
337         if api_client_auth.andand.user
338           session[:user_id] = api_client_auth.user.id
339           session[:api_client_uuid] = api_client_auth.api_client.andand.uuid
340           session[:api_client_authorization_id] = api_client_auth.id
341           user = api_client_auth.user
342           api_client = api_client_auth.api_client
343         end
344       elsif session[:user_id]
345         user = User.find(session[:user_id]) rescue nil
346         api_client = ApiClient.
347           where('uuid=?',session[:api_client_uuid]).
348           first rescue nil
349         if session[:api_client_authorization_id] then
350           api_client_auth = ApiClientAuthorization.
351             find session[:api_client_authorization_id]
352         end
353       end
354       Thread.current[:api_client_ip_address] = remote_ip
355       Thread.current[:api_client_authorization] = api_client_auth
356       Thread.current[:api_client_uuid] = api_client.andand.uuid
357       Thread.current[:api_client] = api_client
358       Thread.current[:user] = user
359       if api_client_auth
360         api_client_auth.last_used_at = Time.now
361         api_client_auth.last_used_by_ip_address = remote_ip
362         api_client_auth.save validate: false
363       end
364       yield
365     ensure
366       Thread.current[:api_client_ip_address] = nil
367       Thread.current[:api_client_authorization] = nil
368       Thread.current[:api_client_uuid] = nil
369       Thread.current[:api_client] = nil
370       Thread.current[:user] = nil
371     end
372   end
373   # /Authentication
374
375   def model_class
376     controller_name.classify.constantize
377   end
378
379   def resource_name             # params[] key used by client
380     controller_name.singularize
381   end
382
383   def table_name
384     controller_name
385   end
386
387   def find_object_by_uuid
388     if params[:id] and params[:id].match /\D/
389       params[:uuid] = params.delete :id
390     end
391     @where = { uuid: params[:uuid] }
392     find_objects_for_index
393     @object = @objects.first
394   end
395
396   def reload_object_before_update
397     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
398     # error when updating an object which was retrieved using a join.
399     if @object.andand.readonly?
400       @object = model_class.find_by_uuid(@objects.first.uuid)
401     end
402   end
403
404   def self.accept_attribute_as_json(attr, force_class=nil)
405     before_filter lambda { accept_attribute_as_json attr, force_class }
406   end
407   accept_attribute_as_json :properties, Hash
408   accept_attribute_as_json :info, Hash
409   def accept_attribute_as_json(attr, force_class)
410     if params[resource_name] and resource_attrs.is_a? Hash
411       if resource_attrs[attr].is_a? String
412         resource_attrs[attr] = Oj.load(resource_attrs[attr],
413                                        symbol_keys: false)
414         if force_class and !resource_attrs[attr].is_a? force_class
415           raise TypeError.new("#{resource_name}[#{attr.to_s}] must be a #{force_class.to_s}")
416         end
417       elsif resource_attrs[attr].is_a? Hash
418         # Convert symbol keys to strings (in hashes provided by
419         # resource_attrs)
420         resource_attrs[attr] = resource_attrs[attr].
421           with_indifferent_access.to_hash
422       end
423     end
424   end
425
426   def render_list
427     @object_list = {
428       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
429       :etag => "",
430       :self_link => "",
431       :offset => @offset,
432       :limit => @limit,
433       :items => @objects.as_api_response(nil)
434     }
435     if @objects.respond_to? :except
436       @object_list[:items_available] = @objects.
437         except(:limit).except(:offset).
438         count(:id, distinct: true)
439     end
440     render json: @object_list
441   end
442
443   def remote_ip
444     # Caveat: this is highly dependent on the proxy setup. YMMV.
445     if request.headers.has_key?('HTTP_X_REAL_IP') then
446       # We're behind a reverse proxy
447       @remote_ip = request.headers['HTTP_X_REAL_IP']
448     else
449       # Hopefully, we are not!
450       @remote_ip = request.env['REMOTE_ADDR']
451     end
452   end
453
454   def self._index_requires_parameters
455     {
456       filters: { type: 'array', required: false },
457       where: { type: 'object', required: false },
458       order: { type: 'string', required: false }
459     }
460   end
461   
462   def client_accepts_plain_text_stream
463     (request.headers['Accept'].split(' ') &
464      ['text/plain', '*/*']).count > 0
465   end
466
467   def render *opts
468     if opts.first
469       response = opts.first[:json]
470       if response.is_a?(Hash) &&
471           params[:_profile] &&
472           Thread.current[:request_starttime]
473         response[:_profile] = {
474           request_time: Time.now - Thread.current[:request_starttime]
475         }
476       end
477     end
478     super *opts
479   end
480 end