diff --git a/app/controllers/api/v8/users/password_reset_controller.rb b/app/controllers/api/v8/users/password_reset_controller.rb index 539bd6623..cb29c60af 100644 --- a/app/controllers/api/v8/users/password_reset_controller.rb +++ b/app/controllers/api/v8/users/password_reset_controller.rb @@ -25,8 +25,7 @@ def create }, status: :not_found end - key = ActionToken.generate_password_reset_key_for(user) - PasswordResetKeyMailer.reset_link_email(user, key).deliver_now + # Mail is sent only by courses.mooc.fi; the response is kept for existing clients. render json: { success: true } diff --git a/app/controllers/password_reset_keys_controller.rb b/app/controllers/password_reset_keys_controller.rb index 2d954fbbb..f450f86c6 100644 --- a/app/controllers/password_reset_keys_controller.rb +++ b/app/controllers/password_reset_keys_controller.rb @@ -5,7 +5,7 @@ class PasswordResetKeysController < ApplicationController extend T::Sig skip_authorization_check - add_breadcrumb 'Forgot password', ->(*_a) { }, only: %i[new show] + add_breadcrumb 'Forgot password', ->(*_a) { }, only: :show sig { void } def show @@ -13,23 +13,13 @@ def show end sig { void } - def new; end + def new + redirect_to_courses_mooc_fi + end sig { void } def create - email = params['email'].to_s.strip - @email = T.let(email, T.nilable(String)) - if email.empty? - return redirect_to(new_password_reset_key_path, alert: 'No e-mail address provided') - end - - user = User.find_by('lower(email) = ?', email.downcase) - unless user - return redirect_to(new_password_reset_key_path, alert: 'No such e-mail address registered') - end - - key = ActionToken.generate_password_reset_key_for(user) - PasswordResetKeyMailer.reset_link_email(user, key).deliver_now + redirect_to_courses_mooc_fi end sig { void } @@ -84,6 +74,17 @@ def destroy end private + # Only courses.mooc.fi sends password reset mail. + sig { void } + def redirect_to_courses_mooc_fi + reset_url = User.courses_mooc_fi_password_reset_url + if reset_url + redirect_to reset_url, allow_other_host: true + else + render plain: 'Password reset is unavailable.', status: :service_unavailable + end + end + sig { void } def find_key_and_user token = params['token'] diff --git a/app/mailers/password_reset_key_mailer.rb b/app/mailers/password_reset_key_mailer.rb deleted file mode 100644 index f00dd3f04..000000000 --- a/app/mailers/password_reset_key_mailer.rb +++ /dev/null @@ -1,15 +0,0 @@ -# typed: strict -# frozen_string_literal: true - -class PasswordResetKeyMailer < ActionMailer::Base - extend T::Sig - sig { params(user: User, key: ActionToken).void } - def reset_link_email(user, key) - @user = T.let(user, T.nilable(User)) - settings = SiteSetting.value('emails') - - subject = 'Reset your mooc.fi account password' - @url = T.let(settings['baseurl'].sub(/\/+$/, '') + '/reset_password/' + key.token, T.nilable(String)) - mail(from: settings['from'], to: user.email, subject: subject) - end -end diff --git a/app/mailers/user_mailer.rb b/app/mailers/user_mailer.rb index 805747a69..6ef47a2d0 100644 --- a/app/mailers/user_mailer.rb +++ b/app/mailers/user_mailer.rb @@ -11,9 +11,18 @@ def email_confirmation(user, origin = nil, language = nil) # To protect our delivery rates we temporaily disable sending this email. return if origin && origin.downcase.include?('elements') + # Locks the row rather than `user`, which may carry an unsaved email change. The lock keeps + # concurrent requests from all passing the check before any token exists. + token = User.transaction do + User.lock.find(user.id) + next unless MailRateLimit.allowed?(user.verification_tokens.email.where(created_at: MailRateLimit::WINDOW.ago..).pluck(:created_at).compact) + + user.verification_tokens.email.create! + end + return unless token + @origin = T.let(origin, T.nilable(String)) @user = T.let(user, T.nilable(User)) - token = user.verification_tokens.email.create! @url = T.let(confirm_email_url(user.id, token.token, language: language), T.nilable(String)) subject = 'Confirm your mooc.fi account email address' if language == 'en' || language == 'en-lu' || language == 'en-ie' subject = 'Vahvista mooc.fi-tilisi sähköpostiosoite' if language == 'fi' diff --git a/app/models/user.rb b/app/models/user.rb index e2252aee5..40c2996a3 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -535,6 +535,13 @@ def self.courses_mooc_fi_account_settings_url "#{base_url}/user-settings/account" if base_url end + # Where users reset a forgotten password. Nil when courses.mooc.fi isn't configured. + sig { returns(T.nilable(String)) } + def self.courses_mooc_fi_password_reset_url + base_url = courses_mooc_fi_base_url + "#{base_url}/reset-password" if base_url + end + # Where users delete their account, which also deletes it here. Nil when courses.mooc.fi isn't configured. sig { returns(T.nilable(String)) } def self.courses_mooc_fi_account_deletion_url diff --git a/app/services/mail_rate_limit.rb b/app/services/mail_rate_limit.rb new file mode 100644 index 000000000..d16d08cf8 --- /dev/null +++ b/app/services/mail_rate_limit.rb @@ -0,0 +1,18 @@ +# typed: strict +# frozen_string_literal: true + +# How often one user may be sent mail that others can trigger on their behalf. Callers skip the +# send silently, so responses do not reveal whether mail was sent. +module MailRateLimit + extend T::Sig + + MAX_PER_WINDOW = T.let(3, Integer) + MIN_INTERVAL = T.let(5.minutes, ActiveSupport::Duration) + WINDOW = T.let(1.day, ActiveSupport::Duration) + + sig { params(previous_sends: T::Array[Time]).returns(T::Boolean) } + def self.allowed?(previous_sends) + recent = previous_sends.select { |sent_at| sent_at > WINDOW.ago } + recent.size < MAX_PER_WINDOW && recent.none? { |sent_at| sent_at > MIN_INTERVAL.ago } + end +end diff --git a/app/views/password_reset_key_mailer/reset_link_email.html.erb b/app/views/password_reset_key_mailer/reset_link_email.html.erb deleted file mode 100644 index 205778d17..000000000 --- a/app/views/password_reset_key_mailer/reset_link_email.html.erb +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - -

Someone requested a password reset for your mooc.fi account <%= @user.email %>. Please proceed to the following URL to change your password

- - <%= @url %> - -

If you don't want to change your password after all, just ignore this message.

- - diff --git a/app/views/password_reset_key_mailer/reset_link_email.text.erb b/app/views/password_reset_key_mailer/reset_link_email.text.erb deleted file mode 100644 index 07f3ceb00..000000000 --- a/app/views/password_reset_key_mailer/reset_link_email.text.erb +++ /dev/null @@ -1,6 +0,0 @@ -Someone requested a password reset for your mooc.fi account <%= @user.email %>. Please proceed to the following URL to change your password - -<%= @url %> - -If you don't want to change your password after all, just ignore this message. - diff --git a/app/views/password_reset_keys/create.html.erb b/app/views/password_reset_keys/create.html.erb deleted file mode 100644 index 5d560892d..000000000 --- a/app/views/password_reset_keys/create.html.erb +++ /dev/null @@ -1,4 +0,0 @@ -

Forgot password

- -

Password reset link e-mailed to <%= @email %>. Remember to check your spam folder just in case.

- diff --git a/app/views/password_reset_keys/new.html.erb b/app/views/password_reset_keys/new.html.erb deleted file mode 100644 index b9dfbb158..000000000 --- a/app/views/password_reset_keys/new.html.erb +++ /dev/null @@ -1,9 +0,0 @@ -

Forgot password

- -<%= form_tag password_reset_keys_path do %> -
- - <%= text_field_tag :email, nil, class: 'form-control', id: 'email', placeholder: 'Email' %> -
- <%= submit_tag 'Send password reset link', class: 'btn btn-primary' %> -<% end %> diff --git a/config/brakeman.ignore b/config/brakeman.ignore index 1694a47f2..65e0dfe7d 100644 --- a/config/brakeman.ignore +++ b/config/brakeman.ignore @@ -459,6 +459,29 @@ 601 ], "note": "The URL comes from the courses_mooc_fi_base_url site setting, not from request input." + }, + { + "warning_type": "Redirect", + "warning_code": 18, + "fingerprint": "8a112bbfa63d3e6f6838efd741400169e68af6f1d5262f92ce807e45c1585630", + "check_name": "Redirect", + "message": "Possible unprotected redirect", + "file": "app/controllers/password_reset_keys_controller.rb", + "line": 82, + "link": "https://brakemanscanner.org/docs/warning_types/redirect/", + "code": "redirect_to(User.courses_mooc_fi_password_reset_url, :allow_other_host => true)", + "render_path": null, + "location": { + "type": "method", + "class": "PasswordResetKeysController", + "method": "redirect_to_courses_mooc_fi" + }, + "user_input": "User.courses_mooc_fi_password_reset_url", + "confidence": "Weak", + "cwe_id": [ + 601 + ], + "note": "The URL comes from the courses_mooc_fi_base_url site setting, not from request input." } ], "brakeman_version": "8.1.0" diff --git a/sorbet/rbi/dsl/password_reset_key_mailer.rbi b/sorbet/rbi/dsl/password_reset_key_mailer.rbi deleted file mode 100644 index 2bb6b5dc5..000000000 --- a/sorbet/rbi/dsl/password_reset_key_mailer.rbi +++ /dev/null @@ -1,16 +0,0 @@ -# typed: true - -# DO NOT EDIT MANUALLY -# This is an autogenerated file for dynamic methods in `PasswordResetKeyMailer`. -# Please instead update this file by running `bin/tapioca dsl PasswordResetKeyMailer`. - - -class PasswordResetKeyMailer - include GeneratedUrlHelpersModule - include GeneratedMountedHelpers - - class << self - sig { params(user: ::User, key: ::ActionToken).returns(::ActionMailer::MessageDelivery) } - def reset_link_email(user, key); end - end -end diff --git a/spec/integration/reset_password_spec.rb b/spec/integration/reset_password_spec.rb index 06936da3d..b5015b23f 100644 --- a/spec/integration/reset_password_spec.rb +++ b/spec/integration/reset_password_spec.rb @@ -6,21 +6,10 @@ describe "Resetting one's password by e-mail", type: :request, integration: true do include IntegrationTestActions - it 'should be possible' do + it 'should be possible with an existing reset key' do user = FactoryBot.create(:verified_user, login: 'theuser', password: 'forgot_this', email: 'theuser@example.com') - visit '/' - find(:link, 'Log in').trigger('click') - click_link 'I forgot my password' - fill_in 'email', with: 'theuser@example.com' - click_button 'Send password reset link' - - # Pretend we got the e-mail. Too much trouble to extract it from capybara's server process. - - wait_until do - user.reload - !user.password_reset_key.nil? - end + ActionToken.generate_password_reset_key_for(user) visit '/reset_password/' + user.password_reset_key.token diff --git a/spec/mailers/password_reset_key_mailer_spec.rb b/spec/mailers/password_reset_key_mailer_spec.rb deleted file mode 100644 index 3a4d68c15..000000000 --- a/spec/mailers/password_reset_key_mailer_spec.rb +++ /dev/null @@ -1,26 +0,0 @@ -# typed: false -# frozen_string_literal: true - -require 'spec_helper' - -describe PasswordResetKeyMailer, type: :mailer do - before :each do - settings = SiteSetting.all_settings['emails'] - settings['baseurl'] = 'http://example.com/foo' - settings['from'] = 'noreply@example.com' - end - - let(:user) { FactoryBot.create(:user) } - let(:key) { ActionToken.create!(user: user, action: :reset_password) } - - it 'should e-mail a password reset key' do - mail = PasswordResetKeyMailer.reset_link_email(user, key) - - expect(mail.to).to include(user.email) - expect(mail.from).to include('noreply@example.com') - expect(mail.encoded).to include('http://example.com/foo/reset_password/' + key.token) - - mail.deliver - expect(ActionMailer::Base.deliveries).not_to be_empty - end -end diff --git a/spec/requests/password_reset_redirect_spec.rb b/spec/requests/password_reset_redirect_spec.rb new file mode 100644 index 000000000..50b702c73 --- /dev/null +++ b/spec/requests/password_reset_redirect_spec.rb @@ -0,0 +1,29 @@ +# typed: false +# frozen_string_literal: true + +require 'spec_helper' + +describe 'Password reset requests', type: :request do + it 'redirects the reset form to courses.mooc.fi' do + SiteSetting.all_settings['courses_mooc_fi_base_url'] = 'https://courses.mooc.fi' + + get '/password_reset_keys/new' + + expect(response).to redirect_to('https://courses.mooc.fi/reset-password') + end + + it 'redirects a reset request to courses.mooc.fi without sending mail' do + SiteSetting.all_settings['courses_mooc_fi_base_url'] = 'https://courses.mooc.fi' + FactoryBot.create(:user, email: 'student@example.com') + + expect { post '/password_reset_keys', params: { email: 'student@example.com' } } + .not_to(change { ActionMailer::Base.deliveries.count }) + expect(response).to redirect_to('https://courses.mooc.fi/reset-password') + end + + it "is unavailable when courses.mooc.fi isn't configured" do + get '/password_reset_keys/new' + + expect(response).to have_http_status(:service_unavailable) + end +end diff --git a/spec/requests/signup_and_password_reset_throttle_spec.rb b/spec/requests/signup_and_password_reset_throttle_spec.rb index 660cd8c83..9beac3cf9 100644 --- a/spec/requests/signup_and_password_reset_throttle_spec.rb +++ b/spec/requests/signup_and_password_reset_throttle_spec.rb @@ -33,6 +33,8 @@ end it 'counts the email from the query string, which Rails prefers over the body' do + # Unset, the controller itself answers 503, which would mask the throttle. + SiteSetting.all_settings['courses_mooc_fi_base_url'] = 'https://courses.mooc.fi' FactoryBot.create(:user, email: 'student@example.com') 5.times do |i| post '/password_reset_keys?email=student@example.com', params: { email: "decoy#{i}@example.com" }, @@ -71,10 +73,9 @@ it 'leaves a JSON body readable for the app' do FactoryBot.create(:user, email: 'student@example.com') - expect do - post '/api/v8/users/password_reset', params: { email: 'student@example.com' }.to_json, - headers: { 'CONTENT_TYPE' => 'application/json' }, env: { 'REMOTE_ADDR' => ip } - end.to change { ActionMailer::Base.deliveries.size }.by(1) + post '/api/v8/users/password_reset', params: { email: 'student@example.com' }.to_json, + headers: { 'CONTENT_TYPE' => 'application/json' }, env: { 'REMOTE_ADDR' => ip } + expect(response).to have_http_status(:ok) end it 'limits password resets per IP across the web form and the API' do @@ -94,11 +95,11 @@ expect(response).to have_http_status(:service_unavailable) end - it 'leaves the client-supplied origin out of the reset email' do + it 'sends no password reset mail' do FactoryBot.create(:user, email: 'student@example.com') expect do - post '/api/v8/users/password_reset', params: { email: 'student@example.com', origin: 'Call +1 555 0100 to verify' } - end.to change { ActionMailer::Base.deliveries.size }.by(1) - expect(ActionMailer::Base.deliveries.last.body.encoded).not_to include('555 0100') + post '/api/v8/users/password_reset', params: { email: 'student@example.com' } + end.not_to(change { ActionMailer::Base.deliveries.size }) + expect(response).to have_http_status(:ok) end end diff --git a/spec/services/mail_rate_limit_spec.rb b/spec/services/mail_rate_limit_spec.rb new file mode 100644 index 000000000..3d5bc0b6f --- /dev/null +++ b/spec/services/mail_rate_limit_spec.rb @@ -0,0 +1,22 @@ +# typed: false +# frozen_string_literal: true + +require 'spec_helper' + +describe MailRateLimit do + it 'allows a first send' do + expect(MailRateLimit.allowed?([])).to be(true) + end + + it 'refuses a send within the minimum interval' do + expect(MailRateLimit.allowed?([1.minute.ago])).to be(false) + end + + it 'refuses a fourth send within the window' do + expect(MailRateLimit.allowed?([1.hour.ago, 2.hours.ago, 3.hours.ago])).to be(false) + end + + it 'ignores sends outside the window' do + expect(MailRateLimit.allowed?([25.hours.ago, 26.hours.ago, 27.hours.ago])).to be(true) + end +end