3 module ApiTemplateOverride
4 def allowed_to_render?(fieldset, field, model, options)
7 options[:select].include? field.to_s
14 class ActsAsApi::ApiTemplate
15 prepend ApiTemplateOverride
20 class ApplicationController < ActionController::Base
21 include CurrentApiClient
22 include ThemesForRails::ActionController
29 ERROR_ACTIONS = [:render_error, :render_not_found]
31 before_filter :disable_api_methods
32 before_filter :set_cors_headers
33 before_filter :respond_with_json_by_default
34 before_filter :remote_ip
35 before_filter :load_read_auths
36 before_filter :require_auth_scope, except: ERROR_ACTIONS
38 before_filter :catch_redirect_hint
39 before_filter(:find_object_by_uuid,
40 except: [:index, :create] + ERROR_ACTIONS)
41 before_filter :load_required_parameters
42 before_filter :load_limit_offset_order_params, only: [:index, :contents]
43 before_filter :load_where_param, only: [:index, :contents]
44 before_filter :load_filters_param, only: [:index, :contents]
45 before_filter :find_objects_for_index, :only => :index
46 before_filter :reload_object_before_update, :only => :update
47 before_filter(:render_404_if_no_object,
48 except: [:index, :create] + ERROR_ACTIONS)
52 attr_writer :resource_attrs
54 MAX_UNIQUE_NAME_ATTEMPTS = 10
57 rescue_from(Exception,
58 ArvadosModel::PermissionDeniedError,
59 :with => :render_error)
60 rescue_from(ActiveRecord::RecordNotFound,
61 ActionController::RoutingError,
62 ActionController::UnknownController,
63 AbstractController::ActionNotFound,
64 :with => :render_not_found)
75 @response_resource_name = nil
79 def default_url_options
80 if Rails.configuration.host
81 {:host => Rails.configuration.host}
88 @objects.uniq!(&:id) if @select.nil? or @select.include? "id"
89 if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
90 @objects.each(&:eager_load_associations)
96 send_json @object.as_api_response(nil, select: @select)
100 @object = model_class.new resource_attrs
102 if @object.respond_to? :name and params[:ensure_unique_name]
103 # Record the original name. See below.
104 name_stem = @object.name
105 retries = MAX_UNIQUE_NAME_ATTEMPTS
112 rescue ActiveRecord::RecordNotUnique => rn
113 raise unless retries > 0
116 # Dig into the error to determine if it is specifically calling out a
117 # (owner_uuid, name) uniqueness violation. In this specific case, and
118 # the client requested a unique name with ensure_unique_name==true,
119 # update the name field and try to save again. Loop as necessary to
120 # discover a unique name. It is necessary to handle name choosing at
121 # this level (as opposed to the client) to ensure that record creation
122 # never fails due to a race condition.
123 raise unless rn.original_exception.is_a? PG::UniqueViolation
125 # Unfortunately ActiveRecord doesn't abstract out any of the
126 # necessary information to figure out if this the error is actually
127 # the specific case where we want to apply the ensure_unique_name
128 # behavior, so the following code is specialized to Postgres.
129 err = rn.original_exception
130 detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
131 raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
135 new_name = "#{name_stem} (#{db_current_time.utc.iso8601(3)})"
136 if new_name == @object.name
137 # If the database is fast enough to do two attempts in the
138 # same millisecond, we need to wait to ensure we try a
139 # different timestamp on each attempt.
141 new_name = "#{name_stem} (#{db_current_time.utc.iso8601(3)})"
143 @object.name = new_name
150 attrs_to_update = resource_attrs.reject { |k,v|
151 [:kind, :etag, :href].index k
153 @object.update_attributes! attrs_to_update
162 def catch_redirect_hint
164 if params.has_key?('redirect_to') then
165 session[:redirect_to] = params[:redirect_to]
170 def render_404_if_no_object
171 render_not_found "Object not found" if !@object
175 logger.error e.inspect
176 if e.respond_to? :backtrace and e.backtrace
177 logger.error e.backtrace.collect { |x| x + "\n" }.join('')
179 if (@object.respond_to? :errors and
180 @object.errors.andand.full_messages.andand.any?)
181 errors = @object.errors.full_messages
182 logger.error errors.inspect
186 status = e.respond_to?(:http_status) ? e.http_status : 422
187 send_error(*errors, status: status)
190 def render_not_found(e=ActionController::RoutingError.new("Path not found"))
191 logger.error e.inspect
192 send_error("Path not found", status: 404)
197 def send_error(*args)
198 if args.last.is_a? Hash
203 err[:errors] ||= args
204 err[:error_token] = [Time.now.utc.to_i, "%08x" % rand(16 ** 8)].join("+")
205 status = err.delete(:status) || 422
206 logger.error "Error #{err[:error_token]}: #{status}"
207 send_json err, status: status
210 def send_json response, opts={}
211 # The obvious render(json: ...) forces a slow JSON encoder. See
212 # #3021 and commit logs. Might be fixed in Rails 4.1.
214 text: SafeJSON.dump(response).html_safe,
215 content_type: 'application/json'
219 def self.limit_index_columns_read
220 # This method returns a list of column names.
221 # If an index request reads that column from the database,
222 # find_objects_for_index will only fetch objects until it reads
223 # max_index_database_read bytes of data from those columns.
227 def find_objects_for_index
228 @objects ||= model_class.readable_by(*@read_users)
229 apply_where_limit_order_params
230 limit_database_read if (action_name == "index")
233 def apply_filters model_class=nil
234 model_class ||= self.model_class
235 @objects = model_class.apply_filters(@objects, @filters)
238 def apply_where_limit_order_params model_class=nil
239 model_class ||= self.model_class
240 apply_filters model_class
242 ar_table_name = @objects.table_name
243 if @where.is_a? Hash and @where.any?
245 @where.each do |attr,value|
246 if attr.to_s == 'any'
247 if value.is_a?(Array) and
248 value.length == 2 and
249 value[0] == 'contains' then
251 model_class.searchable_columns('ilike').each do |column|
252 # Including owner_uuid in an "any column" search will
253 # probably just return a lot of false positives.
254 next if column == 'owner_uuid'
255 ilikes << "#{ar_table_name}.#{column} ilike ?"
256 conditions << "%#{value[1]}%"
259 conditions[0] << ' and (' + ilikes.join(' or ') + ')'
262 elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
263 model_class.columns.collect(&:name).index(attr.to_s)
265 conditions[0] << " and #{ar_table_name}.#{attr} is ?"
267 elsif value.is_a? Array
268 if value[0] == 'contains' and value.length == 2
269 conditions[0] << " and #{ar_table_name}.#{attr} like ?"
270 conditions << "%#{value[1]}%"
272 conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
275 elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
276 conditions[0] << " and #{ar_table_name}.#{attr}=?"
278 elsif value.is_a? Hash
279 # Not quite the same thing as "equal?" but better than nothing?
282 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
283 conditions << "%#{k}%#{v}%"
289 if conditions.length > 1
290 conditions[0].sub!(/^1=1 and /, '')
297 unless action_name.in? %w(create update destroy)
298 # Map attribute names in @select to real column names, resolve
299 # those to fully-qualified SQL column names, and pass the
300 # resulting string to the select method.
301 columns_list = model_class.columns_for_attributes(@select).
302 map { |s| "#{ar_table_name}.#{ActiveRecord::Base.connection.quote_column_name s}" }
303 @objects = @objects.select(columns_list.join(", "))
306 # This information helps clients understand what they're seeing
307 # (Workbench always expects it), but they can't select it explicitly
308 # because it's not an SQL column. Always add it.
309 # (This is harmless, given that clients can deduce what they're
310 # looking at by the returned UUID anyway.)
313 @objects = @objects.order(@orders.join ", ") if @orders.any?
314 @objects = @objects.limit(@limit)
315 @objects = @objects.offset(@offset)
316 @objects = @objects.uniq(@distinct) if not @distinct.nil?
319 def limit_database_read
320 limit_columns = self.class.limit_index_columns_read
321 limit_columns &= model_class.columns_for_attributes(@select) if @select
322 return if limit_columns.empty?
323 model_class.transaction do
324 limit_query = @objects.
326 select("(%s) as read_length" %
327 limit_columns.map { |s| "octet_length(#{s})" }.join(" + "))
330 limit_query.each do |record|
332 read_total += record.read_length.to_i
333 if read_total >= Rails.configuration.max_index_database_read
334 new_limit -= 1 if new_limit > 1
336 elsif new_limit >= @limit
341 @objects = @objects.limit(@limit)
342 # Force @objects to run its query inside this transaction.
343 @objects.each { |_| break }
348 return @attrs if @attrs
349 @attrs = params[resource_name]
350 if @attrs.is_a? String
351 @attrs = Oj.strict_load @attrs, symbol_keys: true
353 unless @attrs.is_a? Hash
354 message = "No #{resource_name}"
355 if resource_name.index('_')
356 message << " (or #{resource_name.camelcase(:lower)})"
358 message << " hash provided with request"
359 raise ArgumentError.new(message)
361 %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
362 @attrs.delete x.to_sym
364 @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
371 if current_api_client_authorization
372 @read_auths << current_api_client_authorization
374 # Load reader tokens if this is a read request.
375 # If there are too many reader tokens, assume the request is malicious
377 if request.get? and params[:reader_tokens] and
378 params[:reader_tokens].size < 100
379 @read_auths += ApiClientAuthorization
381 .where('api_token IN (?) AND
382 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
383 params[:reader_tokens])
386 @read_auths.select! { |auth| auth.scopes_allow_request? request }
387 @read_users = @read_auths.map { |auth| auth.user }.uniq
392 respond_to do |format|
393 format.json { send_error("Not logged in", status: 401) }
394 format.html { redirect_to '/auth/joshid' }
401 unless current_user and current_user.is_admin
402 send_error("Forbidden", status: 403)
406 def require_auth_scope
407 if @read_auths.empty?
408 if require_login != false
409 send_error("Forbidden", status: 403)
415 def disable_api_methods
416 if Rails.configuration.disable_api_methods.
417 include?(controller_name + "." + action_name)
418 send_error("Disabled", status: 404)
423 response.headers['Access-Control-Allow-Origin'] = '*'
424 response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD, PUT, POST, DELETE'
425 response.headers['Access-Control-Allow-Headers'] = 'Authorization'
426 response.headers['Access-Control-Max-Age'] = '86486400'
429 def respond_with_json_by_default
430 html_index = request.accepts.index(Mime::HTML)
431 if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
432 request.format = :json
437 controller_name.classify.constantize
440 def resource_name # params[] key used by client
441 controller_name.singularize
448 def find_object_by_uuid
449 if params[:id] and params[:id].match(/\D/)
450 params[:uuid] = params.delete :id
452 @where = { uuid: params[:uuid] }
458 find_objects_for_index
459 @object = @objects.first
462 def reload_object_before_update
463 # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
464 # error when updating an object which was retrieved using a join.
465 if @object.andand.readonly?
466 @object = model_class.find_by_uuid(@objects.first.uuid)
470 def load_json_value(hash, key, must_be_class=nil)
471 if hash[key].is_a? String
472 hash[key] = SafeJSON.load(hash[key])
473 if must_be_class and !hash[key].is_a? must_be_class
474 raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
479 def self.accept_attribute_as_json(attr, must_be_class=nil)
480 before_filter lambda { accept_attribute_as_json attr, must_be_class }
482 accept_attribute_as_json :properties, Hash
483 accept_attribute_as_json :info, Hash
484 def accept_attribute_as_json(attr, must_be_class)
485 if params[resource_name] and resource_attrs.is_a? Hash
486 if resource_attrs[attr].is_a? Hash
487 # Convert symbol keys to strings (in hashes provided by
489 resource_attrs[attr] = resource_attrs[attr].
490 with_indifferent_access.to_hash
492 load_json_value(resource_attrs, attr, must_be_class)
497 def self.accept_param_as_json(key, must_be_class=nil)
498 prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
500 accept_param_as_json :reader_tokens, Array
504 :kind => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
509 :items => @objects.as_api_response(nil, {select: @select})
512 when nil, '', 'exact'
513 if @objects.respond_to? :except
514 list[:items_available] = @objects.
515 except(:limit).except(:offset).
516 count(:id, distinct: true)
520 raise ArgumentError.new("count parameter must be 'exact' or 'none'")
526 send_json object_list
530 # Caveat: this is highly dependent on the proxy setup. YMMV.
531 if request.headers.has_key?('HTTP_X_REAL_IP') then
532 # We're behind a reverse proxy
533 @remote_ip = request.headers['HTTP_X_REAL_IP']
535 # Hopefully, we are not!
536 @remote_ip = request.env['REMOTE_ADDR']
540 def load_required_parameters
541 (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
543 if info[:required] and not params.include?(key)
544 raise ArgumentError.new("#{key} parameter is required")
545 elsif info[:type] == 'boolean'
546 # Make sure params[key] is either true or false -- not a
547 # string, not nil, etc.
548 if not params.include?(key)
549 params[key] = info[:default]
550 elsif [false, 'false', '0', 0].include? params[key]
552 elsif [true, 'true', '1', 1].include? params[key]
555 raise TypeError.new("#{key} parameter must be a boolean, true or false")
562 def self._create_requires_parameters
564 ensure_unique_name: {
566 description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
574 def self._index_requires_parameters
576 filters: { type: 'array', required: false },
577 where: { type: 'object', required: false },
578 order: { type: 'array', required: false },
579 select: { type: 'array', required: false },
580 distinct: { type: 'boolean', required: false },
581 limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
582 offset: { type: 'integer', required: false, default: 0 },
583 count: { type: 'string', required: false, default: 'exact' },
587 def client_accepts_plain_text_stream
588 (request.headers['Accept'].split(' ') &
589 ['text/plain', '*/*']).count > 0
594 response = opts.first[:json]
595 if response.is_a?(Hash) &&
597 Thread.current[:request_starttime]
598 response[:_profile] = {
599 request_time: Time.now - Thread.current[:request_starttime]
607 return Rails.configuration.arvados_theme