1 module ApiTemplateOverride
2 def allowed_to_render?(fieldset, field, model, options)
5 options[:select].include? field.to_s
12 class ActsAsApi::ApiTemplate
13 prepend ApiTemplateOverride
18 class ApplicationController < ActionController::Base
19 include CurrentApiClient
20 include ThemesForRails::ActionController
27 ERROR_ACTIONS = [:render_error, :render_not_found]
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
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)
50 attr_writer :resource_attrs
52 MAX_UNIQUE_NAME_ATTEMPTS = 10
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)
73 @response_resource_name = nil
77 def default_url_options
78 if Rails.configuration.host
79 {:host => Rails.configuration.host}
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)
94 send_json @object.as_api_response(nil, select: @select)
98 @object = model_class.new resource_attrs
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
110 rescue ActiveRecord::RecordNotUnique => rn
111 raise unless retries > 0
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
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
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.
139 new_name = "#{name_stem} (#{db_current_time.utc.iso8601(3)})"
141 @object.name = new_name
148 attrs_to_update = resource_attrs.reject { |k,v|
149 [:kind, :etag, :href].index k
151 @object.update_attributes! attrs_to_update
160 def catch_redirect_hint
162 if params.has_key?('redirect_to') then
163 session[:redirect_to] = params[:redirect_to]
168 def render_404_if_no_object
169 render_not_found "Object not found" if !@object
173 logger.error e.inspect
174 if e.respond_to? :backtrace and e.backtrace
175 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
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
184 status = e.respond_to?(:http_status) ? e.http_status : 422
185 send_error(*errors, status: status)
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)
195 def send_error(*args)
196 if args.last.is_a? Hash
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
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.
212 text: Oj.dump(response, mode: :compat).html_safe,
213 content_type: 'application/json'
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.
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")
231 def apply_filters model_class=nil
232 model_class ||= self.model_class
233 @objects = model_class.apply_filters(@objects, @filters)
236 def apply_where_limit_order_params model_class=nil
237 model_class ||= self.model_class
238 apply_filters model_class
240 ar_table_name = @objects.table_name
241 if @where.is_a? Hash and @where.any?
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
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]}%"
257 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
260 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
261 model_class.columns.collect(&:name).index(attr.to_s)
263 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
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]}%"
270 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
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}=?"
276 elsif value.is_a? Hash
277 # Not quite the same thing as "equal?" but better than nothing?
280 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
281 conditions << "%#{k}%#{v}%"
287 if conditions.length > 1
288 conditions[0].sub!(/^1=1 and /, '')
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(", "))
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.)
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?
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.
324 select("(%s) as read_length" %
325 limit_columns.map { |s| "octet_length(#{s})" }.join(" + "))
328 limit_query.each do |record|
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
334 elsif new_limit >= @limit
339 @objects = @objects.limit(@limit)
340 # Force @objects to run its query inside this transaction.
341 @objects.each { |_| break }
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
351 unless @attrs.is_a? Hash
352 message = "No #{resource_name}"
353 if resource_name.index('_')
354 message << " (or #{resource_name.camelcase(:lower)})"
356 message << " hash provided with request"
357 raise ArgumentError.new(message)
359 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
360 @attrs.delete x.to_sym
362 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
369 if current_api_client_authorization
370 @read_auths << current_api_client_authorization
372 # Load reader tokens if this is a read request.
373 # If there are too many reader tokens, assume the request is malicious
375 if request.get? and params[:reader_tokens] and
376 params[:reader_tokens].size < 100
377 @read_auths += ApiClientAuthorization
379 .where('api_token IN (?) AND
380 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
381 params[:reader_tokens])
384 @read_auths.select! { |auth| auth.scopes_allow_request? request }
385 @read_users = @read_auths.map { |auth| auth.user }.uniq
390 respond_to do |format|
391 format.json { send_error("Not logged in", status: 401) }
392 format.html { redirect_to '/auth/joshid' }
399 unless current_user and current_user.is_admin
400 send_error("Forbidden", status: 403)
404 def require_auth_scope
405 if @read_auths.empty?
406 if require_login != false
407 send_error("Forbidden", status: 403)
413 def disable_api_methods
414 if Rails.configuration.disable_api_methods.
415 include?(controller_name + "." + action_name)
416 send_error("Disabled", status: 404)
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'
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
435 controller_name.classify.constantize
438 def resource_name # params[] key used by client
439 controller_name.singularize
446 def find_object_by_uuid
447 if params[:id] and params[:id].match(/\D/)
448 params[:uuid] = params.delete :id
450 @where = { uuid: params[:uuid] }
456 find_objects_for_index
457 @object = @objects.first
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)
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}")
477 def self.accept_attribute_as_json(attr, must_be_class=nil)
478 before_filter lambda { accept_attribute_as_json attr, must_be_class }
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
487 resource_attrs[attr] = resource_attrs[attr].
488 with_indifferent_access.to_hash
490 load_json_value(resource_attrs, attr, must_be_class)
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) }
498 accept_param_as_json :reader_tokens, Array
502 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
507 :items => @objects.as_api_response(nil, {select: @select})
510 when nil, '', 'exact'
511 if @objects.respond_to? :except
512 list[:items_available] = @objects.
513 except(:limit).except(:offset).
514 count(:id, distinct: true)
518 raise ArgumentError.new("count parameter must be 'exact' or 'none'")
524 send_json object_list
528 # Caveat: this is highly dependent on the proxy setup. YMMV.
529 if request.headers.has_key?('HTTP_X_REAL_IP') then
530 # We're behind a reverse proxy
531 @remote_ip = request.headers['HTTP_X_REAL_IP']
533 # Hopefully, we are not!
534 @remote_ip = request.env['REMOTE_ADDR']
538 def load_required_parameters
539 (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
541 if info[:required] and not params.include?(key)
542 raise ArgumentError.new("#{key} parameter is required")
543 elsif info[:type] == 'boolean'
544 # Make sure params[key] is either true or false -- not a
545 # string, not nil, etc.
546 if not params.include?(key)
547 params[key] = info[:default]
548 elsif [false, 'false', '0', 0].include? params[key]
550 elsif [true, 'true', '1', 1].include? params[key]
553 raise TypeError.new("#{key} parameter must be a boolean, true or false")
560 def self._create_requires_parameters
562 ensure_unique_name: {
564 description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
572 def self._index_requires_parameters
574 filters: { type: 'array', required: false },
575 where: { type: 'object', required: false },
576 order: { type: 'array', required: false },
577 select: { type: 'array', required: false },
578 distinct: { type: 'boolean', required: false },
579 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
580 offset: { type: 'integer', required: false, default: 0 },
581 count: { type: 'string', required: false, default: 'exact' },
585 def client_accepts_plain_text_stream
586 (request.headers['Accept'].split(' ') &
587 ['text/plain', '*/*']).count > 0
592 response = opts.first[:json]
593 if response.is_a?(Hash) &&
595 Thread.current[:request_starttime]
596 response[:_profile] = {
597 request_time: Time.now - Thread.current[:request_starttime]
605 return Rails.configuration.arvados_theme