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