]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Ensure authorization checks happen for all controller methods
[rails.git] / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include SessionPersistence
3
4   protect_from_forgery :with => :exception
5
6   rescue_from CanCan::AccessDenied, :with => :deny_access
7   check_authorization
8
9   before_action :fetch_body
10   around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
11
12   attr_accessor :current_user
13   helper_method :current_user
14
15   def authorize_web
16     if session[:user]
17       self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
18
19       if current_user.status == "suspended"
20         session.delete(:user)
21         session_expires_automatically
22
23         redirect_to :controller => "users", :action => "suspended"
24
25       # don't allow access to any auth-requiring part of the site unless
26       # the new CTs have been seen (and accept/decline chosen).
27       elsif !current_user.terms_seen && flash[:skip_terms].nil?
28         flash[:notice] = t "users.terms.you need to accept or decline"
29         if params[:referer]
30           redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
31         else
32           redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
33         end
34       end
35     elsif session[:token]
36       session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
37     end
38   rescue StandardError => ex
39     logger.info("Exception authorizing user: #{ex}")
40     reset_session
41     self.current_user = nil
42   end
43
44   def require_user
45     unless current_user
46       if request.get?
47         redirect_to :controller => "users", :action => "login", :referer => request.fullpath
48       else
49         head :forbidden
50       end
51     end
52   end
53
54   def require_oauth
55     @oauth = current_user.access_token(OAUTH_KEY) if current_user && defined? OAUTH_KEY
56   end
57
58   ##
59   # requires the user to be logged in by the token or HTTP methods, or have an
60   # OAuth token with the right capability. this method is a bit of a pain to call
61   # directly, since it's cumbersome to call filters with arguments in rails. to
62   # make it easier to read and write the code, there are some utility methods
63   # below.
64   def require_capability(cap)
65     # when the current token is nil, it means the user logged in with a different
66     # method, otherwise an OAuth token was used, which has to be checked.
67     unless current_token.nil?
68       unless current_token.read_attribute(cap)
69         set_locale
70         report_error t("oauth.permissions.missing"), :forbidden
71         false
72       end
73     end
74   end
75
76   ##
77   # require the user to have cookies enabled in their browser
78   def require_cookies
79     if request.cookies["_osm_session"].to_s == ""
80       if params[:cookie_test].nil?
81         session[:cookie_test] = true
82         redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
83         false
84       else
85         flash.now[:warning] = t "application.require_cookies.cookies_needed"
86       end
87     else
88       session.delete(:cookie_test)
89     end
90   end
91
92   # Utility methods to make the controller filter methods easier to read and write.
93   def require_allow_read_prefs
94     require_capability(:allow_read_prefs)
95   end
96
97   def require_allow_write_prefs
98     require_capability(:allow_write_prefs)
99   end
100
101   def require_allow_write_diary
102     require_capability(:allow_write_diary)
103   end
104
105   def require_allow_write_api
106     require_capability(:allow_write_api)
107
108     if REQUIRE_TERMS_AGREED && current_user.terms_agreed.nil?
109       report_error "You must accept the contributor terms before you can edit.", :forbidden
110       return false
111     end
112   end
113
114   def require_allow_read_gpx
115     require_capability(:allow_read_gpx)
116   end
117
118   def require_allow_write_gpx
119     require_capability(:allow_write_gpx)
120   end
121
122   ##
123   # sets up the current_user for use by other methods. this is mostly called
124   # from the authorize method, but can be called elsewhere if authorisation
125   # is optional.
126   def setup_user_auth
127     # try and setup using OAuth
128     unless Authenticator.new(self, [:token]).allow?
129       username, passwd = get_auth_data # parse from headers
130       # authenticate per-scheme
131       self.current_user = if username.nil?
132                             nil # no authentication provided - perhaps first connect (client should retry after 401)
133                           elsif username == "token"
134                             User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
135                           else
136                             User.authenticate(:username => username, :password => passwd) # basic auth
137                           end
138     end
139
140     # have we identified the user?
141     if current_user
142       # check if the user has been banned
143       user_block = current_user.blocks.active.take
144       unless user_block.nil?
145         set_locale
146         if user_block.zero_hour?
147           report_error t("application.setup_user_auth.blocked_zero_hour"), :forbidden
148         else
149           report_error t("application.setup_user_auth.blocked"), :forbidden
150         end
151       end
152
153       # if the user hasn't seen the contributor terms then don't
154       # allow editing - they have to go to the web site and see
155       # (but can decline) the CTs to continue.
156       if REQUIRE_TERMS_SEEN && !current_user.terms_seen && flash[:skip_terms].nil?
157         set_locale
158         report_error t("application.setup_user_auth.need_to_see_terms"), :forbidden
159       end
160     end
161   end
162
163   def authorize(realm = "Web Password", errormessage = "Couldn't authenticate you")
164     # make the current_user object from any auth sources we have
165     setup_user_auth
166
167     # handle authenticate pass/fail
168     unless current_user
169       # no auth, the user does not exist or the password was wrong
170       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
171       render :plain => errormessage, :status => :unauthorized
172       return false
173     end
174   end
175
176   ##
177   # to be used as a before_filter *after* authorize. this checks that
178   # the user is a moderator and, if not, returns a forbidden error.
179   def authorize_moderator(errormessage = "Access restricted to moderators")
180     # check user is a moderator
181     unless current_user.moderator?
182       render :plain => errormessage, :status => :forbidden
183       false
184     end
185   end
186
187   def check_database_readable(need_api = false)
188     if STATUS == :database_offline || (need_api && STATUS == :api_offline)
189       if request.xhr?
190         report_error "Database offline for maintenance", :service_unavailable
191       else
192         redirect_to :controller => "site", :action => "offline"
193       end
194     end
195   end
196
197   def check_database_writable(need_api = false)
198     if STATUS == :database_offline || STATUS == :database_readonly ||
199        (need_api && (STATUS == :api_offline || STATUS == :api_readonly))
200       if request.xhr?
201         report_error "Database offline for maintenance", :service_unavailable
202       else
203         redirect_to :controller => "site", :action => "offline"
204       end
205     end
206   end
207
208   def check_api_readable
209     if api_status == :offline
210       report_error "Database offline for maintenance", :service_unavailable
211       false
212     end
213   end
214
215   def check_api_writable
216     unless api_status == :online
217       report_error "Database offline for maintenance", :service_unavailable
218       false
219     end
220   end
221
222   def database_status
223     if STATUS == :database_offline
224       :offline
225     elsif STATUS == :database_readonly
226       :readonly
227     else
228       :online
229     end
230   end
231
232   def api_status
233     status = database_status
234     if status == :online
235       if STATUS == :api_offline
236         status = :offline
237       elsif STATUS == :api_readonly
238         status = :readonly
239       end
240     end
241     status
242   end
243
244   def gpx_status
245     status = database_status
246     status = :offline if status == :online && STATUS == :gpx_offline
247     status
248   end
249
250   def require_public_data
251     unless current_user.data_public?
252       report_error "You must make your edits public to upload new data", :forbidden
253       false
254     end
255   end
256
257   # Report and error to the user
258   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
259   #  rather than only a status code and having the web engine make up a
260   #  phrase from that, we can also put the error message into the status
261   #  message. For now, rails won't let us)
262   def report_error(message, status = :bad_request)
263     # TODO: some sort of escaping of problem characters in the message
264     response.headers["Error"] = message
265
266     if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
267       result = OSM::API.new.get_xml_doc
268       result.root.name = "osmError"
269       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
270       result.root << (XML::Node.new("message") << message)
271
272       render :xml => result.to_s
273     else
274       render :plain => message, :status => status
275     end
276   end
277
278   def preferred_languages(reset = false)
279     @preferred_languages = nil if reset
280     @preferred_languages ||= if params[:locale]
281                                Locale.list(params[:locale])
282                              elsif current_user
283                                current_user.preferred_languages
284                              else
285                                Locale.list(http_accept_language.user_preferred_languages)
286                              end
287   end
288
289   helper_method :preferred_languages
290
291   def set_locale(reset = false)
292     if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
293       current_user.languages = http_accept_language.user_preferred_languages
294       current_user.save
295     end
296
297     I18n.locale = Locale.available.preferred(preferred_languages(reset))
298
299     response.headers["Vary"] = "Accept-Language"
300     response.headers["Content-Language"] = I18n.locale.to_s
301   end
302
303   def api_call_handle_error
304     yield
305   rescue ActiveRecord::RecordNotFound => ex
306     head :not_found
307   rescue LibXML::XML::Error, ArgumentError => ex
308     report_error ex.message, :bad_request
309   rescue ActiveRecord::RecordInvalid => ex
310     message = "#{ex.record.class} #{ex.record.id}: "
311     ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
312     report_error message, :bad_request
313   rescue OSM::APIError => ex
314     report_error ex.message, ex.status
315   rescue AbstractController::ActionNotFound => ex
316     raise
317   rescue StandardError => ex
318     logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
319     ex.backtrace.each { |l| logger.info(l) }
320     report_error "#{ex.class}: #{ex.message}", :internal_server_error
321   end
322
323   ##
324   # asserts that the request method is the +method+ given as a parameter
325   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
326   def assert_method(method)
327     ok = request.send((method.to_s.downcase + "?").to_sym)
328     raise OSM::APIBadMethodError, method unless ok
329   end
330
331   ##
332   # wrap an api call in a timeout
333   def api_call_timeout
334     OSM::Timer.timeout(API_TIMEOUT, Timeout::Error) do
335       yield
336     end
337   rescue Timeout::Error
338     raise OSM::APITimeoutError
339   end
340
341   ##
342   # wrap a web page in a timeout
343   def web_timeout
344     OSM::Timer.timeout(WEB_TIMEOUT, Timeout::Error) do
345       yield
346     end
347   rescue ActionView::Template::Error => ex
348     ex = ex.cause
349
350     if ex.is_a?(Timeout::Error) ||
351        (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
352       render :action => "timeout"
353     else
354       raise
355     end
356   rescue Timeout::Error
357     render :action => "timeout"
358   end
359
360   ##
361   # ensure that there is a "user" instance variable
362   def lookup_user
363     render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
364   end
365
366   ##
367   # render a "no such user" page
368   def render_unknown_user(name)
369     @title = t "users.no_such_user.title"
370     @not_found_user = name
371
372     respond_to do |format|
373       format.html { render :template => "users/no_such_user", :status => :not_found }
374       format.all { head :not_found }
375     end
376   end
377
378   ##
379   # Unfortunately if a PUT or POST request that has a body fails to
380   # read it then Apache will sometimes fail to return the response it
381   # is given to the client properly, instead erroring:
382   #
383   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
384   #
385   # To work round this we call rewind on the body here, which is added
386   # as a filter, to force it to be fetched from Apache into a file.
387   def fetch_body
388     request.body.rewind
389   end
390
391   def map_layout
392     append_content_security_policy_directives(
393       :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
394       :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
395       :connect_src => [NOMINATIM_URL, OVERPASS_URL, OSRM_URL, GRAPHHOPPER_URL],
396       :form_action => %w[render.openstreetmap.org],
397       :style_src => %w['unsafe-inline'],
398       :script_src => [MAPQUEST_DIRECTIONS_URL],
399       :img_src => %w[developer.mapquest.com]
400     )
401
402     if STATUS == :database_offline || STATUS == :api_offline
403       flash.now[:warning] = t("layouts.osm_offline")
404     elsif STATUS == :database_readonly || STATUS == :api_readonly
405       flash.now[:warning] = t("layouts.osm_read_only")
406     end
407
408     request.xhr? ? "xhr" : "map"
409   end
410
411   def allow_thirdparty_images
412     append_content_security_policy_directives(:img_src => %w[*])
413   end
414
415   def preferred_editor
416     editor = if params[:editor]
417                params[:editor]
418              elsif current_user&.preferred_editor
419                current_user.preferred_editor
420              else
421                DEFAULT_EDITOR
422              end
423
424     editor
425   end
426
427   helper_method :preferred_editor
428
429   def update_totp
430     if defined?(TOTP_KEY)
431       cookies["_osm_totp_token"] = {
432         :value => ROTP::TOTP.new(TOTP_KEY, :interval => 3600).now,
433         :domain => "openstreetmap.org",
434         :expires => 1.hour.from_now
435       }
436     end
437   end
438
439   def better_errors_allow_inline
440     yield
441   rescue StandardError
442     append_content_security_policy_directives(
443       :script_src => %w['unsafe-inline'],
444       :style_src => %w['unsafe-inline']
445     )
446
447     raise
448   end
449
450   def current_ability
451     # Use capabilities from the oauth token if it exists and is a valid access token
452     if Authenticator.new(self, [:token]).allow?
453       Ability.new(nil).merge(Capability.new(current_token))
454     else
455       Ability.new(current_user)
456     end
457   end
458
459   def deny_access(exception)
460     if @api_deny_access_handling
461       api_deny_access(exception)
462     else
463       web_deny_access(exception)
464     end
465   end
466
467   def web_deny_access(_exception)
468     if current_token
469       set_locale
470       report_error t("oauth.permissions.missing"), :forbidden
471     elsif current_user
472       set_locale
473       respond_to do |format|
474         format.html { redirect_to :controller => "errors", :action => "forbidden" }
475         format.any { report_error t("application.permission_denied"), :forbidden }
476       end
477     elsif request.get?
478       respond_to do |format|
479         format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
480         format.any { head :forbidden }
481       end
482     else
483       head :forbidden
484     end
485   end
486
487   def api_deny_access(_exception)
488     if current_token
489       set_locale
490       report_error t("oauth.permissions.missing"), :forbidden
491     elsif current_user
492       head :forbidden
493     else
494       realm = "Web Password"
495       errormessage = "Couldn't authenticate you"
496       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
497       render :plain => errormessage, :status => :unauthorized
498     end
499   end
500
501   attr_accessor :api_access_handling
502
503   def api_deny_access_handler
504     @api_deny_access_handling = true
505   end
506
507   private
508
509   # extract authorisation credentials from headers, returns user = nil if none
510   def get_auth_data
511     if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
512       authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
513     elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
514       authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
515     elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
516       authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
517     end
518     # only basic authentication supported
519     user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
520     [user, pass]
521   end
522
523   # override to stop oauth plugin sending errors
524   def invalid_oauth_response; end
525 end