Give three more admin surfaces back to the domains that own them

default-user-settings, notification-preferences and oidc leave AdminController.
The first two were pure pass-throughs on AdminService that did nothing but
forward and cast; the third had its SQL there for a domain that already had a
module of its own. AdminService loses SettingsService and
NotificationPreferencesService entirely.

Two things came out of the move rather than going into it.

The OIDC lockout guard now has tests. It refuses to clear the SSO config while
password login is disabled — otherwise the instance has no SSO to log in through
and no password form either — and nothing covered that branch before, because it
sat among admin tests that only exercised the happy path.

The admin e2e app had to learn about the split. It assembles AdminModule alone,
so the moved routes 404'd there while working in production; it now imports the
three domains too. That is the same failure mode the module-provider guards
catch for RPC classes, and it is worth knowing that an e2e app which builds a
subset will find it first.

Also fixes the audit route note: audit-log stays on AdminController on purpose.
AuthModule imports AuditModule, so an admin-gated controller in AuditModule
closes a cycle — the same trap the addons toggles hit.
This commit is contained in:
Maurice
2026-08-09 20:54:13 +02:00
committed by Maurice
parent d4a1601855
commit 8a09f55571
17 changed files with 393 additions and 179 deletions
+7 -1
View File
@@ -85,6 +85,12 @@ vi.mock('../../src/nest/notifications/notification-preferences.service', async (
vi.mock('../../src/nest/notifications/notifications.bridge', () => ({ send: vi.fn().mockResolvedValue(undefined) }));
import { AdminModule } from '../../src/nest/admin/admin.module';
// The admin surface is no longer one module: oidc, the account defaults and the admin
// preference matrix moved to the domains that own them, so the app has to assemble
// them too or those routes 404 here while working in production.
import { OidcModule } from '../../src/nest/oidc/oidc.module';
import { SettingsModule } from '../../src/nest/settings/settings.module';
import { NotificationsModule } from '../../src/nest/notifications/notifications.module';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
@@ -93,7 +99,7 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, RealtimeModule, AdminModule] }).compile();
const moduleRef = await Test.createTestingModule({ imports: [DatabaseModule, RealtimeModule, AdminModule, OidcModule, SettingsModule, NotificationsModule] }).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
// Mirror the production APP_PIPE (app.module.ts): DTO-typed bodies validate
@@ -0,0 +1,82 @@
/**
* The account defaults, after the two routes moved off AdminController next to
* SettingsService, which owns them. Same path, same audit action, same 400 envelope on
* a rejected write — these cases came over with the routes.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { HttpException } from '@nestjs/common';
import { AdminDefaultUserSettingsController } from '../../../src/nest/settings/settings.controller';
import { SettingsModule } from '../../../src/nest/settings/settings.module';
import type { SettingsService } from '../../../src/nest/settings/settings.service';
import type { AuditService } from '../../../src/nest/audit/audit.service';
import type { User } from '../../../src/types';
import { expectRegisteredController } from '../../helpers/module-providers';
const user = { id: 1, role: 'admin' } as User;
const req = { headers: {}, socket: {} } as never;
const writeAudit = vi.fn();
function controller(over: Partial<SettingsService> = {}) {
const settings = {
getAdminUserDefaults: vi.fn(() => ({ theme: 'dark' })),
setAdminUserDefaults: vi.fn(),
...over,
} as unknown as SettingsService;
return { c: new AdminDefaultUserSettingsController(settings, { writeAudit } as unknown as AuditService), settings };
}
const thrown = (run: () => unknown) => {
try {
run();
return null;
} catch (e) {
return e instanceof HttpException ? { status: e.getStatus(), body: e.getResponse() } : e;
}
};
describe('AdminDefaultUserSettingsController', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('DEFAULTS-001 GET returns the stored defaults verbatim', () => {
expect(controller().c.get()).toEqual({ theme: 'dark' });
});
it('DEFAULTS-002 PUT writes, audits, and answers with the STORED defaults', () => {
const { c, settings } = controller();
// Not the request body: the service normalises and drops unknown keys, and the
// admin panel renders straight from this response.
expect(c.update(user, { theme: 'light' } as never, req)).toEqual({ theme: 'dark' });
expect(settings.setAdminUserDefaults).toHaveBeenCalledWith({ theme: 'light' });
expect(writeAudit).toHaveBeenCalledWith(
expect.objectContaining({ userId: 1, action: 'admin.default_user_settings_update', details: { theme: 'light' } }),
);
});
it('DEFAULTS-003 a rejected write is a 400 carrying the message, and is not audited', () => {
const { c } = controller({
setAdminUserDefaults: vi.fn(() => {
throw new Error('unknown setting: nope');
}),
} as Partial<SettingsService>);
expect(thrown(() => c.update(user, { nope: 1 } as never, req))).toEqual({
status: 400,
body: { error: 'unknown setting: nope' },
});
expect(writeAudit).not.toHaveBeenCalled();
});
it('DEFAULTS-004 a non-Error throw is stringified rather than swallowed', () => {
const { c } = controller({
setAdminUserDefaults: vi.fn(() => {
throw 'plain string';
}),
} as Partial<SettingsService>);
expect(thrown(() => c.update(user, {} as never, req))).toEqual({ status: 400, body: { error: 'plain string' } });
});
it('DEFAULTS-005 the class is listed in its module controllers', () => {
expectRegisteredController(SettingsModule, AdminDefaultUserSettingsController);
});
});
@@ -0,0 +1,52 @@
/**
* The admin-scope preference matrix, after the two routes moved off AdminController
* next to NotificationPreferencesService, which owns it. The 'admin' scope argument
* they always passed is now written once, at the only place that uses it.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { AdminNotificationPreferencesController } from '../../../src/nest/notifications/notifications.controller';
import { NotificationsModule } from '../../../src/nest/notifications/notifications.module';
import type { NotificationPreferencesService } from '../../../src/nest/notifications/notification-preferences.service';
import type { User } from '../../../src/types';
import { expectRegisteredController } from '../../helpers/module-providers';
const admin = { id: 1, role: 'admin' } as User;
function controller() {
const prefs = {
getPreferencesMatrix: vi.fn(() => ({ rows: [{ event: 'trip_reminder' }] })),
setAdminPreferences: vi.fn(),
} as unknown as NotificationPreferencesService;
return { c: new AdminNotificationPreferencesController(prefs), prefs };
}
describe('AdminNotificationPreferencesController', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('ADMINPREF-001 GET asks for the admin scope, not the user one', () => {
const { c, prefs } = controller();
expect(c.get(admin)).toEqual({ rows: [{ event: 'trip_reminder' }] });
expect(prefs.getPreferencesMatrix).toHaveBeenCalledWith(1, 'admin', 'admin');
});
it('ADMINPREF-002 PUT persists, then answers with the REFRESHED matrix', () => {
const { c, prefs } = controller();
// The admin panel renders straight from this response, so returning the write
// result instead of a fresh read would leave it showing stale rows.
expect(c.set(admin, { trip_reminder: { email: true } } as never)).toEqual({ rows: [{ event: 'trip_reminder' }] });
expect(prefs.setAdminPreferences).toHaveBeenCalledWith(1, { trip_reminder: { email: true } });
expect(prefs.getPreferencesMatrix).toHaveBeenCalledWith(1, 'admin', 'admin');
});
it('ADMINPREF-003 the acting user drives the lookup, never a body field', () => {
const { c, prefs } = controller();
c.get({ id: 7, role: 'admin' } as User);
expect(prefs.getPreferencesMatrix).toHaveBeenCalledWith(7, 'admin', 'admin');
});
it('ADMINPREF-004 the class is listed in its module controllers', () => {
expectRegisteredController(NotificationsModule, AdminNotificationPreferencesController);
});
});
@@ -84,10 +84,6 @@ describe('AdminController permissions + oidc + misc', () => {
expect(c.savePermissions(user, { permissions: {} }, req)).toEqual({ success: true, permissions: {}, skipped: ['bad'] });
});
it('oidc update maps error, else audits', () => {
expect(thrown(() => adminCtl(svc({ updateOidcSettings: vi.fn().mockReturnValue({ error: 'bad issuer', status: 400 }) } as Partial<AdminService>)).updateOidc(user, {}, req))).toEqual({ status: 400, body: { error: 'bad issuer' } });
expect(adminCtl(svc({ updateOidcSettings: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).updateOidc(user, { issuer: 'https://idp' }, req)).toEqual({ success: true });
});
it('save-demo-baseline maps error, else returns message', () => {
expect(thrown(() => adminCtl(svc({ saveDemoBaseline: vi.fn().mockReturnValue({ error: 'not demo', status: 400 }) } as Partial<AdminService>)).saveDemoBaseline(user, req))).toEqual({ status: 400, body: { error: 'not demo' } });
@@ -138,12 +134,6 @@ describe('AdminController addons + sessions + jwt + defaults', () => {
expect(adminCtl(svc({ rotateJwtSecret: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).rotateJwtSecret(user, req)).toEqual({ success: true });
});
it('default-user-settings: sets + audits', () => {
const setAdminUserDefaults = vi.fn();
const c = adminCtl(svc({ setAdminUserDefaults, getAdminUserDefaults: vi.fn().mockReturnValue({ theme: 'dark' }) } as Partial<AdminService>));
expect(c.setDefaultUserSettings(user, { theme: 'dark' }, req)).toEqual({ theme: 'dark' });
expect(setAdminUserDefaults).toHaveBeenCalled();
});
});
describe('AdminController error envelope fallbacks', () => {
@@ -151,14 +141,7 @@ describe('AdminController error envelope fallbacks', () => {
expect(thrown(() => adminCtl(svc({ createUser: vi.fn().mockReturnValue({ error: 'boom' }) } as Partial<AdminService>)).createUser(user, {}, req))).toEqual({ status: 400, body: { error: 'boom' } });
});
it('updateOidc defaults to 400 when the service error omits a status', () => {
expect(thrown(() => adminCtl(svc({ updateOidcSettings: vi.fn().mockReturnValue({ error: 'nope' }) } as Partial<AdminService>)).updateOidc(user, {}, req))).toEqual({ status: 400, body: { error: 'nope' } });
});
it('updateOidc audits issuer_set=false when no issuer is supplied', () => {
expect(adminCtl(svc({ updateOidcSettings: vi.fn().mockReturnValue({}) } as Partial<AdminService>)).updateOidc(user, {}, req)).toEqual({ success: true });
expect(writeAudit).toHaveBeenCalledWith(expect.objectContaining({ action: 'admin.oidc_update', details: { issuer_set: false } }));
});
});
describe('AdminController read-only getters', () => {
@@ -167,22 +150,13 @@ describe('AdminController read-only getters', () => {
expect(adminCtl(svc({ getStats: vi.fn().mockReturnValue({ users: 3 }) } as Partial<AdminService>)).stats()).toEqual({ users: 3 });
expect(adminCtl(svc({ getPermissions: vi.fn().mockReturnValue({ a: 1 }) } as Partial<AdminService>)).permissions()).toEqual({ a: 1 });
expect(adminCtl(svc({ getAuditLog: vi.fn().mockReturnValue({ entries: [] }) } as Partial<AdminService>)).auditLog({})).toEqual({ entries: [] });
expect(adminCtl(svc({ getOidcSettings: vi.fn().mockReturnValue({ issuer: 'x' }) } as Partial<AdminService>)).getOidc()).toEqual({ issuer: 'x' });
expect(adminCtl(svc({ checkVersion: vi.fn().mockResolvedValue({ current: '1' }) } as Partial<AdminService>)).versionCheck()).resolves.toEqual({ current: '1' });
expect(adminCtl(svc({ getPreferencesMatrix: vi.fn().mockReturnValue({ rows: [] }) } as Partial<AdminService>)).getNotificationPrefs(user)).toEqual({ rows: [] });
expect(adminCtl(svc({ listInvites: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listInvites()).toEqual({ invites: [{ id: 1 }] });
expect(adminCtl(svc({ listAddons: vi.fn().mockReturnValue([{ id: 'mcp' }]) } as Partial<AdminService>)).listAddons()).toEqual({ addons: [{ id: 'mcp' }] });
expect(adminCtl(svc({ listMcpTokens: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listMcpTokens()).toEqual({ tokens: [{ id: 1 }] });
expect(adminCtl(svc({ listOAuthSessions: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<AdminService>)).listOAuthSessions()).toEqual({ sessions: [{ id: 1 }] });
expect(adminCtl(svc({ getAdminUserDefaults: vi.fn().mockReturnValue({ theme: 'dark' }) } as Partial<AdminService>)).getDefaultUserSettings()).toEqual({ theme: 'dark' });
});
it('setNotificationPrefs persists then returns the refreshed matrix', () => {
const setAdminPreferences = vi.fn();
const c = adminCtl(svc({ setAdminPreferences, getPreferencesMatrix: vi.fn().mockReturnValue({ rows: [1] }) } as Partial<AdminService>));
expect(c.setNotificationPrefs(user, { x: 1 })).toEqual({ rows: [1] });
expect(setAdminPreferences).toHaveBeenCalledWith(user.id, { x: 1 });
});
it('githubReleases falls back to default paging when no query is given', async () => {
const getGithubReleases = vi.fn().mockResolvedValue([{ tag: 'v1' }]);
@@ -204,18 +178,6 @@ describe('AdminController tokens + sessions', () => {
});
});
describe('AdminController default-user-settings error path', () => {
it('400 with an Error message when setAdminUserDefaults throws an Error', () => {
const c = adminCtl(svc({ setAdminUserDefaults: vi.fn(() => { throw new Error('bad default'); }) } as Partial<AdminService>));
expect(thrown(() => c.setDefaultUserSettings(user, { theme: 'x' }, req))).toEqual({ status: 400, body: { error: 'bad default' } });
});
it('400 stringifies a non-Error throw', () => {
const c = adminCtl(svc({ setAdminUserDefaults: vi.fn(() => { throw 'plain string'; }) } as Partial<AdminService>));
expect(thrown(() => c.setDefaultUserSettings(user, { theme: 'x' }, req))).toEqual({ status: 400, body: { error: 'plain string' } });
});
});
describe('AdminController dev test-notification', () => {
it('404 outside development', async () => {
@@ -82,14 +82,12 @@ const userCleanup = new UserCleanupService(dbs);
const auth = new AuthService(dbs, permissions, new AtlasService(dbs), new TripMembershipService(dbs), webauthn, userCleanup);
const svc = new AdminService(
dbs,
new SettingsService(dbs),
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
auth,
permissions,
makeNotificationsService(dbs, realtime),
userCleanup,
makeNotificationPreferencesService(dbs),
);
// Legacy free-function names bound to the service, so the moved cases below read
@@ -372,32 +370,6 @@ describe('getAuditLog — JSON details', () => {
// ── OIDC Settings ─────────────────────────────────────────────────────────────
describe('OIDC Settings', () => {
it('ADMIN-SVC-047 — getOidcSettings returns default empty values when no OIDC configured', () => {
const result = getOidcSettings() as any;
expect(result.issuer).toBe('');
expect(result.client_id).toBe('');
expect(result.oidc_only).toBe(false);
expect(result.client_secret_set).toBe(false);
expect(result.display_name).toBe('');
expect(result.discovery_url).toBe('');
});
it('ADMIN-SVC-048 — updateOidcSettings persists issuer and client_id, then getOidcSettings returns them', () => {
updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = getOidcSettings() as any;
expect(result.issuer).toBe('https://auth.example.com');
expect(result.client_id).toBe('my-client');
});
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', () => {
updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = getOidcSettings() as any;
// oidc_only is no longer managed by updateOidcSettings; use password_login/oidc_login toggles
expect(result.oidc_only).toBe(false);
});
});
// ── saveDemoBaseline ──────────────────────────────────────────────────────────
describe('saveDemoBaseline', () => {
@@ -623,11 +595,4 @@ describe('admin quirk fixes (post-fold)', () => {
expect(sessions).toHaveLength(1);
expect(sessions[0].scopes).toBeNull();
});
it('ADMIN-SVC-075 — updateOidcSettings applies all five writes atomically', () => {
const result = svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' }) as any;
expect(result.success).toBe(true);
const settings = svc.getOidcSettings();
expect(settings).toMatchObject({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' });
});
});
@@ -65,14 +65,12 @@ const userCleanup = new UserCleanupService(dbs);
const auth = new AuthService(dbs, permissions, new AtlasService(dbs), new TripMembershipService(dbs), webauthn, userCleanup);
const svc = new AdminService(
dbs,
new SettingsService(dbs),
new AddonsService(dbs),
new PasskeyService(dbs, auth, webauthn),
auth,
permissions,
makeNotificationsService(dbs, realtime),
userCleanup,
makeNotificationPreferencesService(dbs),
);
const checkAndNotifyVersion = () => svc.checkAndNotifyVersion();
@@ -827,3 +827,69 @@ describe('wrapper methods', () => {
expect(setAuthCookieMock).toHaveBeenCalledWith(res, 'jwt', req);
});
});
// The SSO configuration read/write moved here from AdminService, which held the SQL
// for a domain that already had a module. Same cases, same service, new owner.
describe('OIDC settings', () => {
it('ADMIN-SVC-047 — getOidcSettings returns default empty values when no OIDC configured', () => {
const result = svc.getOidcSettings() as any;
expect(result.issuer).toBe('');
expect(result.client_id).toBe('');
expect(result.oidc_only).toBe(false);
expect(result.client_secret_set).toBe(false);
expect(result.display_name).toBe('');
expect(result.discovery_url).toBe('');
});
it('ADMIN-SVC-048 — updateOidcSettings persists issuer and client_id, then getOidcSettings returns them', () => {
svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = svc.getOidcSettings() as any;
expect(result.issuer).toBe('https://auth.example.com');
expect(result.client_id).toBe('my-client');
});
it('ADMIN-SVC-049 — updateOidcSettings does not write oidc_only (replaced by granular toggles)', () => {
svc.updateOidcSettings({ issuer: 'https://auth.example.com', client_id: 'my-client' });
const result = svc.getOidcSettings() as any;
// oidc_only is no longer managed by updateOidcSettings; use password_login/oidc_login toggles
expect(result.oidc_only).toBe(false);
});
it('ADMIN-SVC-075 — updateOidcSettings applies all five writes atomically', () => {
const result = svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' }) as any;
expect(result.success).toBe(true);
const settings = svc.getOidcSettings();
expect(settings).toMatchObject({ issuer: 'https://idp', client_id: 'cid', display_name: 'IdP' });
});
});
describe('OIDC settings — the lockout guard', () => {
it('OIDC-SETTINGS-050 refuses to clear the config while password login is off', () => {
// Clearing the issuer with password login disabled locks every user out of the
// instance: no SSO to log in through, and no password form either.
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockReturnValue({ password_login: false } as never);
expect(svc.updateOidcSettings({ issuer: '', client_id: 'x' })).toMatchObject({ status: 400 });
expect(svc.updateOidcSettings({ issuer: 'x', client_id: '' })).toMatchObject({ status: 400 });
expect((svc.updateOidcSettings({ issuer: '', client_id: '' }) as { error?: string }).error).toMatch(/password login/i);
toggles.mockRestore();
});
it('OIDC-SETTINGS-051 allows the same clear once password login is back on', () => {
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockReturnValue({ password_login: true } as never);
expect(svc.updateOidcSettings({ issuer: '', client_id: '' })).toEqual({ success: true });
toggles.mockRestore();
});
it('OIDC-SETTINGS-052 an omitted client_secret keeps the stored one, an empty string clears it', () => {
const toggles = vi.spyOn(auth, 'resolveAuthToggles').mockReturnValue({ password_login: true } as never);
svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: 'shh' });
expect(svc.getOidcSettings().client_secret_set).toBe(true);
// Omitted: the write skips the column entirely rather than blanking it, which is
// what lets the admin panel save the form without re-typing the secret.
svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c' });
expect(svc.getOidcSettings().client_secret_set).toBe(true);
svc.updateOidcSettings({ issuer: 'https://idp', client_id: 'c', client_secret: '' });
expect(svc.getOidcSettings().client_secret_set).toBe(false);
toggles.mockRestore();
});
});