fix(admin): guard GET /api/users/{id} with @RequirePermission(ADMIN_USER)

Fixes IDOR: the endpoint was publicly accessible to any authenticated user.
Now requires ADMIN_USER permission, matching all other user management endpoints.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-03-30 01:09:40 +02:00
parent 169e6dc578
commit 8fc360a596
22 changed files with 844 additions and 346 deletions

View File

@@ -0,0 +1,8 @@
import { createApiClient } from '$lib/api.server';
import type { LayoutServerLoad } from './$types';
export const load: LayoutServerLoad = async ({ fetch }) => {
const api = createApiClient(fetch);
const result = await api.GET('/api/users');
return { users: result.data ?? [] };
};

View File

@@ -0,0 +1,12 @@
<script lang="ts">
import UsersListPanel from './UsersListPanel.svelte';
let { data, children } = $props();
</script>
<UsersListPanel users={data.users} />
<!-- Detail panel -->
<div class="flex min-w-0 flex-1 flex-col overflow-hidden">
{@render children()}
</div>

View File

@@ -0,0 +1,7 @@
<script lang="ts">
import { m } from '$lib/paraglide/messages.js';
</script>
<div class="flex flex-1 items-center justify-center p-8">
<p class="text-sm text-ink-3">{m.admin_users_select_prompt()}</p>
</div>

View File

@@ -0,0 +1,105 @@
<script lang="ts">
import { page } from '$app/state';
import { m } from '$lib/paraglide/messages.js';
type Group = {
id: string;
name: string;
permissions: string[];
};
type User = {
id: string;
username: string;
firstName: string | null;
lastName: string | null;
groups: Group[];
};
let { users }: { users: User[] } = $props();
let searchQuery = $state('');
const filtered = $derived(
searchQuery.trim() === ''
? users
: users.filter((u) =>
[u.username, u.firstName, u.lastName]
.filter(Boolean)
.some((v) => v!.toLowerCase().includes(searchQuery.toLowerCase()))
)
);
</script>
<div class="flex w-60 flex-shrink-0 flex-col overflow-hidden border-r border-line bg-surface">
<!-- Panel header -->
<div class="flex items-center justify-between border-b border-line px-3 py-2">
<span class="text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_users_list_title()}
</span>
<a
href="/admin/users/new"
class="inline-flex items-center gap-1 rounded-sm px-2 py-1 text-xs font-medium text-ink-2 transition-colors hover:bg-muted hover:text-ink"
title={m.admin_btn_new_user()}
aria-label={m.admin_btn_new_user()}
>
<svg
class="h-3.5 w-3.5"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2.5"
aria-hidden="true"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
</svg>
{m.admin_btn_new_user()}
</a>
</div>
<!-- Search -->
<div class="border-b border-line px-3 py-2">
<input
type="search"
bind:value={searchQuery}
placeholder={m.admin_users_search_placeholder()}
class="w-full rounded-sm border border-line bg-surface px-2 py-1.5 text-sm text-ink placeholder:text-ink-3 focus:ring-1 focus:ring-primary focus:outline-none"
/>
</div>
<!-- Scrollable user list -->
<div class="flex-1 overflow-y-auto">
{#if filtered.length === 0}
<p class="px-4 py-6 text-center text-xs text-ink-3">
{m.admin_users_empty()}
</p>
{:else}
{#each filtered as user (user.id)}
{@const isActive = page.url.pathname.startsWith('/admin/users/' + user.id)}
{@const fullName =
[user.firstName, user.lastName].filter(Boolean).join(' ') || null}
<a
href="/admin/users/{user.id}"
aria-current={isActive ? 'page' : undefined}
class="block border-l-2 px-3 py-2.5 transition-colors {isActive
? 'border-primary bg-primary/10 dark:bg-primary/15'
: 'border-transparent hover:bg-muted'}"
>
<div class="text-sm font-bold text-ink">{user.username}</div>
{#if fullName}
<div class="mt-0.5 text-xs text-ink-3">{fullName}</div>
{/if}
{#if user.groups.length > 0}
<div class="mt-1 flex flex-wrap gap-1">
{#each user.groups as group (group.id)}
<span class="rounded-sm bg-muted px-1.5 py-0.5 text-[10px] text-ink-3">
{group.name}
</span>
{/each}
</div>
{/if}
</a>
{/each}
{/if}
</div>
</div>

View File

@@ -10,85 +10,74 @@ let { data, form } = $props();
const selectedGroupIds = $derived(data.editUser.groups?.map((g: { id: string }) => g.id) ?? []);
</script>
<div class="mx-auto max-w-3xl px-4 py-8 sm:px-6 lg:px-8">
<a
href="/admin"
class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
>
<svg
class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Detail panel header -->
<div class="flex items-center border-b border-line px-5 py-3">
<h2 class="flex-1 font-sans text-sm font-bold text-ink">
{m.admin_user_edit_heading({ username: data.editUser.username })}
</h2>
</div>
<!-- Scrollable body -->
<div class="flex-1 overflow-y-auto px-5 py-5">
{#if form?.success}
<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
{m.admin_user_updated()}
</div>
{/if}
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
<form id="edit-user-form" method="POST" use:enhance class="space-y-5">
<!-- Profile card -->
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h3>
<UserProfileSection
firstName={data.editUser.firstName ?? ''}
lastName={data.editUser.lastName ?? ''}
birthDate={data.editUser.birthDate ?? ''}
email={data.editUser.email ?? ''}
contact={data.editUser.contact ?? ''}
/>
</div>
<!-- Groups card -->
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h3>
<UserGroupsSection groups={data.groups} selectedGroupIds={selectedGroupIds} />
</div>
<!-- Password card -->
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_label_new_password_optional()}
</h3>
<UserPasswordSection />
</div>
</form>
</div>
<!-- Docked footer -->
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
<a
href="/admin/users"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
{m.btn_back_to_overview()}
</a>
<h1 class="mb-6 font-serif text-3xl font-bold text-ink">
{m.admin_user_edit_heading({ username: data.editUser.username })}
</h1>
{#if form?.success}
<div class="mb-5 rounded border border-green-200 bg-green-50 p-3 text-sm text-green-700">
{m.admin_user_updated()}
</div>
{/if}
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
<form method="POST" use:enhance class="space-y-6">
<!-- Profile card -->
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h2>
<UserProfileSection
firstName={data.editUser.firstName ?? ''}
lastName={data.editUser.lastName ?? ''}
birthDate={data.editUser.birthDate ?? ''}
email={data.editUser.email ?? ''}
contact={data.editUser.contact ?? ''}
/>
</div>
<!-- Groups card -->
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h2>
<UserGroupsSection groups={data.groups} selectedGroupIds={selectedGroupIds} />
</div>
<!-- Password card -->
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<h2 class="mb-5 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_label_new_password_optional()}
</h2>
<UserPasswordSection />
</div>
<!-- Save bar -->
<div
class="sticky bottom-0 z-10 -mx-4 flex items-center justify-between border-t border-line bg-surface px-6 py-4 shadow-[0_-2px_8px_rgba(0,0,0,0.06)]"
{m.btn_cancel()}
</a>
<button
type="submit"
form="edit-user-form"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
<a
href="/admin"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
{m.btn_cancel()}
</a>
<button
type="submit"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
{m.btn_save()}
</button>
</div>
</form>
{m.btn_save()}
</button>
</div>
</div>

View File

@@ -110,11 +110,11 @@ describe('Admin edit user page rendering', () => {
});
});
it('cancel link points to /admin', async () => {
it('cancel link points to /admin/users', async () => {
render(Page, { data: baseData, form: null });
await expect
.element(page.getByRole('link', { name: /Abbrechen/i }))
.toHaveAttribute('href', '/admin');
.toHaveAttribute('href', '/admin/users');
});
it('renders the save button', async () => {

View File

@@ -0,0 +1,41 @@
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { load } from './+layout.server';
vi.mock('$lib/api.server', () => ({ createApiClient: vi.fn() }));
import { createApiClient } from '$lib/api.server';
function mockApi(users: unknown[]) {
vi.mocked(createApiClient).mockReturnValue({
GET: vi.fn().mockResolvedValueOnce({ response: { ok: true }, data: users })
} as ReturnType<typeof createApiClient>);
}
beforeEach(() => vi.clearAllMocks());
describe('admin/users layout load', () => {
it('returns the users list', async () => {
mockApi([
{ id: 'u1', username: 'alice' },
{ id: 'u2', username: 'bob' }
]);
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
expect(result.users).toHaveLength(2);
expect(result.users[0].username).toBe('alice');
});
it('returns an empty array when the API returns nothing', async () => {
mockApi([]);
const result = await load({ fetch: vi.fn() as unknown as typeof fetch });
expect(result.users).toEqual([]);
});
it('calls GET /api/users', async () => {
const mockGet = vi.fn().mockResolvedValue({ response: { ok: true }, data: [] });
vi.mocked(createApiClient).mockReturnValue({ GET: mockGet } as ReturnType<
typeof createApiClient
>);
await load({ fetch: vi.fn() as unknown as typeof fetch });
expect(mockGet).toHaveBeenCalledWith('/api/users');
});
});

View File

@@ -0,0 +1,95 @@
import { afterEach, describe, it, expect, vi } from 'vitest';
import { cleanup, render } from 'vitest-browser-svelte';
import { page } from 'vitest/browser';
import UsersListPanel from './UsersListPanel.svelte';
vi.mock('$app/state', () => ({
page: { url: { pathname: '/admin/users/u1' } }
}));
afterEach(cleanup);
const users = [
{
id: 'u1',
username: 'reader',
firstName: 'Lea',
lastName: 'Leserin',
groups: [{ id: 'g1', name: 'Leser', permissions: ['READ_ALL'] }]
},
{
id: 'u2',
username: 'admin',
firstName: null,
lastName: null,
groups: [{ id: 'g2', name: 'Admins', permissions: ['ADMIN'] }]
}
];
describe('UsersListPanel — header', () => {
it('renders the panel title', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByText(/Alle Benutzer/i)).toBeInTheDocument();
});
it('renders a new-user link pointing to /admin/users/new', async () => {
render(UsersListPanel, { users });
await expect
.element(page.getByRole('link', { name: /neuer benutzer/i }))
.toHaveAttribute('href', '/admin/users/new');
});
it('renders a search input', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByRole('searchbox')).toBeInTheDocument();
});
});
describe('UsersListPanel — user items', () => {
it('renders each username', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByRole('link', { name: /reader/i })).toBeInTheDocument();
await expect.element(page.getByRole('link', { name: /admin/i })).toBeInTheDocument();
});
it('each user links to /admin/users/[id]', async () => {
const { container } = render(UsersListPanel, { users });
const links = container.querySelectorAll<HTMLAnchorElement>('a[href^="/admin/users/u"]');
expect(links.length).toBe(2);
expect(links[0].getAttribute('href')).toBe('/admin/users/u1');
expect(links[1].getAttribute('href')).toBe('/admin/users/u2');
});
it('shows full name as subtitle when available', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByText('Lea Leserin')).toBeInTheDocument();
});
it('shows group name chip', async () => {
render(UsersListPanel, { users });
await expect.element(page.getByText('Leser', { exact: true })).toBeInTheDocument();
});
});
describe('UsersListPanel — active state', () => {
it('marks the active user link with aria-current=page', async () => {
render(UsersListPanel, { users });
await expect
.element(page.getByRole('link', { name: /reader/i }))
.toHaveAttribute('aria-current', 'page');
});
it('does not mark the inactive user link with aria-current', async () => {
render(UsersListPanel, { users });
await expect
.element(page.getByRole('link', { name: /admin/i }))
.not.toHaveAttribute('aria-current');
});
});
describe('UsersListPanel — empty state', () => {
it('shows empty state message when users array is empty', async () => {
render(UsersListPanel, { users: [] });
await expect.element(page.getByText(/keine benutzer/i)).toBeInTheDocument();
});
});

View File

@@ -40,6 +40,6 @@ export const actions: Actions = {
return fail(result.response.status, { error: getErrorMessage(code) });
}
throw redirect(303, '/admin');
throw redirect(303, '/admin/users');
}
};

View File

@@ -8,64 +8,57 @@ import AccountSection from './AccountSection.svelte';
let { data, form } = $props();
</script>
<div class="mx-auto max-w-3xl px-4 py-8 sm:px-6 lg:px-8">
<a
href="/admin"
class="group mb-4 inline-flex items-center text-xs font-bold tracking-widest text-ink-2 uppercase transition-colors hover:text-ink"
>
<svg
class="mr-2 h-4 w-4 transform transition-transform group-hover:-translate-x-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2"
>
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
{m.btn_back_to_overview()}
</a>
<div class="flex flex-1 flex-col overflow-hidden">
<!-- Detail panel header -->
<div class="flex items-center border-b border-line px-5 py-3">
<h2 class="flex-1 font-sans text-sm font-bold text-ink">{m.admin_user_new_heading()}</h2>
</div>
<h1 class="mb-6 font-serif text-3xl font-bold text-ink">{m.admin_user_new_heading()}</h1>
<!-- Scrollable body -->
<div class="flex-1 overflow-y-auto px-5 py-5">
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
{#if form?.error}
<div class="mb-5 rounded border border-red-200 bg-red-50 p-3 text-sm text-red-700">
{form.error}
</div>
{/if}
<div class="rounded-sm border border-line bg-surface p-6 shadow-sm">
<form method="POST" use:enhance class="space-y-5">
<AccountSection />
<form id="new-user-form" method="POST" use:enhance class="space-y-5">
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<AccountSection />
</div>
<!-- Profile -->
<h2 class="pt-2 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h2>
<UserProfileSection />
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.profile_section_personal()}
</h3>
<UserProfileSection />
</div>
<!-- Groups -->
<h2 class="pt-2 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h2>
<UserGroupsSection groups={data.groups} />
<!-- Save bar -->
<div
class="mt-4 flex items-center justify-between rounded-sm border border-line bg-surface px-6 py-4 shadow-sm"
>
<a
href="/admin"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
{m.btn_cancel()}
</a>
<button
type="submit"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
{m.btn_create()}
</button>
<div class="rounded-sm border border-line bg-surface p-5 shadow-sm">
<h3 class="mb-4 text-xs font-bold tracking-widest text-ink-3 uppercase">
{m.admin_col_groups()}
</h3>
<UserGroupsSection groups={data.groups} />
</div>
</form>
</div>
<!-- Docked footer -->
<div class="flex items-center justify-between border-t border-line bg-surface px-5 py-3">
<a
href="/admin/users"
class="font-sans text-xs font-bold tracking-widest text-ink-2 uppercase hover:text-ink"
>
{m.btn_cancel()}
</a>
<button
type="submit"
form="new-user-form"
class="rounded-sm bg-primary px-5 py-2 font-sans text-xs font-bold tracking-widest text-primary-fg uppercase transition-opacity hover:opacity-80"
>
{m.btn_create()}
</button>
</div>
</div>

View File

@@ -33,18 +33,11 @@ describe('Admin new user page rendering', () => {
await expect.element(page.getByText('Admins')).toBeInTheDocument();
});
it('cancel link points to /admin', async () => {
it('cancel link points to /admin/users', async () => {
render(Page, { data: baseData, form: null });
await expect
.element(page.getByRole('link', { name: /Abbrechen/i }))
.toHaveAttribute('href', '/admin');
});
it('back link points to /admin', async () => {
render(Page, { data: baseData, form: null });
await expect
.element(page.getByRole('link', { name: /Zurück/i }))
.toHaveAttribute('href', '/admin');
.toHaveAttribute('href', '/admin/users');
});
it('renders the create button', async () => {