fix(oidc): verify mailbox identity before linking accounts

Preserve the provider mailbox on new accounts. For existing accounts, use the stored issuer and subject or check mailbox identity before linking. Keep the candidate lookup and identity update inside the same transaction.
This commit is contained in:
Maurice
2026-12-01 11:20:09 +01:00
parent 0d521f0930
commit 1ff8a814ae
8 changed files with 60 additions and 78 deletions
+2 -20
View File
@@ -478,9 +478,8 @@ export class UsersRepository extends TrekRepository<Users> {
* in SQL, so a JS-lowered bind here would disagree with the column on
* every non-ASCII cased character (program rule 18; Plan 3b Task 7
* review, H1: a `JOSÉ@x.com` account could register but never log back
* in). Distinct from `findByEmailLoweredBind` below, which mirrors O4's
* different legacy statement — do not collapse the two back into one
* method (D4).
* in). OIDC also uses this to find a candidate before checking the mailbox
* local part for an exact match.
*/
async findByEmailCI(email: string): Promise<UserRow | null> {
const platform = this.getEntityManager().getPlatform();
@@ -488,23 +487,6 @@ export class UsersRepository extends TrekRepository<Users> {
return user ? (toRow(user) as UserRow) : null;
}
/**
* `SELECT * FROM users WHERE LOWER(email) = ? AND COALESCE(is_guest, 0) = 0`
* — O4 (`OidcService.findOrCreateUser`, `oidc.service.ts:655`), whose only
* caller JS-lowers the email itself (`oidc.service.ts:620`,
* `userInfo.email.trim().toLowerCase()`) before calling this method,
* exactly mirroring the legacy statement's `LOWER(email) = ?` (SQL
* `LOWER()` on the column, a bind the CALLER already lowered — not a
* second SQL `LOWER()` on the value side). Do not point a caller that has
* NOT already lowered its value at this method — use `findByEmailCI`
* above instead.
*/
async findByEmailLoweredBind(alreadyLoweredEmail: string): Promise<UserRow | null> {
const platform = this.getEntityManager().getPlatform();
const user = await this.findOne({ [lower(platform, 'email')]: alreadyLoweredEmail, is_guest: 0 });
return user ? (toRow(user) as UserRow) : null;
}
// ---------------------------------------------------------------------
// AuthService.demoLogin (auth.service.ts:~376) — inventory-correction
// addition, Plan 3b Task 1 fix round item 7 (pre-authorised for Task 5).
+10
View File
@@ -0,0 +1,10 @@
export function sameMailbox(stored: string, claimed: string): boolean {
const storedAt = stored.lastIndexOf('@');
const claimedAt = claimed.lastIndexOf('@');
if (storedAt < 1 || claimedAt < 1 || storedAt === stored.length - 1 || claimedAt === claimed.length - 1) return false;
return (
stored.slice(0, storedAt) === claimed.slice(0, claimedAt) &&
stored.slice(storedAt + 1).toLowerCase() === claimed.slice(claimedAt + 1).toLowerCase()
);
}
+20 -22
View File
@@ -16,6 +16,7 @@ import { UnitOfWork } from '../database/unit-of-work';
import type { SessionClient } from '../sessions/sessions.service';
import { TripMembershipService } from '../trip-membership/trip-membership.service';
import { InMemoryOidcFlowStore, OidcFlowStore, type OidcPendingState } from './oidc-flow.store';
import { sameMailbox } from './oidc-mailbox';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, OnModuleDestroy } from '@nestjs/common';
@@ -705,16 +706,20 @@ export class OidcService implements OnModuleDestroy {
picture: string | null,
): Promise<{ user: User; roleChange?: OidcRoleChange } | { error: string }> {
// A row that does not carry this sub and issuer was found by its email
// address alone. Linking it takes two promises: the IdP says the address is
// verified, and the address on the row was not typed in by the account itself
// (signup, profile settings), or whoever did that would receive this person's
// sign-in. The unverified answer comes first, so it never tells an unverified
// login whether such an account exists.
// address alone. Linking requires a verified mailbox matching the row and
// an address the account did not set itself. Check verification first so the
// result does not tell an unverified login whether the account exists.
if (user.oidc_sub !== sub || user.oidc_issuer !== config.issuer) {
const emailVerified = userInfo.email_verified === true || userInfo.email_verified === 'true';
if (!emailVerified) {
return { error: 'email_not_verified' };
}
if (!sameMailbox(user.email, userInfo.email?.trim() ?? '')) {
logWarn(
`[OIDC] Refused to link a sign-in to user ${user.id} by email: the claimed mailbox does not match the stored mailbox.`,
);
return { error: 'email_link_blocked' };
}
if (user.email_self_asserted) {
logWarn(
`[OIDC] Refused to link a sign-in to user ${user.id} by email: the account set that address itself. An admin can confirm it by changing the email in the admin panel.`,
@@ -791,26 +796,19 @@ export class OidcService implements OnModuleDestroy {
// missing email before it ever calls this; the same code flows through its
// `oidc_error=' + result.error` pass-through if reached here.
if (!userInfo.email) return { error: 'no_email' };
const email = userInfo.email.trim().toLowerCase();
const name = this.usernameSource(userInfo) || email.split('@')[0];
const email = userInfo.email.trim();
const name = this.usernameSource(userInfo) || email.toLowerCase().split('@')[0];
const sub = userInfo.sub;
const picture = safeOidcPicture(userInfo.picture);
// Try to find existing user by sub, then by email
let user = await this.usersRepo.findByOidcIdentity(sub, config.issuer);
if (!user) {
// Never link/log-in to a guest (#1362) via its synthetic email.
// `email` is already JS-lowered above (O4 shape) — findByEmailLoweredBind
// mirrors the legacy `LOWER(email) = ?` statement exactly; do not use
// findByEmailCI here, it is AU12's `LOWER(email) = LOWER(?)` shape.
user = await this.usersRepo.findByEmailLoweredBind(email);
}
if (user) {
// The identity link, the role from the claims and the avatar are one write.
const existing = user;
return await this.uow.transactional(() => this.refreshLinkedUser(existing, sub, config, userInfo, picture));
}
const linked = await this.uow.transactional(async () => {
// The folded lookup finds candidates and blocks duplicate registration.
// Only a matching mailbox can authorize a new identity link.
const user =
(await this.usersRepo.findByOidcIdentity(sub, config.issuer)) ?? (await this.usersRepo.findByEmailCI(email));
return user ? this.refreshLinkedUser(user, sub, config, userInfo, picture) : null;
});
if (linked) return linked;
// --- New user registration ---
const userCount = await this.usersRepo.countNonGuest();