1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: AGPL-3.0
7 module ApiTemplateOverride
8 def allowed_to_render?(fieldset, field, model, options)
11 options[:select].include? field.to_s
18 class ActsAsApi::ApiTemplate
19 prepend ApiTemplateOverride
24 class ApplicationController < ActionController::Base
25 include ThemesForRails::ActionController
26 include CurrentApiClient
33 ERROR_ACTIONS = [:render_error, :render_not_found]
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
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)
55 theme Rails.configuration.arvados_theme
57 attr_writer :resource_attrs
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)
78 @response_resource_name = nil
82 def default_url_options
83 if Rails.configuration.host
84 {:host => Rails.configuration.host}
91 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
92 @objects.each(&:eager_load_associations)
98 send_json @object.as_api_response(nil, select: @select)
102 @object = model_class.new resource_attrs
104 if @object.respond_to?(:name) && params[:ensure_unique_name]
105 @object.save_with_unique_name!
114 attrs_to_update = resource_attrs.reject { |k,v|
115 [:kind, :etag, :href].index k
117 @object.update_attributes! attrs_to_update
126 def catch_redirect_hint
128 if params.has_key?('redirect_to') then
129 session[:redirect_to] = params[:redirect_to]
134 def render_404_if_no_object
135 render_not_found "Object not found" if !@object
139 logger.error e.inspect
140 if e.respond_to? :backtrace and e.backtrace
141 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
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
150 status = e.respond_to?(:http_status) ? e.http_status : 422
151 send_error(*errors, status: status)
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)
161 def send_error(*args)
162 if args.last.is_a? Hash
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
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.
178 text: SafeJSON.dump(response).html_safe,
179 content_type: 'application/json'
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
188 def apply_filters model_class=nil
189 model_class ||= self.model_class
190 @objects = model_class.apply_filters(@objects, @filters)
193 def apply_where_limit_order_params model_class=nil
194 model_class ||= self.model_class
195 apply_filters model_class
197 ar_table_name = @objects.table_name
198 if @where.is_a? Hash and @where.any?
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
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]}%"
214 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
217 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
218 model_class.columns.collect(&:name).index(attr.to_s)
220 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
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]}%"
227 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
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}=?"
233 elsif value.is_a? Hash
234 # Not quite the same thing as "equal?" but better than nothing?
237 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
238 conditions << "%#{k}%#{v}%"
244 if conditions.length > 1
245 conditions[0].sub!(/^1=1 and /, '')
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(", "))
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.)
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?
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
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(" + "))
291 limit_query.each do |record|
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
298 elsif new_limit >= @limit
302 @objects = @objects.limit(@limit)
303 # Force @objects to run its query inside this transaction.
304 @objects.each { |_| break }
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
314 unless @attrs.is_a? Hash
315 message = "No #{resource_name}"
316 if resource_name.index('_')
317 message << " (or #{resource_name.camelcase(:lower)})"
319 message << " hash provided with request"
320 raise ArgumentError.new(message)
322 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
323 @attrs.delete x.to_sym
325 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
332 if current_api_client_authorization
333 @read_auths << current_api_client_authorization
335 # Load reader tokens if this is a read request.
336 # If there are too many reader tokens, assume the request is malicious
338 if request.get? and params[:reader_tokens] and
339 params[:reader_tokens].size < 100
340 @read_auths += ApiClientAuthorization
342 .where('api_token IN (?) AND
343 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
344 params[:reader_tokens])
347 @read_auths.select! { |auth| auth.scopes_allow_request? request }
348 @read_users = @read_auths.map(&:user).uniq
353 respond_to do |format|
354 format.json { send_error("Not logged in", status: 401) }
355 format.html { redirect_to '/auth/joshid' }
362 unless current_user and current_user.is_admin
363 send_error("Forbidden", status: 403)
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)
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]
383 response.headers['X-Request-Id'] = Thread.current[:request_id] = req_id
385 Thread.current[:request_id] = nil
388 def append_info_to_payload(payload)
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
395 def disable_api_methods
396 if Rails.configuration.disable_api_methods.
397 include?(controller_name + "." + action_name)
398 send_error("Disabled", status: 404)
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'
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
417 controller_name.classify.constantize
420 def resource_name # params[] key used by client
421 controller_name.singularize
428 def find_object_by_uuid
429 if params[:id] and params[:id].match(/\D/)
430 params[:uuid] = params.delete :id
432 @where = { uuid: params[:uuid] }
438 find_objects_for_index
439 @object = @objects.first
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)
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}")
459 def self.accept_attribute_as_json(attr, must_be_class=nil)
460 before_filter lambda { accept_attribute_as_json attr, must_be_class }
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
469 resource_attrs[attr] = resource_attrs[attr].
470 with_indifferent_access.to_hash
472 load_json_value(resource_attrs, attr, must_be_class)
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) }
480 accept_param_as_json :reader_tokens, Array
482 def object_list(model_class:)
483 if @objects.respond_to?(:except)
484 limit_database_read(model_class: model_class)
487 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
492 :items => @objects.as_api_response(nil, {select: @select})
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)
503 raise ArgumentError.new("count parameter must be 'exact' or 'none'")
509 send_json object_list(model_class: self.model_class)
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']
518 # Hopefully, we are not!
519 @remote_ip = request.env['REMOTE_ADDR']
523 def load_required_parameters
524 (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
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]
535 elsif [true, 'true', '1', 1].include? params[key]
538 raise TypeError.new("#{key} parameter must be a boolean, true or false")
545 def self._create_requires_parameters
547 ensure_unique_name: {
549 description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
557 def self._index_requires_parameters
559 filters: { type: 'array', required: false },
560 where: { type: 'object', required: false },
561 order: { type: 'array', required: false },
562 select: { type: 'array', required: false },
563 distinct: { type: 'boolean', required: false },
564 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
565 offset: { type: 'integer', required: false, default: 0 },
566 count: { type: 'string', required: false, default: 'exact' },
570 def client_accepts_plain_text_stream
571 (request.headers['Accept'].split(' ') &
572 ['text/plain', '*/*']).count > 0
577 response = opts.first[:json]
578 if response.is_a?(Hash) &&
580 Thread.current[:request_starttime]
581 response[:_profile] = {
582 request_time: Time.now - Thread.current[:request_starttime]