mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 17:03:15 +00:00
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:
@@ -4,7 +4,7 @@
|
||||
"src/db/repositories/Places.repository.ts": 1432,
|
||||
"src/db/repositories/Reservations.repository.ts": 1550,
|
||||
"src/db/repositories/Trips.repository.ts": 1120,
|
||||
"src/db/repositories/Users.repository.ts": 1421,
|
||||
"src/db/repositories/Users.repository.ts": 1403,
|
||||
"src/nest/atlas/atlas.service.ts": 1166,
|
||||
"src/nest/auth/auth.service.ts": 1114,
|
||||
"src/nest/budget/budget.service.ts": 1607,
|
||||
|
||||
@@ -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).
|
||||
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -349,34 +349,6 @@ describe('UsersRepository', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('findByEmailLoweredBind (O4) — OidcService.findOrCreateUser, caller already JS-lowers', () => {
|
||||
it('USERSREPO-018c: matches an already-lowered bind against a mixed-case stored email, excludes guests', async () => {
|
||||
const { user } = createUser(testDb, { email: 'Case.Test@Example.com' });
|
||||
const row = await users.findByEmailLoweredBind('case.test@example.com');
|
||||
expect(row?.id).toBe(user.id);
|
||||
expect(await users.findByEmailLoweredBind('nope@example.com')).toBeNull();
|
||||
});
|
||||
|
||||
it('USERSREPO-018d: a guest with a matching email is not returned', async () => {
|
||||
const { user } = createUser(testDb, { email: 'guest2b@example.com' });
|
||||
await updateRows(t, Users, { id: user.id }, { is_guest: 1 });
|
||||
expect(await users.findByEmailLoweredBind('guest2b@example.com')).toBeNull();
|
||||
});
|
||||
|
||||
// O4's own legacy shape: `LOWER(email) = ?` — SQLite only lowers the
|
||||
// COLUMN; the caller's already-lowered bind is compared as-is. A stored
|
||||
// non-ASCII email folds to 'josÉ@x.com' under SQLite's ASCII-only
|
||||
// LOWER(); a JS-lowered bind of the exact same spelling is
|
||||
// 'josé@x.com' — genuinely different strings, so THIS method correctly
|
||||
// does not match it. That is O4's real (pre-existing, unchanged)
|
||||
// behaviour, not a regression — findByEmailCI above is the method
|
||||
// OidcService's non-JS-lowered callers must use instead.
|
||||
it('USERSREPO-018e: a JS-lowered bind against a non-ASCII stored email does not match (this is O4 parity, not a bug)', async () => {
|
||||
createUser(testDb, { email: 'JOSÉ@x.com' });
|
||||
expect(await users.findByEmailLoweredBind('josé@x.com')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// Plan 3b Task 1 fix round item 7 — AuthService.demoLogin's exact statement
|
||||
// (`SELECT * FROM users WHERE email = ?`), missing from the inventory,
|
||||
// added now so Task 5 has it.
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { sameMailbox } from '../../../src/nest/oidc/oidc-mailbox';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('sameMailbox', () => {
|
||||
it.each([
|
||||
['Team@example.test', 'Team@example.test', true],
|
||||
['Team@example.test', 'Team@EXAMPLE.TEST', true],
|
||||
['Team@example.test', 'team@example.test', false],
|
||||
['Team@example.test', 'Team@other.test', false],
|
||||
['"team@work"@example.test', '"team@work"@EXAMPLE.TEST', true],
|
||||
['', 'Team@example.test', false],
|
||||
['Team@example.test', '', false],
|
||||
['Team@', 'Team@example.test', false],
|
||||
['Team@example.test', 'Team@', false],
|
||||
] as const)('compares %s with %s', (stored, claimed, expected) => {
|
||||
expect(sameMailbox(stored, claimed)).toBe(expected);
|
||||
});
|
||||
});
|
||||
@@ -599,13 +599,13 @@ describe('findOrCreateUser', () => {
|
||||
expect((result as { user: any }).user.id).toBe(user.id);
|
||||
});
|
||||
|
||||
it('OIDC-SVC-022: creates new user when registration is open', async () => {
|
||||
it('OIDC-SVC-022: creates a new user with the original mailbox when registration is open', async () => {
|
||||
const result = await svc.findOrCreateUser(
|
||||
{ sub: 'sub-new-1', email: 'newuser@example.com', name: 'New User' },
|
||||
{ sub: 'sub-new-1', email: 'NewUser@example.com', name: 'New User' },
|
||||
MOCK_CONFIG,
|
||||
);
|
||||
expect('user' in result).toBe(true);
|
||||
expect(await userByEmail('newuser@example.com')).not.toBeNull();
|
||||
expect(result).toMatchObject({ user: { email: 'NewUser@example.com' } });
|
||||
expect(await userByEmail('NewUser@example.com')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('OIDC-SVC-023: first user gets admin role', async () => {
|
||||
@@ -673,12 +673,12 @@ describe('findOrCreateUser', () => {
|
||||
});
|
||||
|
||||
it('OIDC-SVC-025: links oidc_sub when existing user has none (verified email)', async () => {
|
||||
const { user } = createUser(testDb, { email: 'charlie@example.com' });
|
||||
const { user } = createUser(testDb, { email: 'Charlé@example.com' });
|
||||
// Ensure no oidc_sub set
|
||||
await setUserColumns(user.id, { oidc_sub: null, oidc_issuer: null });
|
||||
|
||||
await svc.findOrCreateUser(
|
||||
{ sub: 'sub-charlie-linked', email: 'charlie@example.com', name: 'Charlie', email_verified: true },
|
||||
{ sub: 'sub-charlie-linked', email: 'Charlé@EXAMPLE.COM', name: 'Charlie', email_verified: true },
|
||||
MOCK_CONFIG,
|
||||
);
|
||||
|
||||
|
||||
+2
-1
@@ -103,10 +103,11 @@ When an SSO login matches an existing TREK account by OIDC subject (`sub`), that
|
||||
An SSO login that finds no account by its subject falls back to the email address. It links the TREK account with that address only when all of these hold:
|
||||
|
||||
- **The provider confirms the address.** `email_verified` has to be true, otherwise the login ends with `email_not_verified`.
|
||||
- **The mailbox matches.** The part before `@` must match the TREK address exactly. Capitalization of the domain does not matter.
|
||||
- **The address did not come from the account itself.** An address typed into the signup form or changed under **Settings** proves nothing about who owns it, so a login with that address ends with `email_link_blocked` and the user sees a message to ask the admin. Addresses an admin entered (an account created in **Admin → Users**, or an email changed there), the first account of the instance and accounts the provider created are linked as before.
|
||||
- **The account is not linked to another subject of the same provider.** The same issuer with another `sub` is another person at that provider, so this also ends with `email_link_blocked`. Pointing the instance at a different provider (a new issuer) still moves an account over on its first verified login there.
|
||||
|
||||
The server log says which of the two blocks a login hit. `[OIDC] Refused to link a sign-in to user <id> by email: the account set that address itself` is the second one, `… it is linked to another subject of this provider` the third.
|
||||
The server log says whether linking was blocked by a mailbox mismatch, a self-entered address, or a link to another subject at the same provider.
|
||||
|
||||
When the account is linked to another subject of the same provider and you know it is the same person (the provider was migrated or rebuilt, or it changed how it forms the `sub`), remove the stored link: in **Admin → Users**, edit the user and use **Remove SSO link**. The next SSO sign-in then links the account like a first one, under the rules above. Changing the email does not help in this case. The action is not offered for your own account and is recorded in the [Audit-Log](Audit-Log) as `admin.user_sso_unlink`. Only remove a link when you are sure: if the address now belongs to somebody else at the provider, that person receives the account.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user