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