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