mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(admin): remove the SSO link of an account whose provider changed its subject
A sign-in with another subject of the same provider is refused, so an account whose provider re-issued the subject (a migrated or rebuilt IdP, a changed sub format) was locked out: editing the email, as the wiki advised, never touched the stored link. The edit dialog now offers "Remove SSO link" for other accounts while SSO is set up (DELETE /api/admin/users/:id/sso, audit admin.user_sso_unlink). The next SSO sign-in links again under the rules of a first one, so it still needs a verified, not self-set email. The log line names the remedy, and the wiki tells the two refusals apart. Fixes #3065
This commit is contained in:
@@ -823,6 +823,14 @@ export class UsersRepository extends TrekRepository<Users> {
|
||||
await this.nativeUpdate({ id }, { oidc_sub: sub, oidc_issuer: issuer });
|
||||
}
|
||||
|
||||
/**
|
||||
* `UPDATE users SET oidc_sub = NULL, oidc_issuer = NULL WHERE id = ?`: the
|
||||
* admin's "Remove SSO link" (#3065). No `updated_at`, like the link it undoes.
|
||||
*/
|
||||
async clearOidcIdentity(id: number): Promise<void> {
|
||||
await this.nativeUpdate({ id }, { oidc_sub: null, oidc_issuer: null });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// O8 — claims-based role change
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
@@ -156,6 +156,22 @@ export class AdminController {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Delete('users/:id/sso')
|
||||
async unlinkUserSso(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
|
||||
const result = await this.admin.unlinkUserSso(id, user.id);
|
||||
if (result.unlinked) {
|
||||
await this.audit.writeAudit({
|
||||
userId: user.id,
|
||||
action: 'admin.user_sso_unlink',
|
||||
resource: String(id),
|
||||
ip: getClientIp(req),
|
||||
details: { targetUser: result.email },
|
||||
});
|
||||
logInfo(`Admin ${user.email} removed the SSO link of user ${result.email}`);
|
||||
}
|
||||
return { success: true, unlinked: result.unlinked };
|
||||
}
|
||||
|
||||
// ── Stats / permissions / audit ──
|
||||
@Get('stats')
|
||||
stats() {
|
||||
|
||||
@@ -398,6 +398,35 @@ export class AdminService {
|
||||
return { success: true, email: target.email };
|
||||
}
|
||||
|
||||
/**
|
||||
* Forget the SSO identity stored on another account (#3065).
|
||||
*
|
||||
* A sign-in that arrives with a different subject of the same provider is
|
||||
* refused, because that is another person at the provider as far as TREK can
|
||||
* tell. When the provider itself re-issued the subject (a migrated or rebuilt
|
||||
* IdP, a changed `sub` format), the account owner is locked out and editing the
|
||||
* email does not help. Clearing the link hands the decision to the admin: the
|
||||
* next SSO sign-in links again under the same rules as a first one, so it still
|
||||
* needs a verified email and an address the account did not set itself.
|
||||
*
|
||||
* Never for the caller themselves, for the same reason as resetUserMfa: a
|
||||
* stolen admin session must not be able to loosen the login of the account it
|
||||
* came from.
|
||||
*/
|
||||
async unlinkUserSso(id: string, actingUserId: number): Promise<{ email: string; unlinked: boolean }> {
|
||||
const targetId = Number(id);
|
||||
// SECURITY: plain JS comparison, kept here like resetUserMfa's (R4).
|
||||
if (targetId === actingUserId) {
|
||||
throw new DomainError(400, 'You cannot remove the SSO link of your own account');
|
||||
}
|
||||
const target = await this.users.findById(targetId);
|
||||
if (!target || target.is_guest) throw new DomainError(404, 'User not found');
|
||||
if (!target.oidc_sub && !target.oidc_issuer) return { email: target.email, unlinked: false };
|
||||
|
||||
await this.users.clearOidcIdentity(targetId);
|
||||
return { email: target.email, unlinked: true };
|
||||
}
|
||||
|
||||
// ── Stats ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async getStats() {
|
||||
|
||||
@@ -686,7 +686,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
// provider, never this account under a new name.
|
||||
if (user.oidc_sub && user.oidc_issuer === config.issuer) {
|
||||
logWarn(
|
||||
`[OIDC] Refused to link a sign-in to user ${user.id} by email: it is linked to another subject of this provider.`,
|
||||
`[OIDC] Refused to link a sign-in to user ${user.id} by email: it is linked to another subject of this provider. If the provider changed the subject of the same person, an admin can remove the SSO link of this user in the admin panel.`,
|
||||
);
|
||||
return { error: 'email_link_blocked' };
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import { NotificationsModule } from '../../src/nest/notifications/notifications.
|
||||
import { OidcModule } from '../../src/nest/oidc/oidc.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { SettingsModule } from '../../src/nest/settings/settings.module';
|
||||
import { countRows, findRow, insertRow } from '../helpers/factories/rows';
|
||||
import { countRows, findRow, insertRow, updateRows } from '../helpers/factories/rows';
|
||||
import { readAppSetting } from '../helpers/factories/settings';
|
||||
import { makeTrip } from '../helpers/factories/trips';
|
||||
import { makeAdmin, makeUser } from '../helpers/factories/users';
|
||||
@@ -262,6 +262,27 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('DELETE /users/:id/sso clears the stored SSO identity, audits it, and is admin-only (#3065)', async () => {
|
||||
const { user } = await makeUser(orm, { email: 'sso-moved@example.test', username: 'sso-moved' });
|
||||
await updateRows(orm, Users, { id: user.id }, { oidc_sub: 'sub-old', oidc_issuer: 'https://idp.example.test' });
|
||||
|
||||
const denied = await request(server).delete(`/api/admin/users/${user.id}/sso`).set('Cookie', sessionCookie(2));
|
||||
expect(denied.status).toBe(403);
|
||||
|
||||
const res = await request(server).delete(`/api/admin/users/${user.id}/sso`).set('Cookie', sessionCookie(1));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ success: true, unlinked: true });
|
||||
const row = await findRow(orm, Users, { id: user.id });
|
||||
expect(row && { oidc_sub: row.oidc_sub ?? null, oidc_issuer: row.oidc_issuer ?? null }).toEqual({
|
||||
oidc_sub: null,
|
||||
oidc_issuer: null,
|
||||
});
|
||||
expect(await findRow(orm, AuditLog, { action: 'admin.user_sso_unlink', resource: String(user.id) })).not.toBeNull();
|
||||
|
||||
const self = await request(server).delete('/api/admin/users/1/sso').set('Cookie', sessionCookie(1));
|
||||
expect(self.status).toBe(400);
|
||||
});
|
||||
|
||||
it('404 on the dev-only test-notification outside development', async () => {
|
||||
const res = await request(server).post('/api/admin/dev/test-notification').set('Cookie', sessionCookie(1)).send({});
|
||||
expect(res.status).toBe(404);
|
||||
|
||||
@@ -669,6 +669,25 @@ describe('UsersRepository', () => {
|
||||
expect(row.updated_at).toBe('2020-01-01 00:00:00');
|
||||
});
|
||||
|
||||
it('USERSREPO-088: clearOidcIdentity nulls sub+issuer WITHOUT touching updated_at (#3065)', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await updateRows(
|
||||
t,
|
||||
Users,
|
||||
{ id: user.id },
|
||||
{ oidc_sub: 'sub-1', oidc_issuer: 'https://idp.example.com', updated_at: '2020-01-01 00:00:00' },
|
||||
);
|
||||
await users.clearOidcIdentity(user.id);
|
||||
const row = (await findRow(t, Users, { id: user.id })) as {
|
||||
oidc_sub: string | null;
|
||||
oidc_issuer: string | null;
|
||||
updated_at: string;
|
||||
};
|
||||
expect(row.oidc_sub).toBeNull();
|
||||
expect(row.oidc_issuer).toBeNull();
|
||||
expect(row.updated_at).toBe('2020-01-01 00:00:00');
|
||||
});
|
||||
|
||||
it('USERSREPO-042: setRole (O8) writes role WITHOUT touching updated_at', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
await updateRows(t, Users, { id: user.id }, { updated_at: '2020-01-01 00:00:00' });
|
||||
|
||||
@@ -357,6 +357,42 @@ describe('AdminController addons + sessions + jwt + defaults', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('AdminController SSO unlink (#3065)', () => {
|
||||
it('ADMIN-CTRL-SSO-001: audits a removed link and answers unlinked: true', async () => {
|
||||
writeAudit.mockClear();
|
||||
const unlinkUserSso = vi.fn().mockResolvedValue({ email: 'a@b.c', unlinked: true });
|
||||
expect(await adminCtl(svc({ unlinkUserSso } as Partial<AdminService>)).unlinkUserSso(user, '4', req)).toEqual({
|
||||
success: true,
|
||||
unlinked: true,
|
||||
});
|
||||
expect(unlinkUserSso).toHaveBeenCalledWith('4', user.id);
|
||||
expect(writeAudit).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ action: 'admin.user_sso_unlink', resource: '4', details: { targetUser: 'a@b.c' } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('ADMIN-CTRL-SSO-002: writes no audit row when there was no link, and maps the self refusal', async () => {
|
||||
writeAudit.mockClear();
|
||||
expect(
|
||||
await adminCtl(
|
||||
svc({ unlinkUserSso: vi.fn().mockResolvedValue({ email: 'a@b.c', unlinked: false }) } as Partial<AdminService>),
|
||||
).unlinkUserSso(user, '4', req),
|
||||
).toEqual({ success: true, unlinked: false });
|
||||
expect(writeAudit).not.toHaveBeenCalled();
|
||||
expect(
|
||||
await thrown(() =>
|
||||
adminCtl(
|
||||
svc({
|
||||
unlinkUserSso: vi
|
||||
.fn()
|
||||
.mockRejectedValue(new DomainError(400, 'You cannot remove the SSO link of your own account')),
|
||||
} as Partial<AdminService>),
|
||||
).unlinkUserSso(user, '1', req),
|
||||
),
|
||||
).toEqual({ status: 400, body: { error: 'You cannot remove the SSO link of your own account' } });
|
||||
});
|
||||
});
|
||||
|
||||
describe('AdminController read-only getters', () => {
|
||||
it('return service values verbatim', async () => {
|
||||
expect(
|
||||
|
||||
@@ -998,6 +998,61 @@ describe('resetUserMfa', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// #3065: the provider re-issued a user's subject, so every sign-in hits
|
||||
// "linked to another subject of this provider" and editing the email cannot help.
|
||||
describe('unlinkUserSso', () => {
|
||||
it('ADMIN-SVC-097 — clears sub and issuer so the next SSO sign-in links like a first one', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
await updateRows(orm, Users, { id: user.id }, { oidc_sub: 'sub-old', oidc_issuer: 'https://idp.example.com' });
|
||||
|
||||
const result = await svc.unlinkUserSso(String(user.id), admin.user.id);
|
||||
|
||||
expect(result).toEqual({ email: user.email, unlinked: true });
|
||||
const row = await readUser(orm, user.id);
|
||||
expect({ oidc_sub: row.oidc_sub, oidc_issuer: row.oidc_issuer }).toEqual({ oidc_sub: null, oidc_issuer: null });
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-098 — an account without an SSO link answers unlinked: false and stays as it is', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
const { user } = createUser(testDb);
|
||||
|
||||
expect(await svc.unlinkUserSso(String(user.id), admin.user.id)).toEqual({ email: user.email, unlinked: false });
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-099 — refuses the callers own account and keeps its link', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
await updateRows(
|
||||
orm,
|
||||
Users,
|
||||
{ id: admin.user.id },
|
||||
{ oidc_sub: 'sub-admin', oidc_issuer: 'https://idp.example.com' },
|
||||
);
|
||||
|
||||
const result = (await asLegacyResult(svc.unlinkUserSso(String(admin.user.id), admin.user.id))) as {
|
||||
error?: string;
|
||||
status?: number;
|
||||
};
|
||||
|
||||
expect(result.status).toBe(400);
|
||||
expect(result.error).toMatch(/your own/i);
|
||||
expect((await readUser(orm, admin.user.id)).oidc_sub).toBe('sub-admin');
|
||||
});
|
||||
|
||||
it('ADMIN-SVC-100 — 404 for a user that is not there, and for a guest', async () => {
|
||||
const admin = createAdmin(testDb);
|
||||
const { user: guest } = createUser(testDb);
|
||||
await updateRows(orm, Users, { id: guest.id }, { is_guest: 1 });
|
||||
|
||||
expect((await asLegacyResult(svc.unlinkUserSso('99999', admin.user.id))) as { status?: number }).toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
expect(
|
||||
(await asLegacyResult(svc.unlinkUserSso(String(guest.id), admin.user.id))) as { status?: number },
|
||||
).toMatchObject({ status: 404 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkVersion on a centrally administered install', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs();
|
||||
|
||||
Reference in New Issue
Block a user