Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions app/controllers/api/v8/users/password_reset_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
31 changes: 16 additions & 15 deletions app/controllers/password_reset_keys_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,21 @@ 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
find_key_and_user
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 }
Expand Down Expand Up @@ -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']
Expand Down
15 changes: 0 additions & 15 deletions app/mailers/password_reset_key_mailer.rb

This file was deleted.

11 changes: 10 additions & 1 deletion app/mailers/user_mailer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
7 changes: 7 additions & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions app/services/mail_rate_limit.rb
Original file line number Diff line number Diff line change
@@ -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
13 changes: 0 additions & 13 deletions app/views/password_reset_key_mailer/reset_link_email.html.erb

This file was deleted.

6 changes: 0 additions & 6 deletions app/views/password_reset_key_mailer/reset_link_email.text.erb

This file was deleted.

4 changes: 0 additions & 4 deletions app/views/password_reset_keys/create.html.erb

This file was deleted.

9 changes: 0 additions & 9 deletions app/views/password_reset_keys/new.html.erb

This file was deleted.

23 changes: 23 additions & 0 deletions config/brakeman.ignore
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
16 changes: 0 additions & 16 deletions sorbet/rbi/dsl/password_reset_key_mailer.rbi

This file was deleted.

15 changes: 2 additions & 13 deletions spec/integration/reset_password_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
26 changes: 0 additions & 26 deletions spec/mailers/password_reset_key_mailer_spec.rb

This file was deleted.

29 changes: 29 additions & 0 deletions spec/requests/password_reset_redirect_spec.rb
Original file line number Diff line number Diff line change
@@ -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
17 changes: 9 additions & 8 deletions spec/requests/signup_and_password_reset_throttle_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
Expand Down Expand Up @@ -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
Expand All @@ -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
22 changes: 22 additions & 0 deletions spec/services/mail_rate_limit_spec.rb
Original file line number Diff line number Diff line change
@@ -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
Loading