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