Skip to content

Beautiful Open-Source Form Builder

fix(auth): harden email account flows (#1283)

Julien Nahum0397909c4bad
diff --git a/api/app/Http/Controllers/Auth/ForgotPasswordController.php b/api/app/Http/Controllers/Auth/ForgotPasswordController.php
index 9874a5c7d..325a6177b 100644
--- a/api/app/Http/Controllers/Auth/ForgotPasswordController.php
+++ b/api/app/Http/Controllers/Auth/ForgotPasswordController.php
@@ -3,6 +3,7 @@
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
+use App\Jobs\Auth\SendPasswordResetLink;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Http\Request;
@@ -21,24 +22,32 @@ class ForgotPasswordController extends Controller
}
/**
- * Get the response for a successful password reset link.
+ * Send a reset link without revealing whether the email is registered.
*
- * @param string $response
- * @return \Illuminate\Http\RedirectResponse
+ * @return \Illuminate\Http\JsonResponse
*/
- protected function sendResetLinkResponse(Request $request, $response)
+ public function sendResetLinkEmail(Request $request)
{
- return ['status' => trans($response)];
- }
+ $requestedEmail = $request->input('email');
- /**
- * Get the response for a failed password reset link.
- *
- * @param string $response
- * @return \Illuminate\Http\RedirectResponse
- */
- protected function sendResetLinkFailedResponse(Request $request, $response)
- {
- return response()->json(['email' => trans($response)], 400);
+ if (is_string($requestedEmail)) {
+ $request->merge([
+ 'email' => strtolower(trim($requestedEmail)),
+ ]);
+ }
+
+ $this->validateEmail($request);
+
+ $email = $request->string('email')->toString();
+
+ if (config('queue.default') === 'sync') {
+ SendPasswordResetLink::dispatchAfterResponse($email);
+ } else {
+ SendPasswordResetLink::dispatch($email);
+ }
+
+ return response()->json([
+ 'status' => trans('passwords.sent_if_exists'),
+ ]);
}
}
diff --git a/api/app/Http/Controllers/Settings/ProfileController.php b/api/app/Http/Controllers/Settings/ProfileController.php
index db74fac42..9052c3f76 100644
--- a/api/app/Http/Controllers/Settings/ProfileController.php
+++ b/api/app/Http/Controllers/Settings/ProfileController.php
@@ -4,8 +4,10 @@ namespace App\Http\Controllers\Settings;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Http\Exceptions\ThrottleRequestsException;
+use Illuminate\Validation\ValidationException;
class ProfileController extends Controller
{
@@ -17,17 +19,44 @@ class ProfileController extends Controller
public function update(Request $request)
{
$user = $request->user();
+ $requestedEmail = $request->input('email');
+ $emailChanged = is_string($requestedEmail)
+ && strtolower($requestedEmail) !== strtolower($user->email);
- $this->validate($request, [
+ $rules = [
'name' => 'required',
'email' => 'required|email|unique:users,email,' . $user->id,
- ]);
+ ];
+
+ if ($emailChanged && $user->canChangeEmail()) {
+ $rules['current_password'] = ['required', 'string'];
+ }
- // Check if email is actually changing
- $emailChanged = strtolower($request->email) !== strtolower($user->email);
+ $this->validate($request, $rules);
- // Apply throttling only if email is changing
if ($emailChanged) {
+ if (!$user->canChangeEmail()) {
+ throw ValidationException::withMessages([
+ 'email' => ['Your email address is managed by your sign-in provider and cannot be changed here.'],
+ ]);
+ }
+
+ $reauthKey = 'profile-email-reauth:' . $user->id;
+
+ if (RateLimiter::tooManyAttempts($reauthKey, 5)) {
+ throw new ThrottleRequestsException('Too Many Attempts.');
+ }
+
+ if (!Hash::check($request->current_password, $user->password)) {
+ RateLimiter::hit($reauthKey, 60);
+
+ throw ValidationException::withMessages([
+ 'current_password' => ['The current password is incorrect.'],
+ ]);
+ }
+
+ RateLimiter::clear($reauthKey);
+
$key = 'profilechange:' . $user->id;
$attempts = RateLimiter::attempts($key);
diff --git a/api/app/Http/Resources/UserResource.php b/api/app/Http/Resources/UserResource.php
index ad99b45a3..857596e10 100644
--- a/api/app/Http/Resources/UserResource.php
+++ b/api/app/Http/Resources/UserResource.php
@@ -25,6 +25,7 @@ class UserResource extends JsonResource
'has_forms' => $this->has_forms,
'active_license' => $this->licenses()->active()->first(),
'two_factor_enabled' => $this->hasTwoFactorEnabled(),
+ 'can_change_email' => $this->canChangeEmail(),
] : [];
return array_merge(parent::toArray($request), $personalData);
diff --git a/api/app/Jobs/Auth/SendPasswordResetLink.php b/api/app/Jobs/Auth/SendPasswordResetLink.php
new file mode 100644
index 000000000..ac8a2a5b3
--- /dev/null
+++ b/api/app/Jobs/Auth/SendPasswordResetLink.php
@@ -0,0 +1,29 @@
+<?php
+
+namespace App\Jobs\Auth;
+
+use Illuminate\Bus\Queueable;
+use Illuminate\Contracts\Queue\ShouldQueue;
+use Illuminate\Foundation\Bus\Dispatchable;
+use Illuminate\Queue\InteractsWithQueue;
+use Illuminate\Queue\SerializesModels;
+use Illuminate\Support\Facades\Password;
+
+class SendPasswordResetLink implements ShouldQueue
+{
+ use Dispatchable;
+ use InteractsWithQueue;
+ use Queueable;
+ use SerializesModels;
+
+ public function __construct(public string $email)
+ {
+ }
+
+ public function handle(): void
+ {
+ Password::broker()->sendResetLink([
+ 'email' => $this->email,
+ ]);
+ }
+}
diff --git a/api/app/Models/User.php b/api/app/Models/User.php
index a6c537017..a799d006e 100644
--- a/api/app/Models/User.php
+++ b/api/app/Models/User.php
@@ -203,6 +203,12 @@ class User extends Authenticatable implements JWTSubject, CachableAttributes, Tw
return !is_null($this->blocked_at);
}
+ public function canChangeEmail(): bool
+ {
+ return !empty($this->password)
+ && ($this->meta['signup_provider'] ?? null) !== 'oidc';
+ }
+
public function blockUser(string $reason, ?int $moderatorId): void
{
$this->blocked_at = now();
diff --git a/api/app/Providers/RouteServiceProvider.php b/api/app/Providers/RouteServiceProvider.php
index 2fe61722d..a550f0ab3 100644
--- a/api/app/Providers/RouteServiceProvider.php
+++ b/api/app/Providers/RouteServiceProvider.php
@@ -52,6 +52,19 @@ class RouteServiceProvider extends ServiceProvider
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
+ RateLimiter::for('password-reset', function (Request $request) {
+ $ip = $request->ip();
+ $requestedEmail = $request->input('email');
+ $email = is_string($requestedEmail) ? strtolower(trim($requestedEmail)) : 'invalid';
+ $emailKey = hash('sha256', $email !== '' ? $email : 'unknown');
+
+ return [
+ Limit::perMinute(5)->by('password-reset:minute:ip:' . $ip),
+ Limit::perHour(30)->by('password-reset:hour:ip:' . $ip),
+ Limit::perHour(5)->by('password-reset:hour:email:' . $emailKey),
+ ];
+ });
+
RateLimiter::for('oidc-init', function (Request $request) {
$connection = (string) ($request->route('slug') ?? 'unknown');
$key = hash('sha256', $request->ip() . '|' . $connection);
diff --git a/api/resources/lang/en/passwords.php b/api/resources/lang/en/passwords.php
index 2345a56b5..5cdd382fa 100644
--- a/api/resources/lang/en/passwords.php
+++ b/api/resources/lang/en/passwords.php
@@ -15,6 +15,7 @@ return [
'reset' => 'Your password has been reset!',
'sent' => 'We have emailed your password reset link!',
+ 'sent_if_exists' => 'If an account exists for that email, we have sent a password reset link.',
'throttled' => 'Please wait before retrying.',
'token' => 'This password reset token is invalid.',
'user' => "We can't find a user with that email address.",
diff --git a/api/routes/api.php b/api/routes/api.php
index 4ed4c413e..34d7ef1c5 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -438,7 +438,8 @@ Route::group(['middleware' => 'guest:api'], function () {
Route::post('login', [LoginController::class, 'login'])->name('login');
Route::post('register', [RegisterController::class, 'register']);
- Route::post('password/email', [ForgotPasswordController::class, 'sendResetLinkEmail']);
+ Route::post('password/email', [ForgotPasswordController::class, 'sendResetLinkEmail'])
+ ->middleware('throttle:password-reset');
Route::post('password/reset', [ResetPasswordController::class, 'reset']);
Route::post('email/verify/{user}', [VerificationController::class, 'verify'])->name('verification.verify');
diff --git a/api/tests/Feature/EmailChangeThrottlingTest.php b/api/tests/Feature/EmailChangeThrottlingTest.php
index e6c14d82d..9e6b9caef 100644
--- a/api/tests/Feature/EmailChangeThrottlingTest.php
+++ b/api/tests/Feature/EmailChangeThrottlingTest.php
@@ -13,6 +13,7 @@ it('allows first two email changes within an hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertSuccessful();
@@ -20,6 +21,7 @@ it('allows first two email changes within an hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertSuccessful();
});
@@ -35,6 +37,7 @@ it('blocks third email change within an hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertSuccessful();
@@ -42,6 +45,7 @@ it('blocks third email change within an hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertSuccessful();
@@ -49,6 +53,7 @@ it('blocks third email change within an hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertStatus(429)
->assertJson([
@@ -89,6 +94,7 @@ it('resets throttle counter after one hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertSuccessful();
@@ -96,6 +102,7 @@ it('resets throttle counter after one hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertSuccessful();
@@ -103,6 +110,7 @@ it('resets throttle counter after one hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertStatus(429);
@@ -112,6 +120,7 @@ it('resets throttle counter after one hour', function () {
$response = $this->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
]);
$response->assertSuccessful();
});
diff --git a/api/tests/Feature/ForgotPasswordTest.php b/api/tests/Feature/ForgotPasswordTest.php
new file mode 100644
index 000000000..bd990f495
--- /dev/null
+++ b/api/tests/Feature/ForgotPasswordTest.php
@@ -0,0 +1,129 @@
+<?php
+
+use App\Jobs\Auth\SendPasswordResetLink;
+use App\Models\User;
+use App\Notifications\ResetPassword;
+use Illuminate\Routing\Middleware\ThrottleRequests;
+use Illuminate\Support\Facades\Bus;
+use Illuminate\Support\Facades\Notification;
+
+beforeEach(function () {
+ $this->withMiddleware(ThrottleRequests::class);
+});
+
+it('returns the same response whether or not the email exists', function () {
+ Bus::fake();
+
+ User::factory()->create([
+ 'email' => '[email protected]',
+ ]);
+
+ $registeredResponse = $this
+ ->withServerVariables(['REMOTE_ADDR' => '198.51.100.10'])
+ ->postJson('/password/email', [
+ 'email' => '[email protected]',
+ ]);
+
+ $unregisteredResponse = $this
+ ->withServerVariables(['REMOTE_ADDR' => '198.51.100.10'])
+ ->postJson('/password/email', [
+ 'email' => '[email protected]',
+ ]);
+
+ $registeredResponse->assertOk();
+ $unregisteredResponse->assertOk();
+ expect($registeredResponse->json())->toBe($unregisteredResponse->json());
+ Bus::assertDispatchedAfterResponseTimes(SendPasswordResetLink::class, 2);
+});
+
+it('normalizes the email before dispatching the reset job', function () {
+ Bus::fake();
+
+ $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.11'])
+ ->postJson('/password/email', [
+ 'email' => ' [email protected] ',
+ ])
+ ->assertOk();
+
+ Bus::assertDispatchedAfterResponse(
+ SendPasswordResetLink::class,
+ fn (SendPasswordResetLink $job) => $job->email === '[email protected]'
+ );
+});
+
+it('rejects a structured email value without dispatching a reset job', function () {
+ Bus::fake();
+
+ $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.12'])
+ ->postJson('/password/email', [
+ 'email' => ['not-a-string'],
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('email');
+
+ Bus::assertNotDispatched(SendPasswordResetLink::class);
+});
+
+it('dispatches immediately to an asynchronous queue connection', function () {
+ Bus::fake();
+ config(['queue.default' => 'redis']);
+
+ $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.13'])
+ ->postJson('/password/email', [
+ 'email' => '[email protected]',
+ ])
+ ->assertOk();
+
+ Bus::assertDispatched(SendPasswordResetLink::class);
+ Bus::assertNotDispatchedAfterResponse(SendPasswordResetLink::class);
+});
+
+it('sends a reset notification only when the normalized email exists', function () {
+ Notification::fake();
+
+ $user = User::factory()->create([
+ 'email' => '[email protected]',
+ ]);
+
+ (new SendPasswordResetLink('[email protected]'))->handle();
+ (new SendPasswordResetLink('[email protected]'))->handle();
+
+ Notification::assertSentTo($user, ResetPassword::class);
+ Notification::assertCount(1);
+});
+
+it('limits password reset requests per ip address', function () {
+ Bus::fake();
+
+ foreach (range(1, 5) as $attempt) {
+ $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.20'])
+ ->postJson('/password/email', [
+ 'email' => "missing-{$attempt}@example.com",
+ ])
+ ->assertOk();
+ }
+
+ $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.20'])
+ ->postJson('/password/email', [
+ 'email' => '[email protected]',
+ ])
+ ->assertTooManyRequests();
+});
+
+it('limits password reset requests per email across ip addresses', function () {
+ Bus::fake();
+
+ foreach (range(1, 5) as $attempt) {
+ $this->withServerVariables(['REMOTE_ADDR' => "198.51.100.{$attempt}"])
+ ->postJson('/password/email', [
+ 'email' => '[email protected]',
+ ])
+ ->assertOk();
+ }
+
+ $this->withServerVariables(['REMOTE_ADDR' => '198.51.100.100'])
+ ->postJson('/password/email', [
+ 'email' => '[email protected]',
+ ])
+ ->assertTooManyRequests();
+});
diff --git a/api/tests/Feature/SettingsTest.php b/api/tests/Feature/SettingsTest.php
index be7376489..1ef9c9e49 100644
--- a/api/tests/Feature/SettingsTest.php
+++ b/api/tests/Feature/SettingsTest.php
@@ -8,6 +8,7 @@ it('update profile info', function () {
->patchJson('/settings/profile', [
'name' => 'Test User',
'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
])
->assertSuccessful()
->assertJsonStructure(['id', 'name', 'email']);
@@ -19,6 +20,155 @@ it('update profile info', function () {
]);
});
+it('requires the current password when changing email', function () {
+ $user = User::factory()->create([
+ 'email' => '[email protected]',
+ ]);
+
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'Test User',
+ 'email' => '[email protected]',
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('current_password');
+
+ expect($user->refresh()->email)->toBe('[email protected]');
+});
+
+it('rejects an incorrect current password when changing email', function () {
+ $user = User::factory()->create([
+ 'email' => '[email protected]',
+ ]);
+
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'Test User',
+ 'email' => '[email protected]',
+ 'current_password' => 'incorrect-password',
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('current_password');
+
+ expect($user->refresh()->email)->toBe('[email protected]');
+});
+
+it('throttles repeated current password guesses when changing email', function () {
+ $user = User::factory()->create([
+ 'email' => '[email protected]',
+ ]);
+
+ foreach (range(1, 5) as $attempt) {
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'Test User',
+ 'email' => '[email protected]',
+ 'current_password' => "incorrect-password-{$attempt}",
+ ])
+ ->assertUnprocessable();
+ }
+
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'Test User',
+ 'email' => '[email protected]',
+ 'current_password' => 'Abcd@1234',
+ ])
+ ->assertTooManyRequests();
+
+ expect($user->refresh()->email)->toBe('[email protected]');
+});
+
+it('does not require the current password when email is unchanged', function () {
+ $user = User::factory()->create([
+ 'name' => 'Original Name',
+ 'email' => '[email protected]',
+ ]);
+
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'Updated Name',
+ 'email' => '[email protected]',
+ ])
+ ->assertSuccessful();
+
+ expect($user->refresh()->name)->toBe('Updated Name');
+});
+
+it('rejects a structured email value without throwing a server error', function () {
+ $user = User::factory()->create();
+
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'Test User',
+ 'email' => ['not-a-string'],
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('email');
+});
+
+it('does not offer an email change to a passwordless account', function () {
+ $user = User::factory()->create([
+ 'email' => '[email protected]',
+ 'password' => null,
+ 'meta' => [
+ 'signup_provider' => 'google',
+ 'signup_provider_user_id' => 'google-user-id',
+ ],
+ ]);
+
+ $this->actingAs($user)
+ ->getJson('/user')
+ ->assertSuccessful()
+ ->assertJsonPath('can_change_email', false);
+
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'OAuth User',
+ 'email' => '[email protected]',
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('email');
+
+ expect($user->refresh()->email)->toBe('[email protected]');
+});
+
+it('does not offer an email change to an OIDC-managed account', function () {
+ $user = User::factory()->create([
+ 'email' => '[email protected]',
+ 'password' => Hash::make('unavailable-random-password'),
+ 'meta' => [
+ 'signup_provider' => 'oidc',
+ 'signup_provider_user_id' => 'oidc-user-id',
+ ],
+ ]);
+
+ $this->actingAs($user)
+ ->getJson('/user')
+ ->assertSuccessful()
+ ->assertJsonPath('can_change_email', false);
+
+ $this->actingAs($user)
+ ->patchJson('/settings/profile', [
+ 'name' => 'OIDC User',
+ 'email' => '[email protected]',
+ 'current_password' => 'unavailable-random-password',
+ ])
+ ->assertUnprocessable()
+ ->assertJsonValidationErrors('email');
+
+ expect($user->refresh()->email)->toBe('[email protected]');
+});
+
+it('offers an email change to an account with a local password', function () {
+ $user = User::factory()->create();
+
+ $this->actingAs($user)
+ ->getJson('/user')
+ ->assertSuccessful()
+ ->assertJsonPath('can_change_email', true);
+});
+
it('update password', function () {
$this->actingAs($user = User::factory()->create())
->patchJson('/settings/password', [
diff --git a/client/components/users/settings/Account.vue b/client/components/users/settings/Account.vue
index 445d8e25e..e47d193cb 100644
--- a/client/components/users/settings/Account.vue
+++ b/client/components/users/settings/Account.vue
@@ -28,6 +28,23 @@
type="email"
placeholder="Enter your email"
:required="true"
+ :disabled="user?.can_change_email === false"
+ >
+ <template
+ v-if="user?.can_change_email === false"
+ #help
+ >
+ Your email address is managed by your sign-in provider.
+ </template>
+ </text-input>
+ <TextInput
+ v-if="isEmailChanged && user?.can_change_email !== false"
+ :form="profileForm"
+ name="current_password"
+ label="Current Password"
+ native-type="password"
+ placeholder="Enter current password"
+ :required="true"
/>
</div>
@@ -70,15 +87,12 @@
// Use useAuth composable for all user-related mutations
const alert = useAlert()
-// Auth composable (TanStack Query powered)
const {
- updateProfile: updateProfileMutationFactory,
deleteAccount: deleteAccountFactory,
invalidateUser
} = useAuth()
// Query mutations
-const updateMutation = updateProfileMutationFactory()
const deleteMutation = deleteAccountFactory()
const { data: user } = useAuth().user()
@@ -87,11 +101,16 @@ const { data: user } = useAuth().user()
const profileForm = useForm({
name: '',
email: '',
+ current_password: '',
+})
+
+const isEmailChanged = computed(() => {
+ return Boolean(user.value) && profileForm.email.trim().toLowerCase() !== user.value.email.toLowerCase()
})
// Update profile
const updateProfile = () => {
- profileForm.mutate(updateMutation)
+ profileForm.patch('/settings/profile')
.then(() => {
invalidateUser()
alert.success('Your info has been updated!')
@@ -100,6 +119,9 @@ const updateProfile = () => {
console.error(error)
alert.error(error?.data?.message || 'Error updating profile')
})
+ .finally(() => {
+ profileForm.current_password = ''
+ })
}
// Delete account confirmation
@@ -122,22 +144,30 @@ const deleteAccount = () => {
})
}
+function syncProfileForm(currentUser) {
+ profileForm.name = currentUser.name
+ profileForm.email = currentUser.email
+ profileForm.current_password = ''
+}
+
// Initialize form with user data
onBeforeMount(() => {
if (user.value) {
- profileForm.keys().forEach((key) => {
- profileForm[key] = user.value[key]
- })
+ syncProfileForm(user.value)
}
})
// Watch for user changes
watch(user, (newUser) => {
if (newUser) {
- profileForm.keys().forEach((key) => {
- profileForm[key] = newUser[key]
- })
+ syncProfileForm(newUser)
}
}, { immediate: true })
-</script>
\ No newline at end of file
+watch(isEmailChanged, (emailChanged) => {
+ if (!emailChanged) {
+ profileForm.current_password = ''
+ }
+})
+
+</script>