8784: Fix test for latest firefox.
[arvados.git] / services / api / app / controllers / application_controller.rb
1 require 'safe_json'
2
3 module ApiTemplateOverride
4   def allowed_to_render?(fieldset, field, model, options)
5     return false if !super
6     if options[:select]
7       options[:select].include? field.to_s
8     else
9       true
10     end
11   end
12 end
13
14 class ActsAsApi::ApiTemplate
15   prepend ApiTemplateOverride
16 end
17
18 require 'load_param'
19
20 class ApplicationController < ActionController::Base
21   include ThemesForRails::ActionController
22   include CurrentApiClient
23   include LoadParam
24   include DbCurrentTime
25
26   respond_to :json
27   protect_from_forgery
28
29   ERROR_ACTIONS = [:render_error, :render_not_found]
30
31   before_filter :disable_api_methods
32   before_filter :set_cors_headers
33   before_filter :respond_with_json_by_default
34   before_filter :remote_ip
35   before_filter :load_read_auths
36   before_filter :require_auth_scope, except: ERROR_ACTIONS
37
38   before_filter :catch_redirect_hint
39   before_filter(:find_object_by_uuid,
40                 except: [:index, :create] + ERROR_ACTIONS)
41   before_filter :load_required_parameters
42   before_filter :load_limit_offset_order_params, only: [:index, :contents]
43   before_filter :load_where_param, only: [:index, :contents]
44   before_filter :load_filters_param, only: [:index, :contents]
45   before_filter :find_objects_for_index, :only => :index
46   before_filter :reload_object_before_update, :only => :update
47   before_filter(:render_404_if_no_object,
48                 except: [:index, :create] + ERROR_ACTIONS)
49
50   theme Rails.configuration.arvados_theme
51
52   attr_writer :resource_attrs
53
54   begin
55     rescue_from(Exception,
56                 ArvadosModel::PermissionDeniedError,
57                 :with => :render_error)
58     rescue_from(ActiveRecord::RecordNotFound,
59                 ActionController::RoutingError,
60                 ActionController::UnknownController,
61                 AbstractController::ActionNotFound,
62                 :with => :render_not_found)
63   end
64
65   def initialize *args
66     super
67     @object = nil
68     @objects = nil
69     @offset = nil
70     @limit = nil
71     @select = nil
72     @distinct = nil
73     @response_resource_name = nil
74     @attrs = nil
75   end
76
77   def default_url_options
78     if Rails.configuration.host
79       {:host => Rails.configuration.host}
80     else
81       {}
82     end
83   end
84
85   def index
86     if @select.nil? || @select.include?("id")
87       @objects = @objects.uniq(&:id)
88     end
89     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
90       @objects.each(&:eager_load_associations)
91     end
92     render_list
93   end
94
95   def show
96     send_json @object.as_api_response(nil, select: @select)
97   end
98
99   def create
100     @object = model_class.new resource_attrs
101
102     if @object.respond_to?(:name) && params[:ensure_unique_name]
103       @object.save_with_unique_name!
104     else
105       @object.save!
106     end
107
108     show
109   end
110
111   def update
112     attrs_to_update = resource_attrs.reject { |k,v|
113       [:kind, :etag, :href].index k
114     }
115     @object.update_attributes! attrs_to_update
116     show
117   end
118
119   def destroy
120     @object.destroy
121     show
122   end
123
124   def catch_redirect_hint
125     if !current_user
126       if params.has_key?('redirect_to') then
127         session[:redirect_to] = params[:redirect_to]
128       end
129     end
130   end
131
132   def render_404_if_no_object
133     render_not_found "Object not found" if !@object
134   end
135
136   def render_error(e)
137     logger.error e.inspect
138     if e.respond_to? :backtrace and e.backtrace
139       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
140     end
141     if (@object.respond_to? :errors and
142         @object.errors.andand.full_messages.andand.any?)
143       errors = @object.errors.full_messages
144       logger.error errors.inspect
145     else
146       errors = [e.inspect]
147     end
148     status = e.respond_to?(:http_status) ? e.http_status : 422
149     send_error(*errors, status: status)
150   end
151
152   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
153     logger.error e.inspect
154     send_error("Path not found", status: 404)
155   end
156
157   protected
158
159   def send_error(*args)
160     if args.last.is_a? Hash
161       err = args.pop
162     else
163       err = {}
164     end
165     err[:errors] ||= args
166     err[:error_token] = [Time.now.utc.to_i, "%08x" % rand(16 ** 8)].join("+")
167     status = err.delete(:status) || 422
168     logger.error "Error #{err[:error_token]}: #{status}"
169     send_json err, status: status
170   end
171
172   def send_json response, opts={}
173     # The obvious render(json: ...) forces a slow JSON encoder. See
174     # #3021 and commit logs. Might be fixed in Rails 4.1.
175     render({
176              text: SafeJSON.dump(response).html_safe,
177              content_type: 'application/json'
178            }.merge opts)
179   end
180
181   def find_objects_for_index
182     @objects ||= model_class.readable_by(*@read_users)
183     apply_where_limit_order_params
184   end
185
186   def apply_filters model_class=nil
187     model_class ||= self.model_class
188     @objects = model_class.apply_filters(@objects, @filters)
189   end
190
191   def apply_where_limit_order_params model_class=nil
192     model_class ||= self.model_class
193     apply_filters model_class
194
195     ar_table_name = @objects.table_name
196     if @where.is_a? Hash and @where.any?
197       conditions = ['1=1']
198       @where.each do |attr,value|
199         if attr.to_s == 'any'
200           if value.is_a?(Array) and
201               value.length == 2 and
202               value[0] == 'contains' then
203             ilikes = []
204             model_class.searchable_columns('ilike').each do |column|
205               # Including owner_uuid in an "any column" search will
206               # probably just return a lot of false positives.
207               next if column == 'owner_uuid'
208               ilikes << "#{ar_table_name}.#{column} ilike ?"
209               conditions << "%#{value[1]}%"
210             end
211             if ilikes.any?
212               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
213             end
214           end
215         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
216             model_class.columns.collect(&:name).index(attr.to_s)
217           if value.nil?
218             conditions[0] << " and #{ar_table_name}.#{attr} is ?"
219             conditions << nil
220           elsif value.is_a? Array
221             if value[0] == 'contains' and value.length == 2
222               conditions[0] << " and #{ar_table_name}.#{attr} like ?"
223               conditions << "%#{value[1]}%"
224             else
225               conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
226               conditions << value
227             end
228           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
229             conditions[0] << " and #{ar_table_name}.#{attr}=?"
230             conditions << value
231           elsif value.is_a? Hash
232             # Not quite the same thing as "equal?" but better than nothing?
233             value.each do |k,v|
234               if v.is_a? String
235                 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
236                 conditions << "%#{k}%#{v}%"
237               end
238             end
239           end
240         end
241       end
242       if conditions.length > 1
243         conditions[0].sub!(/^1=1 and /, '')
244         @objects = @objects.
245           where(*conditions)
246       end
247     end
248
249     if @select
250       unless action_name.in? %w(create update destroy)
251         # Map attribute names in @select to real column names, resolve
252         # those to fully-qualified SQL column names, and pass the
253         # resulting string to the select method.
254         columns_list = model_class.columns_for_attributes(@select).
255           map { |s| "#{ar_table_name}.#{ActiveRecord::Base.connection.quote_column_name s}" }
256         @objects = @objects.select(columns_list.join(", "))
257       end
258
259       # This information helps clients understand what they're seeing
260       # (Workbench always expects it), but they can't select it explicitly
261       # because it's not an SQL column.  Always add it.
262       # (This is harmless, given that clients can deduce what they're
263       # looking at by the returned UUID anyway.)
264       @select |= ["kind"]
265     end
266     @objects = @objects.order(@orders.join ", ") if @orders.any?
267     @objects = @objects.limit(@limit)
268     @objects = @objects.offset(@offset)
269     @objects = @objects.uniq(@distinct) if not @distinct.nil?
270   end
271
272   # limit_database_read ensures @objects (which must be an
273   # ActiveRelation) does not return too many results to fit in memory,
274   # by previewing the results and calling @objects.limit() if
275   # necessary.
276   def limit_database_read(model_class:)
277     return if @limit == 0 || @limit == 1
278     model_class ||= self.model_class
279     limit_columns = model_class.limit_index_columns_read
280     limit_columns &= model_class.columns_for_attributes(@select) if @select
281     return if limit_columns.empty?
282     model_class.transaction do
283       limit_query = @objects.
284         except(:select, :distinct).
285         select("(%s) as read_length" %
286                limit_columns.map { |s| "octet_length(#{model_class.table_name}.#{s})" }.join(" + "))
287       new_limit = 0
288       read_total = 0
289       limit_query.each do |record|
290         new_limit += 1
291         read_total += record.read_length.to_i
292         if read_total >= Rails.configuration.max_index_database_read
293           new_limit -= 1 if new_limit > 1
294           @limit = new_limit
295           break
296         elsif new_limit >= @limit
297           break
298         end
299       end
300       @objects = @objects.limit(@limit)
301       # Force @objects to run its query inside this transaction.
302       @objects.each { |_| break }
303     end
304   end
305
306   def resource_attrs
307     return @attrs if @attrs
308     @attrs = params[resource_name]
309     if @attrs.is_a? String
310       @attrs = Oj.strict_load @attrs, symbol_keys: true
311     end
312     unless @attrs.is_a? Hash
313       message = "No #{resource_name}"
314       if resource_name.index('_')
315         message << " (or #{resource_name.camelcase(:lower)})"
316       end
317       message << " hash provided with request"
318       raise ArgumentError.new(message)
319     end
320     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
321       @attrs.delete x.to_sym
322     end
323     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
324     @attrs
325   end
326
327   # Authentication
328   def load_read_auths
329     @read_auths = []
330     if current_api_client_authorization
331       @read_auths << current_api_client_authorization
332     end
333     # Load reader tokens if this is a read request.
334     # If there are too many reader tokens, assume the request is malicious
335     # and ignore it.
336     if request.get? and params[:reader_tokens] and
337         params[:reader_tokens].size < 100
338       @read_auths += ApiClientAuthorization
339         .includes(:user)
340         .where('api_token IN (?) AND
341                 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
342                params[:reader_tokens])
343         .all
344     end
345     @read_auths.select! { |auth| auth.scopes_allow_request? request }
346     @read_users = @read_auths.map { |auth| auth.user }.uniq
347   end
348
349   def require_login
350     if not current_user
351       respond_to do |format|
352         format.json { send_error("Not logged in", status: 401) }
353         format.html { redirect_to '/auth/joshid' }
354       end
355       false
356     end
357   end
358
359   def admin_required
360     unless current_user and current_user.is_admin
361       send_error("Forbidden", status: 403)
362     end
363   end
364
365   def require_auth_scope
366     if @read_auths.empty?
367       if require_login != false
368         send_error("Forbidden", status: 403)
369       end
370       false
371     end
372   end
373
374   def disable_api_methods
375     if Rails.configuration.disable_api_methods.
376         include?(controller_name + "." + action_name)
377       send_error("Disabled", status: 404)
378     end
379   end
380
381   def set_cors_headers
382     response.headers['Access-Control-Allow-Origin'] = '*'
383     response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD, PUT, POST, DELETE'
384     response.headers['Access-Control-Allow-Headers'] = 'Authorization'
385     response.headers['Access-Control-Max-Age'] = '86486400'
386   end
387
388   def respond_with_json_by_default
389     html_index = request.accepts.index(Mime::HTML)
390     if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
391       request.format = :json
392     end
393   end
394
395   def model_class
396     controller_name.classify.constantize
397   end
398
399   def resource_name             # params[] key used by client
400     controller_name.singularize
401   end
402
403   def table_name
404     controller_name
405   end
406
407   def find_object_by_uuid
408     if params[:id] and params[:id].match(/\D/)
409       params[:uuid] = params.delete :id
410     end
411     @where = { uuid: params[:uuid] }
412     @offset = 0
413     @limit = 1
414     @orders = []
415     @filters = []
416     @objects = nil
417     find_objects_for_index
418     @object = @objects.first
419   end
420
421   def reload_object_before_update
422     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
423     # error when updating an object which was retrieved using a join.
424     if @object.andand.readonly?
425       @object = model_class.find_by_uuid(@objects.first.uuid)
426     end
427   end
428
429   def load_json_value(hash, key, must_be_class=nil)
430     if hash[key].is_a? String
431       hash[key] = SafeJSON.load(hash[key])
432       if must_be_class and !hash[key].is_a? must_be_class
433         raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
434       end
435     end
436   end
437
438   def self.accept_attribute_as_json(attr, must_be_class=nil)
439     before_filter lambda { accept_attribute_as_json attr, must_be_class }
440   end
441   accept_attribute_as_json :properties, Hash
442   accept_attribute_as_json :info, Hash
443   def accept_attribute_as_json(attr, must_be_class)
444     if params[resource_name] and resource_attrs.is_a? Hash
445       if resource_attrs[attr].is_a? Hash
446         # Convert symbol keys to strings (in hashes provided by
447         # resource_attrs)
448         resource_attrs[attr] = resource_attrs[attr].
449           with_indifferent_access.to_hash
450       else
451         load_json_value(resource_attrs, attr, must_be_class)
452       end
453     end
454   end
455
456   def self.accept_param_as_json(key, must_be_class=nil)
457     prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
458   end
459   accept_param_as_json :reader_tokens, Array
460
461   def object_list(model_class:)
462     if @objects.respond_to?(:except)
463       limit_database_read(model_class: model_class)
464     end
465     list = {
466       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
467       :etag => "",
468       :self_link => "",
469       :offset => @offset,
470       :limit => @limit,
471       :items => @objects.as_api_response(nil, {select: @select})
472     }
473     case params[:count]
474     when nil, '', 'exact'
475       if @objects.respond_to? :except
476         list[:items_available] = @objects.
477           except(:limit).except(:offset).
478           count(:id, distinct: true)
479       end
480     when 'none'
481     else
482       raise ArgumentError.new("count parameter must be 'exact' or 'none'")
483     end
484     list
485   end
486
487   def render_list
488     send_json object_list(model_class: self.model_class)
489   end
490
491   def remote_ip
492     # Caveat: this is highly dependent on the proxy setup. YMMV.
493     if request.headers.key?('HTTP_X_REAL_IP') then
494       # We're behind a reverse proxy
495       @remote_ip = request.headers['HTTP_X_REAL_IP']
496     else
497       # Hopefully, we are not!
498       @remote_ip = request.env['REMOTE_ADDR']
499     end
500   end
501
502   def load_required_parameters
503     (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
504       each do |key, info|
505       if info[:required] and not params.include?(key)
506         raise ArgumentError.new("#{key} parameter is required")
507       elsif info[:type] == 'boolean'
508         # Make sure params[key] is either true or false -- not a
509         # string, not nil, etc.
510         if not params.include?(key)
511           params[key] = info[:default]
512         elsif [false, 'false', '0', 0].include? params[key]
513           params[key] = false
514         elsif [true, 'true', '1', 1].include? params[key]
515           params[key] = true
516         else
517           raise TypeError.new("#{key} parameter must be a boolean, true or false")
518         end
519       end
520     end
521     true
522   end
523
524   def self._create_requires_parameters
525     {
526       ensure_unique_name: {
527         type: "boolean",
528         description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
529         location: "query",
530         required: false,
531         default: false
532       }
533     }
534   end
535
536   def self._index_requires_parameters
537     {
538       filters: { type: 'array', required: false },
539       where: { type: 'object', required: false },
540       order: { type: 'array', required: false },
541       select: { type: 'array', required: false },
542       distinct: { type: 'boolean', required: false },
543       limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
544       offset: { type: 'integer', required: false, default: 0 },
545       count: { type: 'string', required: false, default: 'exact' },
546     }
547   end
548
549   def client_accepts_plain_text_stream
550     (request.headers['Accept'].split(' ') &
551      ['text/plain', '*/*']).count > 0
552   end
553
554   def render *opts
555     if opts.first
556       response = opts.first[:json]
557       if response.is_a?(Hash) &&
558           params[:_profile] &&
559           Thread.current[:request_starttime]
560         response[:_profile] = {
561           request_time: Time.now - Thread.current[:request_starttime]
562         }
563       end
564     end
565     super(*opts)
566   end
567 end