5383: use db current time in place of Time.now
[arvados.git] / services / api / app / controllers / application_controller.rb
1 module ApiTemplateOverride
2   def allowed_to_render?(fieldset, field, model, options)
3     return false if !super
4     if options[:select]
5       options[:select].include? field.to_s
6     else
7       true
8     end
9   end
10 end
11
12 class ActsAsApi::ApiTemplate
13   prepend ApiTemplateOverride
14 end
15
16 require 'load_param'
17 require 'record_filters'
18
19 class ApplicationController < ActionController::Base
20   include CurrentApiClient
21   include ThemesForRails::ActionController
22   include LoadParam
23   include RecordFilters
24   include DbCurrentTime
25
26   respond_to :json
27   protect_from_forgery
28
29   ERROR_ACTIONS = [:render_error, :render_not_found]
30
31   before_filter :set_cors_headers
32   before_filter :respond_with_json_by_default
33   before_filter :remote_ip
34   before_filter :load_read_auths
35   before_filter :require_auth_scope, except: ERROR_ACTIONS
36
37   before_filter :catch_redirect_hint
38   before_filter(:find_object_by_uuid,
39                 except: [:index, :create] + ERROR_ACTIONS)
40   before_filter :load_required_parameters
41   before_filter :load_limit_offset_order_params, only: [:index, :contents]
42   before_filter :load_where_param, only: [:index, :contents]
43   before_filter :load_filters_param, only: [:index, :contents]
44   before_filter :find_objects_for_index, :only => :index
45   before_filter :reload_object_before_update, :only => :update
46   before_filter(:render_404_if_no_object,
47                 except: [:index, :create] + ERROR_ACTIONS)
48
49   theme :select_theme
50
51   attr_accessor :resource_attrs
52
53   begin
54     rescue_from(Exception,
55                 ArvadosModel::PermissionDeniedError,
56                 :with => :render_error)
57     rescue_from(ActiveRecord::RecordNotFound,
58                 ActionController::RoutingError,
59                 ActionController::UnknownController,
60                 AbstractController::ActionNotFound,
61                 :with => :render_not_found)
62   end
63
64   def default_url_options
65     if Rails.configuration.host
66       {:host => Rails.configuration.host}
67     else
68       {}
69     end
70   end
71
72   def index
73     @objects.uniq!(&:id) if @select.nil? or @select.include? "id"
74     if params[:eager] and params[:eager] != '0' and params[:eager] != 0 and params[:eager] != ''
75       @objects.each(&:eager_load_associations)
76     end
77     render_list
78   end
79
80   def show
81     send_json @object.as_api_response(nil, select: @select)
82   end
83
84   def create
85     @object = model_class.new resource_attrs
86
87     if @object.respond_to? :name and params[:ensure_unique_name]
88       # Record the original name.  See below.
89       name_stem = @object.name
90       counter = 1
91     end
92
93     begin
94       @object.save!
95     rescue ActiveRecord::RecordNotUnique => rn
96       raise unless params[:ensure_unique_name]
97
98       # Dig into the error to determine if it is specifically calling out a
99       # (owner_uuid, name) uniqueness violation.  In this specific case, and
100       # the client requested a unique name with ensure_unique_name==true,
101       # update the name field and try to save again.  Loop as necessary to
102       # discover a unique name.  It is necessary to handle name choosing at
103       # this level (as opposed to the client) to ensure that record creation
104       # never fails due to a race condition.
105       raise unless rn.original_exception.is_a? PG::UniqueViolation
106
107       # Unfortunately ActiveRecord doesn't abstract out any of the
108       # necessary information to figure out if this the error is actually
109       # the specific case where we want to apply the ensure_unique_name
110       # behavior, so the following code is specialized to Postgres.
111       err = rn.original_exception
112       detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
113       raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
114
115       # OK, this exception really is just a unique name constraint
116       # violation, and we've been asked to ensure_unique_name.
117       counter += 1
118       @object.uuid = nil
119       @object.name = "#{name_stem} (#{counter})"
120       redo
121     end while false
122     show
123   end
124
125   def update
126     attrs_to_update = resource_attrs.reject { |k,v|
127       [:kind, :etag, :href].index k
128     }
129     @object.update_attributes! attrs_to_update
130     show
131   end
132
133   def destroy
134     @object.destroy
135     show
136   end
137
138   def catch_redirect_hint
139     if !current_user
140       if params.has_key?('redirect_to') then
141         session[:redirect_to] = params[:redirect_to]
142       end
143     end
144   end
145
146   def render_404_if_no_object
147     render_not_found "Object not found" if !@object
148   end
149
150   def render_error(e)
151     logger.error e.inspect
152     if e.respond_to? :backtrace and e.backtrace
153       logger.error e.backtrace.collect { |x| x + "\n" }.join('')
154     end
155     if (@object.respond_to? :errors and
156         @object.errors.andand.full_messages.andand.any?)
157       errors = @object.errors.full_messages
158       logger.error errors.inspect
159     else
160       errors = [e.inspect]
161     end
162     status = e.respond_to?(:http_status) ? e.http_status : 422
163     send_error(*errors, status: status)
164   end
165
166   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
167     logger.error e.inspect
168     send_error("Path not found", status: 404)
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] = [db_current_time.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: Oj.dump(response, mode: :compat).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     apply_where_limit_order_params
198   end
199
200   def apply_filters model_class=nil
201     model_class ||= self.model_class
202     ft = record_filters @filters, model_class
203     if ft[:cond_out].any?
204       @objects = @objects.where('(' + ft[:cond_out].join(') AND (') + ')',
205                                 *ft[:param_out])
206     end
207   end
208
209   def apply_where_limit_order_params model_class=nil
210     model_class ||= self.model_class
211     apply_filters model_class
212
213     ar_table_name = @objects.table_name
214     if @where.is_a? Hash and @where.any?
215       conditions = ['1=1']
216       @where.each do |attr,value|
217         if attr.to_s == 'any'
218           if value.is_a?(Array) and
219               value.length == 2 and
220               value[0] == 'contains' then
221             ilikes = []
222             model_class.searchable_columns('ilike').each do |column|
223               # Including owner_uuid in an "any column" search will
224               # probably just return a lot of false positives.
225               next if column == 'owner_uuid'
226               ilikes << "#{ar_table_name}.#{column} ilike ?"
227               conditions << "%#{value[1]}%"
228             end
229             if ilikes.any?
230               conditions[0] << ' and (' + ilikes.join(' or ') + ')'
231             end
232           end
233         elsif attr.to_s.match(/^[a-z][_a-z0-9]+$/) and
234             model_class.columns.collect(&:name).index(attr.to_s)
235           if value.nil?
236             conditions[0] << " and #{ar_table_name}.#{attr} is ?"
237             conditions << nil
238           elsif value.is_a? Array
239             if value[0] == 'contains' and value.length == 2
240               conditions[0] << " and #{ar_table_name}.#{attr} like ?"
241               conditions << "%#{value[1]}%"
242             else
243               conditions[0] << " and #{ar_table_name}.#{attr} in (?)"
244               conditions << value
245             end
246           elsif value.is_a? String or value.is_a? Fixnum or value == true or value == false
247             conditions[0] << " and #{ar_table_name}.#{attr}=?"
248             conditions << value
249           elsif value.is_a? Hash
250             # Not quite the same thing as "equal?" but better than nothing?
251             value.each do |k,v|
252               if v.is_a? String
253                 conditions[0] << " and #{ar_table_name}.#{attr} ilike ?"
254                 conditions << "%#{k}%#{v}%"
255               end
256             end
257           end
258         end
259       end
260       if conditions.length > 1
261         conditions[0].sub!(/^1=1 and /, '')
262         @objects = @objects.
263           where(*conditions)
264       end
265     end
266
267     if @select
268       unless action_name.in? %w(create update destroy)
269         # Map attribute names in @select to real column names, resolve
270         # those to fully-qualified SQL column names, and pass the
271         # resulting string to the select method.
272         api_column_map = model_class.attributes_required_columns
273         columns_list = @select.
274           flat_map { |attr| api_column_map[attr] }.
275           uniq.
276           map { |s| "#{ar_table_name}.#{ActiveRecord::Base.connection.quote_column_name s}" }
277         @objects = @objects.select(columns_list.join(", "))
278       end
279
280       # This information helps clients understand what they're seeing
281       # (Workbench always expects it), but they can't select it explicitly
282       # because it's not an SQL column.  Always add it.
283       # (This is harmless, given that clients can deduce what they're
284       # looking at by the returned UUID anyway.)
285       @select |= ["kind"]
286     end
287     @objects = @objects.order(@orders.join ", ") if @orders.any?
288     @objects = @objects.limit(@limit)
289     @objects = @objects.offset(@offset)
290     @objects = @objects.uniq(@distinct) if not @distinct.nil?
291   end
292
293   def resource_attrs
294     return @attrs if @attrs
295     @attrs = params[resource_name]
296     if @attrs.is_a? String
297       @attrs = Oj.load @attrs, symbol_keys: true
298     end
299     unless @attrs.is_a? Hash
300       message = "No #{resource_name}"
301       if resource_name.index('_')
302         message << " (or #{resource_name.camelcase(:lower)})"
303       end
304       message << " hash provided with request"
305       raise ArgumentError.new(message)
306     end
307     %w(created_at modified_by_client_uuid modified_by_user_uuid modified_at).each do |x|
308       @attrs.delete x.to_sym
309     end
310     @attrs = @attrs.symbolize_keys if @attrs.is_a? HashWithIndifferentAccess
311     @attrs
312   end
313
314   # Authentication
315   def load_read_auths
316     @read_auths = []
317     if current_api_client_authorization
318       @read_auths << current_api_client_authorization
319     end
320     # Load reader tokens if this is a read request.
321     # If there are too many reader tokens, assume the request is malicious
322     # and ignore it.
323     if request.get? and params[:reader_tokens] and
324         params[:reader_tokens].size < 100
325       @read_auths += ApiClientAuthorization
326         .includes(:user)
327         .where('api_token IN (?) AND
328                 (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)',
329                params[:reader_tokens])
330         .all
331     end
332     @read_auths.select! { |auth| auth.scopes_allow_request? request }
333     @read_users = @read_auths.map { |auth| auth.user }.uniq
334   end
335
336   def require_login
337     if not current_user
338       respond_to do |format|
339         format.json { send_error("Not logged in", status: 401) }
340         format.html { redirect_to '/auth/joshid' }
341       end
342       false
343     end
344   end
345
346   def admin_required
347     unless current_user and current_user.is_admin
348       send_error("Forbidden", status: 403)
349     end
350   end
351
352   def require_auth_scope
353     if @read_auths.empty?
354       if require_login != false
355         send_error("Forbidden", status: 403)
356       end
357       false
358     end
359   end
360
361   def set_cors_headers
362     response.headers['Access-Control-Allow-Origin'] = '*'
363     response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD, PUT, POST, DELETE'
364     response.headers['Access-Control-Allow-Headers'] = 'Authorization'
365     response.headers['Access-Control-Max-Age'] = '86486400'
366   end
367
368   def respond_with_json_by_default
369     html_index = request.accepts.index(Mime::HTML)
370     if html_index.nil? or request.accepts[0...html_index].include?(Mime::JSON)
371       request.format = :json
372     end
373   end
374
375   def model_class
376     controller_name.classify.constantize
377   end
378
379   def resource_name             # params[] key used by client
380     controller_name.singularize
381   end
382
383   def table_name
384     controller_name
385   end
386
387   def find_object_by_uuid
388     if params[:id] and params[:id].match /\D/
389       params[:uuid] = params.delete :id
390     end
391     @where = { uuid: params[:uuid] }
392     @offset = 0
393     @limit = 1
394     @orders = []
395     @filters = []
396     @objects = nil
397     find_objects_for_index
398     @object = @objects.first
399   end
400
401   def reload_object_before_update
402     # This is necessary to prevent an ActiveRecord::ReadOnlyRecord
403     # error when updating an object which was retrieved using a join.
404     if @object.andand.readonly?
405       @object = model_class.find_by_uuid(@objects.first.uuid)
406     end
407   end
408
409   def load_json_value(hash, key, must_be_class=nil)
410     if hash[key].is_a? String
411       hash[key] = Oj.load(hash[key], symbol_keys: false)
412       if must_be_class and !hash[key].is_a? must_be_class
413         raise TypeError.new("parameter #{key.to_s} must be a #{must_be_class.to_s}")
414       end
415     end
416   end
417
418   def self.accept_attribute_as_json(attr, must_be_class=nil)
419     before_filter lambda { accept_attribute_as_json attr, must_be_class }
420   end
421   accept_attribute_as_json :properties, Hash
422   accept_attribute_as_json :info, Hash
423   def accept_attribute_as_json(attr, must_be_class)
424     if params[resource_name] and resource_attrs.is_a? Hash
425       if resource_attrs[attr].is_a? Hash
426         # Convert symbol keys to strings (in hashes provided by
427         # resource_attrs)
428         resource_attrs[attr] = resource_attrs[attr].
429           with_indifferent_access.to_hash
430       else
431         load_json_value(resource_attrs, attr, must_be_class)
432       end
433     end
434   end
435
436   def self.accept_param_as_json(key, must_be_class=nil)
437     prepend_before_filter lambda { load_json_value(params, key, must_be_class) }
438   end
439   accept_param_as_json :reader_tokens, Array
440
441   def object_list
442     list = {
443       :kind  => "arvados##{(@response_resource_name || resource_name).camelize(:lower)}List",
444       :etag => "",
445       :self_link => "",
446       :offset => @offset,
447       :limit => @limit,
448       :items => @objects.as_api_response(nil, {select: @select})
449     }
450     if @objects.respond_to? :except
451       list[:items_available] = @objects.
452         except(:limit).except(:offset).
453         count(:id, distinct: true)
454     end
455     list
456   end
457
458   def render_list
459     send_json object_list
460   end
461
462   def remote_ip
463     # Caveat: this is highly dependent on the proxy setup. YMMV.
464     if request.headers.has_key?('HTTP_X_REAL_IP') then
465       # We're behind a reverse proxy
466       @remote_ip = request.headers['HTTP_X_REAL_IP']
467     else
468       # Hopefully, we are not!
469       @remote_ip = request.env['REMOTE_ADDR']
470     end
471   end
472
473   def load_required_parameters
474     (self.class.send "_#{params[:action]}_requires_parameters" rescue {}).
475       each do |key, info|
476       if info[:required] and not params.include?(key)
477         raise ArgumentError.new("#{key} parameter is required")
478       elsif info[:type] == 'boolean'
479         # Make sure params[key] is either true or false -- not a
480         # string, not nil, etc.
481         if not params.include?(key)
482           params[key] = info[:default]
483         elsif [false, 'false', '0', 0].include? params[key]
484           params[key] = false
485         elsif [true, 'true', '1', 1].include? params[key]
486           params[key] = true
487         else
488           raise TypeError.new("#{key} parameter must be a boolean, true or false")
489         end
490       end
491     end
492     true
493   end
494
495   def self._create_requires_parameters
496     {
497       ensure_unique_name: {
498         type: "boolean",
499         description: "Adjust name to ensure uniqueness instead of returning an error on (owner_uuid, name) collision.",
500         location: "query",
501         required: false,
502         default: false
503       }
504     }
505   end
506
507   def self._index_requires_parameters
508     {
509       filters: { type: 'array', required: false },
510       where: { type: 'object', required: false },
511       order: { type: 'array', required: false },
512       select: { type: 'array', required: false },
513       distinct: { type: 'boolean', required: false },
514       limit: { type: 'integer', required: false, default: DEFAULT_LIMIT },
515       offset: { type: 'integer', required: false, default: 0 },
516     }
517   end
518
519   def client_accepts_plain_text_stream
520     (request.headers['Accept'].split(' ') &
521      ['text/plain', '*/*']).count > 0
522   end
523
524   def render *opts
525     if opts.first
526       response = opts.first[:json]
527       if response.is_a?(Hash) &&
528           params[:_profile] &&
529           Thread.current[:request_starttime]
530         response[:_profile] = {
531           request_time: db_current_time - Thread.current[:request_starttime]
532         }
533       end
534     end
535     super *opts
536   end
537
538   def select_theme
539     return Rails.configuration.arvados_theme
540   end
541 end