diff --git a/server/src/db/entities/PasswordResetTokens.entity.ts b/server/src/db/entities/PasswordResetTokens.entity.ts index 8f015cdfc..f28cf6a1f 100644 --- a/server/src/db/entities/PasswordResetTokens.entity.ts +++ b/server/src/db/entities/PasswordResetTokens.entity.ts @@ -13,6 +13,7 @@ export class PasswordResetTokens { consumed_at?: string | null; created_at?: string | null; created_ip?: string | null; + email?: string | null; } export const PasswordResetTokensSchema = defineEntity({ @@ -28,5 +29,6 @@ export const PasswordResetTokensSchema = defineEntity({ consumed_at: p.type(DbTimestampType).nullable(), created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), created_ip: p.text().nullable(), + email: p.text().nullable(), }, }); diff --git a/server/src/db/kysely/PasswordResetTokens.table.ts b/server/src/db/kysely/PasswordResetTokens.table.ts index c41b0d648..879954ced 100644 --- a/server/src/db/kysely/PasswordResetTokens.table.ts +++ b/server/src/db/kysely/PasswordResetTokens.table.ts @@ -10,4 +10,5 @@ export interface PasswordResetTokensTable { consumed_at: InsertOptional; created_at: InsertOptional; created_ip: InsertOptional; + email: InsertOptional; } diff --git a/server/src/db/migrations/Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to.ts b/server/src/db/migrations/Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to.ts new file mode 100644 index 000000000..82a9d1bc8 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to.ts @@ -0,0 +1,21 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * A password reset link remembers the address it was mailed to, so it stops + * working once the account has moved to another address. + * + * `password_reset_tokens.email` holds the account's address at the moment the + * link was issued. Every link issued before this step starts empty and keeps + * working until it expires or is used, as it did before. + */ +export class Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to extends Migration { + override name = 'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to'; + + override up(): void { + engineDdl(this, { + sqlite: ['ALTER TABLE password_reset_tokens ADD COLUMN email TEXT'], + postgres: ['alter table "password_reset_tokens" add column "email" text null'], + }); + } +} diff --git a/server/src/db/repositories/PasswordResetTokens.repository.ts b/server/src/db/repositories/PasswordResetTokens.repository.ts index 3448d03f8..d2c2d3ce6 100644 --- a/server/src/db/repositories/PasswordResetTokens.repository.ts +++ b/server/src/db/repositories/PasswordResetTokens.repository.ts @@ -13,6 +13,7 @@ export interface PasswordResetTokenRow { consumed_at: string | null; created_at: string | null; created_ip: string | null; + email: string | null; } const _passwordResetTokenRowKeys: AssertRowKeys = true; @@ -23,6 +24,7 @@ export interface NewPasswordResetTokenRow { token_hash: string; expires_at: DbTimestamp; created_ip: string | null; + email: string; } /** `AuthService.resetPassword`'s lookup (AU39). */ @@ -31,6 +33,7 @@ export interface PasswordResetTokenLookup { user_id: number; expires_at: string; consumed_at: string | null; + email: string | null; } /** @@ -78,6 +81,7 @@ export class PasswordResetTokensRepository extends TrekRepository { - const row = await this.findOne({ token_hash: hash }, { fields: ['id', 'user', 'expires_at', 'consumed_at'] }); + const row = await this.findOne( + { token_hash: hash }, + { fields: ['id', 'user', 'expires_at', 'consumed_at', 'email'] }, + ); return row - ? { id: row.id, user_id: row.user.id, expires_at: row.expires_at, consumed_at: row.consumed_at ?? null } + ? { + id: row.id, + user_id: row.user.id, + expires_at: row.expires_at, + consumed_at: row.consumed_at ?? null, + email: row.email ?? null, + } : null; } diff --git a/server/src/nest/auth/auth.service.ts b/server/src/nest/auth/auth.service.ts index 6a31966f8..f45a0aafc 100644 --- a/server/src/nest/auth/auth.service.ts +++ b/server/src/nest/auth/auth.service.ts @@ -987,11 +987,22 @@ export class AuthService { const token_hash = hashResetToken(raw); const expires_at = dbNow(new Date(Date.now() + PASSWORD_RESET_TTL_MS)); // Invalidate any prior unconsumed tokens for this user and issue the new one - // together, so there is always exactly one live reset link in flight. - await this.uow.transactional(async () => { + // together, so there is always exactly one live reset link in flight. The + // address is read again here: one changed since the lookup gets no link. + const issued = await this.uow.transactional(async () => { + const current = await this.usersRepo.getEmail(user.id); + if (current === null || current.toLowerCase() !== user.email.toLowerCase()) return false; await this.passwordResetTokens.consumeAllLiveForUser(user.id); - await this.passwordResetTokens.insertToken({ user_id: user.id, token_hash, expires_at, created_ip: createdIp }); + await this.passwordResetTokens.insertToken({ + user_id: user.id, + token_hash, + expires_at, + created_ip: createdIp, + email: user.email, + }); + return true; }); + if (!issued) return { tokenForDelivery: null, userId: null, userEmail: null, reason: 'no_user' }; return { tokenForDelivery: raw, userId: user.id, userEmail: user.email, reason: 'issued' }; } @@ -1028,6 +1039,10 @@ export class AuthService { const user = await this.usersRepo.findResetTarget(row.user_id); if (!user) throw new DomainError(400, 'Invalid or expired reset link'); + // A link mailed to an address the account no longer has is dead. + if (row.email !== null && row.email.toLowerCase() !== user.email.toLowerCase()) { + throw new DomainError(400, 'Invalid or expired reset link'); + } // MFA gate. If enabled, require a valid TOTP or backup code. const mfaOn = user.mfa_enabled === 1; diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts index c24029c03..6d6186912 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -118,6 +118,7 @@ const UNNUMBERED = [ 'Migration20200101046490_a_trip_can_switch_its_own_addons', 'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account', 'Migration20200101046510_a_session_knows_its_provider_session', + 'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/password-reset-email-migration.test.ts b/server/tests/unit/db/password-reset-email-migration.test.ts new file mode 100644 index 000000000..5711d5dae --- /dev/null +++ b/server/tests/unit/db/password-reset-email-migration.test.ts @@ -0,0 +1,49 @@ +/** + * `Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to`: + * the nullable `password_reset_tokens.email` column. Migrate to the step + * before it with a live link already there, apply just this one, and check + * that the link comes through untouched with no address. + */ +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; + +import { describe, expect, it } from 'vitest'; + +const TARGET = 'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to'; + +describe('password_reset_tokens.email migration', () => { + it('PWDRESETMIG-001: adds a nullable text column and leaves existing links as they were', async () => { + const orm = await createMigrationOrm(); + try { + const names = await pendingNames(orm); + const idx = names.indexOf(TARGET); + expect(idx).toBeGreaterThan(0); + const previous = names[idx - 1]; + if (!previous) throw new Error('no step before the target'); + await migrateTo(orm, previous); + await rawExec( + orm, + "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'owner@test', 'x')", + ); + await rawExec( + orm, + "INSERT INTO password_reset_tokens (id, user_id, token_hash, expires_at) VALUES (7, 1, 'h', '2030-01-01 00:00:00')", + ); + + await migrateTo(orm, TARGET); + + const columns = await rawQuery<{ name: string; type: string; notnull: number }>( + orm, + "SELECT name, type, \"notnull\" FROM pragma_table_info('password_reset_tokens') WHERE name = 'email'", + ); + expect(columns).toEqual([{ name: 'email', type: 'TEXT', notnull: 0 }]); + expect( + await rawQuery( + orm, + 'SELECT id, user_id, token_hash, consumed_at, email FROM password_reset_tokens WHERE id = 7', + ), + ).toEqual([{ id: 7, user_id: 1, token_hash: 'h', consumed_at: null, email: null }]); + } finally { + await orm.close(true); + } + }); +}); diff --git a/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts b/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts index c9b4e6f7b..4ae11b2d7 100644 --- a/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts +++ b/server/tests/unit/db/repositories/PasswordResetTokens.repository.test.ts @@ -66,6 +66,7 @@ describe('PasswordResetTokensRepository', () => { token_hash: tokenHash, expires_at: expiresAt, created_ip: '1.2.3.4', + email: 'owner@example.com', }); const row = await findRow(t, PasswordResetTokens, { token_hash: tokenHash }); @@ -75,13 +76,20 @@ describe('PasswordResetTokensRepository', () => { expires_at: expiresAt, consumed_at: null, created_ip: '1.2.3.4', + email: 'owner@example.com', }); }); it('PWDRESETREPO-002: writes a NULL created_ip', async () => { const { user } = createUser(testDb); const tokenHash = hash('no-ip-token'); - await tokens.insertToken({ user_id: user.id, token_hash: tokenHash, expires_at: dbNow(), created_ip: null }); + await tokens.insertToken({ + user_id: user.id, + token_hash: tokenHash, + expires_at: dbNow(), + created_ip: null, + email: user.email, + }); const row = await findRow(t, PasswordResetTokens, { token_hash: tokenHash }); expect(row?.created_ip).toBeNull(); @@ -96,7 +104,21 @@ describe('PasswordResetTokensRepository', () => { const found = await tokens.findByTokenHash(tokenHash); - expect(found).toEqual({ id, user_id: user.id, expires_at: expect.any(String), consumed_at: null }); + expect(found).toEqual({ id, user_id: user.id, expires_at: expect.any(String), consumed_at: null, email: null }); + }); + + it('PWDRESETREPO-003b: carries the address the link was issued for', async () => { + const { user } = createUser(testDb); + const tokenHash = hash('bound-to-address'); + await tokens.insertToken({ + user_id: user.id, + token_hash: tokenHash, + expires_at: dbNow(), + created_ip: null, + email: 'bound@example.com', + }); + + expect((await tokens.findByTokenHash(tokenHash))?.email).toBe('bound@example.com'); }); it('PWDRESETREPO-004: a consumed token is still found (consumed_at is checked by the caller, not filtered here)', async () => { diff --git a/server/tests/unit/nest/auth.service.test.ts b/server/tests/unit/nest/auth.service.test.ts index f37a311b0..900c7ea79 100644 --- a/server/tests/unit/nest/auth.service.test.ts +++ b/server/tests/unit/nest/auth.service.test.ts @@ -1444,6 +1444,52 @@ describe('resetPassword', () => { await svc.requestPasswordReset(user.email, null); expect((await svc.requestPasswordReset(user.email, null)).reason).toBe('throttled_per_email'); }); + + it('AUTH-DB-085b: an address changed while the request runs gets no link', async () => { + const { user } = createUser(testDb); + const usersRepo = await createTestUsersRepo(testDb); + const original = usersRepo.findForPasswordReset.bind(usersRepo); + const lookupSpy = vi.spyOn(usersRepo, 'findForPasswordReset').mockImplementationOnce(async (email) => { + const found = await original(email); + await updateRows(orm, Users, { id: user.id }, { email: 'moved@example.com' }); + return found; + }); + try { + const result = await svc.requestPasswordReset(user.email, null); + expect(result).toEqual({ tokenForDelivery: null, userId: null, userEmail: null, reason: 'no_user' }); + } finally { + lookupSpy.mockRestore(); + } + expect(await countRows(orm, PasswordResetTokens, { user: user.id })).toBe(0); + }); + + it('AUTH-DB-085c: a link stops working once the account has moved to another address', async () => { + const { user } = createUser(testDb); + const issued = await svc.requestPasswordReset(user.email, null); + expect((await findRow(orm, PasswordResetTokens, { user: user.id })).email).toBe(user.email); + await updateRows(orm, Users, { id: user.id }, { email: 'moved@example.com' }); + + expect( + await asLegacyResult(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' })), + ).toEqual({ error: 'Invalid or expired reset link', status: 400 }); + expect((await readUser(orm, user.id)).password_version).toBe(0); + }); + + it('AUTH-DB-085d: a change of case only, or a link from before links knew their address, still resets', async () => { + const { user } = createUser(testDb); + const issued = await svc.requestPasswordReset(user.email, null); + await updateRows(orm, Users, { id: user.id }, { email: user.email.toUpperCase() }); + expect( + await asLegacyResult(svc.resetPassword({ token: issued.tokenForDelivery!, new_password: 'Fresh123!' })), + ).toEqual({ success: true, userId: user.id }); + + const { user: older } = createUser(testDb); + const legacy = await svc.requestPasswordReset(older.email, null); + await updateRows(orm, PasswordResetTokens, { user: older.id }, { email: null }); + expect( + await asLegacyResult(svc.resetPassword({ token: legacy.tokenForDelivery!, new_password: 'Fresh123!' })), + ).toEqual({ success: true, userId: older.id }); + }); }); // ---------------------------------------------------------------------------