mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-20 22:16:26 +00:00
fix(oidc): a sign-in links to an account by email only when the address was not set by the account itself
An SSO login that matched no account by its subject took the account with the same email address and linked the provider identity to it. That address proves nothing when the account typed it in itself: anyone could sign up with, or switch their profile to, a colleague's address and receive the colleague's first SSO login. The provider switch branch (#2110) relinked a row on any email match without even asking for email_verified, and also for another subject of the same provider. users.email_self_asserted remembers an address the account set itself: signup (not the first account) and an email change in the profile settings set it, an admin entering a new address clears it, and accounts the provider creates start without it. Existing accounts keep linking, except those whose address moved away from the registered one without an admin editing it. A login by email now needs a verified address and an unmarked account, and is refused for another subject of the same issuer, with email_link_blocked and a translated message on the login screen. An email change in the profile settings writes a user.email_change audit row. Refs #2110
This commit is contained in:
@@ -115,6 +115,7 @@ export class Users {
|
||||
airtrail_write_enabled?: number | null = 0;
|
||||
display_name?: string | null;
|
||||
immich_allow_insecure_tls: number & Opt = 0;
|
||||
email_self_asserted: number & Opt = 0;
|
||||
assignment_participants_collection = new Collection<AssignmentParticipants>(this);
|
||||
audit_log_collection = new Collection<AuditLog>(this);
|
||||
bucket_list_collection = new Collection<BucketList>(this);
|
||||
@@ -255,6 +256,7 @@ export const UsersSchema = defineEntity({
|
||||
airtrail_write_enabled: p.integer().nullable(),
|
||||
display_name: p.text().nullable(),
|
||||
immich_allow_insecure_tls: p.integer().default(0),
|
||||
email_self_asserted: p.integer().default(0),
|
||||
assignment_participants_collection: () => p.oneToMany(AssignmentParticipants).mappedBy('user').hidden(),
|
||||
audit_log_collection: () => p.oneToMany(AuditLog).mappedBy('user').hidden(),
|
||||
bucket_list_collection: () => p.oneToMany(BucketList).mappedBy('user').hidden(),
|
||||
|
||||
@@ -43,4 +43,5 @@ export interface UsersTable {
|
||||
airtrail_write_enabled: InsertOptional<number | null>;
|
||||
display_name: InsertOptional<string | null>;
|
||||
immich_allow_insecure_tls: InsertOptional<number>;
|
||||
email_self_asserted: InsertOptional<number>;
|
||||
}
|
||||
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
import { addColumnIfMissing } from '../migration-utils';
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
interface UserEmailRow {
|
||||
id: number;
|
||||
email: string;
|
||||
}
|
||||
|
||||
interface AuditRow {
|
||||
user_id: number | null;
|
||||
resource: string | null;
|
||||
details: string | null;
|
||||
}
|
||||
|
||||
/** The parsed `details` of an audit row, or null for an empty or broken one. */
|
||||
function detailsOf(row: AuditRow): Record<string, unknown> | null {
|
||||
if (!row.details) return null;
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(row.details);
|
||||
return parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers whether an account's email address is one the account typed in
|
||||
* itself.
|
||||
*
|
||||
* An SSO sign-in that matches no linked account falls back to the email
|
||||
* address and links the provider identity to whichever account holds it. That
|
||||
* address proves nothing when the account chose it at signup or in its profile
|
||||
* settings: anyone could put a colleague's address on their own account and
|
||||
* receive the colleague's first SSO sign-in. `email_self_asserted` is 1 for
|
||||
* such an address and keeps the sign-in from linking to it; an address an admin
|
||||
* set, or one the provider created the account with, stays 0.
|
||||
*
|
||||
* Existing accounts start at 0, so instances keep linking the way they did.
|
||||
* The exception is an account whose address provably moved away from the one
|
||||
* it registered with (its `user.register` audit row) without an admin ever
|
||||
* editing its email (an `admin.user_update` row naming `email`): only the
|
||||
* account itself can have changed it. The audit details are JSON text, read
|
||||
* and compared here rather than in SQL.
|
||||
*/
|
||||
export class Migration20200101042800_an_email_the_account_typed_in_itself extends Migration {
|
||||
override name = 'Migration20200101042800_an_email_the_account_typed_in_itself';
|
||||
|
||||
override async up(): Promise<void> {
|
||||
await addColumnIfMissing(this, 'users', 'email_self_asserted', 'email_self_asserted INTEGER NOT NULL DEFAULT 0');
|
||||
|
||||
const registrations = (await this.execute(
|
||||
`SELECT user_id, resource, details FROM audit_log WHERE action = 'user.register' AND user_id IS NOT NULL`,
|
||||
)) as AuditRow[];
|
||||
if (registrations.length === 0) return;
|
||||
|
||||
const registeredWith = new Map<number, string[]>();
|
||||
for (const row of registrations) {
|
||||
const email = detailsOf(row)?.email;
|
||||
if (typeof email !== 'string' || row.user_id === null) continue;
|
||||
registeredWith.set(row.user_id, [...(registeredWith.get(row.user_id) ?? []), email.trim().toLowerCase()]);
|
||||
}
|
||||
|
||||
const adminEdits = (await this.execute(
|
||||
`SELECT user_id, resource, details FROM audit_log WHERE action = 'admin.user_update'`,
|
||||
)) as AuditRow[];
|
||||
const editedByAdmin = new Set<string>();
|
||||
for (const row of adminEdits) {
|
||||
const fields = detailsOf(row)?.fields;
|
||||
if (row.resource && Array.isArray(fields) && fields.includes('email')) editedByAdmin.add(row.resource);
|
||||
}
|
||||
|
||||
const users = (await this.execute(`SELECT id, email FROM users WHERE COALESCE(is_guest, 0) = 0`)) as UserEmailRow[];
|
||||
for (const user of users) {
|
||||
const registered = registeredWith.get(user.id);
|
||||
if (!registered || editedByAdmin.has(String(user.id))) continue;
|
||||
if (registered.includes(user.email.trim().toLowerCase())) continue;
|
||||
await this.execute('UPDATE users SET email_self_asserted = 1 WHERE id = ?', [user.id]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,7 @@ export interface UserRow {
|
||||
airtrail_write_enabled: number | null;
|
||||
display_name: string | null;
|
||||
immich_allow_insecure_tls: number;
|
||||
email_self_asserted: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -85,6 +86,8 @@ export interface NewUserRow {
|
||||
oidc_sub?: string | null;
|
||||
oidc_issuer?: string | null;
|
||||
avatar?: string | null;
|
||||
/** 1 for an address typed into the signup form (nobody vouches for it), 0 for the first account and SSO ones. */
|
||||
email_self_asserted?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -119,6 +122,7 @@ export interface UserProfilePatch {
|
||||
amap_api_key?: string | null;
|
||||
username?: string;
|
||||
email?: string;
|
||||
email_self_asserted?: number;
|
||||
}
|
||||
|
||||
/** `UserProfileService.getApiKeyColumns`/`currentKeys` (UP1). */
|
||||
@@ -280,6 +284,7 @@ export interface AdminEditPatch {
|
||||
role?: string;
|
||||
password_hash?: string;
|
||||
password_version?: number;
|
||||
email_self_asserted?: number;
|
||||
}
|
||||
|
||||
export class UsersRepository extends TrekRepository<Users> {
|
||||
@@ -474,6 +479,7 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
oidc_sub: row.oidc_sub ?? null,
|
||||
oidc_issuer: row.oidc_issuer ?? null,
|
||||
avatar: row.avatar ?? null,
|
||||
email_self_asserted: row.email_self_asserted ?? 0,
|
||||
}),
|
||||
);
|
||||
const inserted = await this.findById(id);
|
||||
@@ -990,17 +996,10 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `` UPDATE users SET ${updates.join(', ')}, updated_at = CURRENT_TIMESTAMP
|
||||
* WHERE id = ? `` — the SET clause is built at the CALL SITE from a fixed
|
||||
* set of 6 possible literal column names, never here: `patchProfile` takes
|
||||
* only the already-decided final columns as a typed partial and writes
|
||||
* them in ONE `nativeUpdate` (never `assign`+`flush`, which would be a
|
||||
* second statement shape for the identical intent) — the entity-API
|
||||
* equivalent of the legacy's dynamic `SET` list, without ever building SQL
|
||||
* text. `updated_at` is always stamped, matching the legacy: this method's
|
||||
* only caller (`UserProfileService.updateSettings`) calls it only when at
|
||||
* least one field changed (`updates.length > 0`), the same guard the
|
||||
* legacy statement was built under.
|
||||
* `` UPDATE users SET ${updates.join(', ')}, updated_at = CURRENT_TIMESTAMP WHERE id = ? ``: the
|
||||
* caller decides the columns of {@link UserProfilePatch}, this writes them in ONE `nativeUpdate`
|
||||
* (never `assign`+`flush`) and never builds SQL text. `updated_at` is always stamped, as in the
|
||||
* legacy; the only caller (`UserProfileService.updateSettings`) calls it only when a field changed.
|
||||
*/
|
||||
async patchProfile(id: number, changes: UserProfilePatch): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
|
||||
@@ -271,6 +271,10 @@ export class AdminService {
|
||||
const patch: AdminEditPatch = {};
|
||||
if (username) patch.username = username;
|
||||
if (email) patch.email = email;
|
||||
// An address the admin enters is one the admin vouches for, so an SSO sign-in
|
||||
// may link to it again. The edit dialog sends the email on every save, so only
|
||||
// a new address counts, not the unchanged one or the same one in another case.
|
||||
if (email && email.toLowerCase() !== user.email.toLowerCase()) patch.email_self_asserted = 0;
|
||||
if (role) patch.role = role;
|
||||
if (password) {
|
||||
patch.password_hash = passwordHash!;
|
||||
|
||||
@@ -15,6 +15,7 @@ const ACTION_LABELS: Record<string, string> = {
|
||||
'user.account_delete': 'deleted account',
|
||||
'user.mfa_enable': 'enabled MFA',
|
||||
'user.mfa_disable': 'disabled MFA',
|
||||
'user.email_change': 'changed email',
|
||||
'user.session_revoke': 'signed out a session',
|
||||
'user.sessions_revoke_others': 'signed out other sessions',
|
||||
'settings.app_update': 'updated settings',
|
||||
|
||||
@@ -196,6 +196,11 @@ export class AuthController {
|
||||
async updateSettings(@CurrentUser() user: User, @Body() body: SettingsUpdateDto, @Req() req: Request) {
|
||||
const result = await this.profile.updateSettings(user.id, body);
|
||||
await this.auditApiKeys(user.id, result.changedKeys ?? [], req);
|
||||
// The address itself stays out of the row, like the key values above; the row
|
||||
// is what tells an admin later that the account chose its current address.
|
||||
if (result.emailChanged) {
|
||||
await this.audit.writeAudit({ userId: user.id, action: 'user.email_change', ip: getClientIp(req) });
|
||||
}
|
||||
return { success: result.success, user: result.user };
|
||||
}
|
||||
|
||||
|
||||
@@ -468,10 +468,9 @@ export class AuthService {
|
||||
const password_hash = bcrypt.hashSync(password, BCRYPT_COST);
|
||||
|
||||
try {
|
||||
// One transaction for the whole signup: a mid-sequence throw (invite
|
||||
// bookkeeping, trip auto-join) must not leave a half-registered user.
|
||||
// The collision check and the first-user count run inside it too, so two
|
||||
// signups at once cannot both pass the check or both become admin.
|
||||
// One transaction for the whole signup: a mid-sequence throw (invite bookkeeping, trip auto-join)
|
||||
// must not leave a half-registered user. The collision check and the first-user count run inside
|
||||
// it too, so two signups at once cannot both pass the check or both become admin.
|
||||
return await this.uow.transactional(async () => {
|
||||
// Ignore guests (#1362): their synthetic username/email must never block a real signup.
|
||||
const existingUserId = await this.usersRepo.findIdByEmailOrUsernameCI(email, username);
|
||||
@@ -482,6 +481,7 @@ export class AuthService {
|
||||
const role = isFirstUser ? 'admin' : 'user';
|
||||
const inserted = await this.usersRepo.insertUser({
|
||||
username, email, password_hash, role, first_seen_version: readEnv().app.appVersion || '0.0.0',
|
||||
email_self_asserted: isFirstUser ? 0 : 1,
|
||||
});
|
||||
|
||||
const user = { id: inserted.id, username, email, role, avatar: null, mfa_enabled: false };
|
||||
|
||||
@@ -210,7 +210,7 @@ export class UserProfileService {
|
||||
async updateSettings(
|
||||
userId: number,
|
||||
rawBody: unknown,
|
||||
): Promise<{ success?: boolean; user?: Record<string, unknown>; changedKeys?: string[] }> {
|
||||
): Promise<{ success?: boolean; user?: Record<string, unknown>; changedKeys?: string[]; emailChanged?: boolean }> {
|
||||
const body = rawBody as {
|
||||
maps_api_key?: string;
|
||||
openweather_api_key?: string;
|
||||
@@ -261,6 +261,14 @@ export class UserProfileService {
|
||||
if (username !== undefined) changes.username = username.trim();
|
||||
if (email !== undefined) changes.email = email.trim();
|
||||
|
||||
// A new address typed in here is the account's own word for it, so an SSO
|
||||
// sign-in no longer links to it by email (see OidcService.refreshLinkedUser).
|
||||
// Changing only the case keeps the address and its standing.
|
||||
const previousEmail = changes.email !== undefined ? await this.usersRepo.getEmail(userId) : null;
|
||||
const emailChanged =
|
||||
changes.email !== undefined && changes.email.toLowerCase() !== (previousEmail ?? '').toLowerCase();
|
||||
if (emailChanged) changes.email_self_asserted = 1;
|
||||
|
||||
// Read before the write, so the comparison sees the old value; the role in
|
||||
// the same row decides whether the two instance-wide names travel with it.
|
||||
const current = await this.currentKeys(userId);
|
||||
@@ -297,6 +305,7 @@ export class UserProfileService {
|
||||
avatar_url: avatarUrl(updated || {}),
|
||||
},
|
||||
changedKeys,
|
||||
emailChanged,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -665,21 +665,35 @@ export class OidcService implements OnModuleDestroy {
|
||||
userInfo: OidcUserInfo,
|
||||
picture: string | null,
|
||||
): Promise<{ user: User; roleChange?: OidcRoleChange } | { error: string }> {
|
||||
// Reaching here without an oidc_sub means we matched an existing local
|
||||
// account by email. Only auto-link the OIDC identity when the IdP asserts
|
||||
// the email is verified; an unverified email must not auto-link.
|
||||
if (!user.oidc_sub) {
|
||||
// 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.
|
||||
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' };
|
||||
}
|
||||
await this.usersRepo.linkOidcIdentity(user.id, sub, config.issuer);
|
||||
user = { ...user, oidc_sub: sub, oidc_issuer: config.issuer };
|
||||
} else if (user.oidc_issuer !== config.issuer || user.oidc_sub !== sub) {
|
||||
// The admin pointed the instance at a different IdP. We got here through the
|
||||
// verified-email lookup, so this is the same person arriving from the new
|
||||
// provider; leaving the old sub and issuer on the row would keep the account
|
||||
// pinned to a provider that no longer exists (#2110).
|
||||
if (user.email_self_asserted) {
|
||||
console.warn(
|
||||
`[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.`,
|
||||
);
|
||||
return { error: 'email_link_blocked' };
|
||||
}
|
||||
// The same provider with another subject is another person at that
|
||||
// provider, never this account under a new name.
|
||||
if (user.oidc_sub && user.oidc_issuer === config.issuer) {
|
||||
console.warn(
|
||||
`[OIDC] Refused to link a sign-in to user ${user.id} by email: it is linked to another subject of this provider.`,
|
||||
);
|
||||
return { error: 'email_link_blocked' };
|
||||
}
|
||||
// Without an oidc_sub this is the account's first SSO sign-in. With one from
|
||||
// another issuer, the admin pointed the instance at a different IdP: leaving
|
||||
// the old sub and issuer on the row would keep the account pinned to a
|
||||
// provider that no longer exists (#2110).
|
||||
await this.usersRepo.linkOidcIdentity(user.id, sub, config.issuer);
|
||||
user = { ...user, oidc_sub: sub, oidc_issuer: config.issuer };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user