From 10da62ea4c3ae00ffa5461a5709b979937f5af8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 16:58:00 +0200 Subject: [PATCH] Lock down injected users, 2FA slug, forms and globals writes - Injected auth collection with roles: admins manage all accounts, others only themselves (Payload's default let any account edit or delete any other) - 2FA defaults to the resolved auth collection instead of 'users' - SiteSettings, CookieSettings, Notifications, Forms: write needs editor+; form Emails tab readable by editor+ only Co-Authored-By: Claude Opus 5.5 --- docs/access.md | 16 ++++ docs/forms.md | 5 ++ docs/notifications.md | 2 +- docs/security.md | 12 ++- src/globals/CookieSettings/index.ts | 2 + src/globals/Notifications/index.ts | 2 + src/globals/SiteSettings/index.ts | 4 + src/modules/forms/formsPluginConfig.ts | 16 +++- src/plugin.ts | 23 ++++- test/accessControl.test.ts | 119 +++++++++++++++++++++++++ 10 files changed, 194 insertions(+), 7 deletions(-) create mode 100644 test/accessControl.test.ts diff --git a/docs/access.md b/docs/access.md index 1a751cf..0841278 100644 --- a/docs/access.md +++ b/docs/access.md @@ -22,6 +22,22 @@ Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, pierwszego admina nadal da się utworzyć. Kolekcja należy do Ciebie (create-payload-app) — plugin tylko dokłada pole. +## Co plugin zamyka sam + +| Zasób | Odczyt | Zapis | +|---|---|---| +| kolekcja auth **wstrzyknięta** przez plugin (gdy projekt nie ma własnej) i z rolami | admin: wszyscy; inni: tylko siebie | `create`/`delete`: admin; `update`: admin albo siebie | +| Site Settings, Cookie Settings, Notifications | publiczny | `editor+` | +| Site Integrations | admin | admin | +| Forms | publiczny (bez zakładki Emails — ta tylko `editor+`) | `editor+` | +| Form submissions | `editor+` | REST `create`: zalogowani; `delete`: admin | + +Własna kolekcja auth projektu zachowuje własne `access` — plugin dokłada tylko pole +`roles`. Ustaw jej co najmniej `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`: +domyślny Payload pozwala każdemu zalogowanemu zmienić e-mail i hasło innego konta. +Kolekcja wstrzyknięta **bez** `access` (brak ról) zostaje przy domyślnych regułach Payloada — +bez ról wszystkie konta są równe. + > Po dodaniu: zadbaj, by seed / pierwszy user miał `roles: ['admin']`, inaczej > stracisz dostęp do zasobów admin-only (np. SiteIntegrations). diff --git a/docs/forms.md b/docs/forms.md index ad508e0..cab334d 100644 --- a/docs/forms.md +++ b/docs/forms.md @@ -298,6 +298,11 @@ wysyła przez `submitForm` (server action → Local API), więc to go nie dotycz `forms: { formSubmissionOverrides: { access: { create: () => true } } }` — wtedy zabezpieczenia `submitForm` na tej drodze nie działają. +**Formularze edytuje tylko `editor+`.** Kolekcja `forms` jest publiczna do odczytu (pola renderują +formularz), ale `create`/`update`/`delete` i odczyt zakładki Emails (odbiorcy, BCC) wymagają roli +`editor` lub `admin` — konto `user` nie dopisze sobie BCC do każdego zgłoszenia. Nadpisanie: +`forms: { formOverrides: { access: { … } } }`. + Walidacja jest istotna, bo server action to publiczny endpoint — da się go wołać z pominięciem formularza. Plugin ładuje definicję formularza i: odrzuca nieznane klucze, wymusza pola `required`, tnie długość (5000 znaków). Do bazy trafia tylko diff --git a/docs/notifications.md b/docs/notifications.md index aea0d89..e31c70e 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -67,5 +67,5 @@ fallback. `getNotificationTexts` resolwuje, co istnieje. ## Dostęp Global ma `read: () => true` — teksty są publiczne (pokazywane użytkownikom -końcowym), więc front czyta je bez sesji. Inaczej niż SiteIntegrations +końcowym), więc front czyta je bez sesji. Zapis: `editor+`. Inaczej niż SiteIntegrations (`read: isAdmin` — tam sekrety). diff --git a/docs/security.md b/docs/security.md index 02769e7..d0cafbb 100644 --- a/docs/security.md +++ b/docs/security.md @@ -274,7 +274,7 @@ ipalKit({ twoFactor: { issuer: 'Nazwa Firmy', // pokazywane w aplikacji authenticator plugin: payloadTotp, // ← WSTRZYKNIJ — patrz niżej dlaczego - // collectionSlug: 'users', + // collectionSlug: 'users', // domyślnie kolekcja auth: access.authCollection → admin.user → 'users' }, }) ``` @@ -334,3 +334,13 @@ dostęp do danych, nie tylko UI. - Zgłoszenia formularzy: odczyt `editor+`; adresy z zakładki Emails niewidoczne publicznie. - Uploady: `buildUploadSecurityHeaders()` w `next.config.ts` (SVG nie uruchomi skryptu na domenie strony). - `users`: plugin wstrzykuje kolekcję auth, gdy projekt jej nie ma (role i 2FA zawsze się wpinają). + +## Kontrola dostępu (od wersji po 1.12.3) + +- Wstrzyknięta kolekcja auth z rolami: konto `user` czyta i edytuje tylko siebie, tworzy i usuwa + tylko admin. Wcześniej każdy zalogowany mógł zmienić e-mail/hasło admina. +- 2FA bez `collectionSlug` wrapuje kolekcję, którą faktycznie się logujesz (`access.authCollection`, + potem `admin.user`), a nie literał `'users'` — inaczej TOTP po cichu nie działał. +- Site Settings, Cookie Settings, Notifications i kolekcja Forms: zapis tylko `editor+`; zakładka + Emails formularza (odbiorcy, BCC) czytelna tylko dla `editor+`. +- Pełna tabela: [access.md](./access.md#co-plugin-zamyka-sam). diff --git a/src/globals/CookieSettings/index.ts b/src/globals/CookieSettings/index.ts index 587650d..7f88079 100644 --- a/src/globals/CookieSettings/index.ts +++ b/src/globals/CookieSettings/index.ts @@ -1,5 +1,6 @@ import type { GlobalConfig } from 'payload' +import { adminOrEditor } from '../../modules/access/index.js' import { cookieSettingsFields } from './fields.js' /** @@ -11,6 +12,7 @@ export function buildCookieSettings(): GlobalConfig { slug: 'cookie-settings', access: { read: () => true, + update: adminOrEditor, // consent texts are legal copy — not for plain 'user' accounts }, admin: { group: 'Settings', diff --git a/src/globals/Notifications/index.ts b/src/globals/Notifications/index.ts index 308b23f..e8b918f 100644 --- a/src/globals/Notifications/index.ts +++ b/src/globals/Notifications/index.ts @@ -1,5 +1,6 @@ import type { GlobalConfig } from 'payload' +import { adminOrEditor } from '../../modules/access/index.js' import { notificationsFields } from './fields.js' /** @@ -12,6 +13,7 @@ export function buildNotifications(): GlobalConfig { slug: 'notifications', access: { read: () => true, // texts are public-facing (shown to end users) + update: adminOrEditor, }, admin: { group: 'Settings' }, fields: notificationsFields, diff --git a/src/globals/SiteSettings/index.ts b/src/globals/SiteSettings/index.ts index c373ce9..4222038 100644 --- a/src/globals/SiteSettings/index.ts +++ b/src/globals/SiteSettings/index.ts @@ -1,5 +1,6 @@ import type { Field, GlobalConfig } from 'payload' +import { adminOrEditor } from '../../modules/access/index.js' import { generalFields } from './fields/general.js' import { themeFields } from './fields/theme.js' @@ -42,6 +43,9 @@ export function buildSiteSettings({ slug: 'site-settings', access: { read: () => true, + // Editors and admins only — a plain 'user' account (open sign-up) must + // not rewrite the brand, homepage or construction mode. + update: adminOrEditor, }, admin: { group: 'Settings', diff --git a/src/modules/forms/formsPluginConfig.ts b/src/modules/forms/formsPluginConfig.ts index 08dd69b..eab94a4 100644 --- a/src/modules/forms/formsPluginConfig.ts +++ b/src/modules/forms/formsPluginConfig.ts @@ -26,10 +26,15 @@ const submissionsCreateAccess = ({ req }: AccessArgs) => Boolean(req.user) */ const submissionsReadAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor') const submissionsDeleteAccess = ({ req }: AccessArgs) => isAdmin(req.user as never) +/** + * Forms carry recipient addresses (Emails → To/BCC): a plain 'user' account + * editing a form could BCC every submission to itself. Editors and admins only. + */ +const staffAccess = ({ req }: AccessArgs) => hasMinimumRole(req.user as never, 'editor') /** * Forms stay publicly readable (their fields render the form), but the Emails - * tab — recipient addresses, templates — is for logged-in staff only, so + * tab — recipient addresses, templates — is for editors and admins only, so * GET /api/forms doesn't hand out the company's inboxes to spammers. */ function hideEmails(fields: Field[]): Field[] { @@ -37,7 +42,7 @@ function hideEmails(fields: Field[]): Field[] { 'name' in field && field.name === 'emails' ? ({ ...field, - access: { ...(field as { access?: object }).access, read: ({ req }: AccessArgs) => Boolean(req.user) }, + access: { ...(field as { access?: object }).access, read: staffAccess }, } as Field) : field, ) @@ -104,6 +109,13 @@ export function buildFormsPlugin(forms: FormsOption): Plugin { formOverrides: { labels: { plural: 'Forms', singular: 'Form' }, ...forms.formOverrides, + access: { + create: staffAccess, + delete: staffAccess, + read: () => true, + update: staffAccess, + ...forms.formOverrides?.access, + }, admin: { ...group, ...forms.formOverrides?.admin }, fields: ({ defaultFields }) => hideEmails(forms.formOverrides?.fields ? forms.formOverrides.fields({ defaultFields }) : defaultFields), diff --git a/src/plugin.ts b/src/plugin.ts index a2df254..e0124a2 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -7,7 +7,7 @@ import { migrateCookieSettingsSaveButton } from './globals/CookieSettings/migrat import { buildNotifications } from './globals/Notifications/index.js' import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js' import { buildSiteSettings } from './globals/SiteSettings/index.js' -import { injectRoles } from './modules/access/index.js' +import { adminOnly, adminOrSelf, injectRoles } from './modules/access/index.js' import { buildConsentLogCollection, buildConsentLogEndpoint } from './modules/consent/consentLog.js' import { buildConstructionFields } from './modules/construction/fields.js' import { buildArchiveFields } from './modules/content/index.js' @@ -65,10 +65,23 @@ export const ipalKit = (options: IpalOptions): Plugin => { (options.twoFactor ? options.twoFactor.collectionSlug : undefined) ?? config.admin?.user ?? 'users' + // With roles on it (access.authCollection), the injected collection is + // locked down: Payload's default lets ANY logged-in account read, edit + // (email, password) or delete every other account — a plain 'user' could + // take over an admin. Admins manage everyone; others only themselves. if (!(config.collections ?? []).some((c) => c.slug === authSlug)) { + const hasRoles = options.access?.authCollection === authSlug config.collections = [ ...(config.collections ?? []), - { slug: authSlug, admin: { useAsTitle: 'email' }, auth: true, fields: [] }, + { + slug: authSlug, + ...(hasRoles + ? { access: { create: adminOnly, delete: adminOnly, read: adminOrSelf, update: adminOrSelf } } + : {}), + admin: { useAsTitle: 'email' }, + auth: true, + fields: [], + }, ] } @@ -108,8 +121,12 @@ export const ipalKit = (options: IpalOptions): Plugin => { ) } + // Default to the resolved auth collection (access.authCollection / + // admin.user), not a literal 'users': wrapping a slug nobody logs in with + // leaves the real collection without TOTP fields, and the TOTP access + // wrapper lets users without those fields through — 2FA silently off. config = await totp({ - collection: tf.collectionSlug ?? 'users', + collection: tf.collectionSlug ?? authSlug, forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out totp: { issuer: tf.issuer }, })(config) diff --git a/test/accessControl.test.ts b/test/accessControl.test.ts new file mode 100644 index 0000000..5306bdd --- /dev/null +++ b/test/accessControl.test.ts @@ -0,0 +1,119 @@ +import type { Access, CollectionConfig, Config, Field, GlobalConfig } from 'payload' + +import { describe, expect, test, vi } from 'vitest' + +import type { I18nConfig } from '../src/modules/i18n/types.js' + +import { ipalKit } from '../src/plugin.js' + +const i18n: I18nConfig = { + defaultLocale: 'pl', + locales: [ + { code: 'pl', label: 'Polski' }, + { code: 'en', label: 'English' }, + ], +} + +const empty = (extra: Partial = {}): Config => + ({ collections: [], secret: 'x', ...extra }) as unknown as Config + +const admin = { id: 1, roles: ['admin'] } +const editor = { id: 2, roles: ['editor'] } +const user = { id: 3, roles: ['user'] } + +/** Runs a collection/global access function the way Payload does. */ +const run = (fn: Access | undefined, u: unknown) => + fn ? fn({ req: { user: u } } as never) : 'payload-default' + +describe('injected auth collection', () => { + test('with roles: a plain user can only see and edit itself, never create or delete', async () => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {} + + expect(run(access.update, user)).toEqual({ id: { equals: 3 } }) + expect(run(access.read, user)).toEqual({ id: { equals: 3 } }) + expect(run(access.delete, user)).toBe(false) + expect(run(access.create, user)).toBe(false) + expect(run(access.delete, editor)).toBe(false) + expect(run(access.update, null)).toBe(false) + + expect(run(access.update, admin)).toBe(true) + expect(run(access.delete, admin)).toBe(true) + expect(run(access.create, admin)).toBe(true) + }) + + test("the project's own auth collection keeps its own access", async () => { + const own = { slug: 'users', access: { read: () => true }, auth: true, fields: [] } + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })( + empty({ collections: [own] as CollectionConfig[] }), + ) + expect(config.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access) + }) +}) + +describe('2FA wraps the auth collection people log in with', () => { + const totp = () => vi.fn((_: unknown) => (c: Config) => c) + + test('defaults to access.authCollection, not a literal "users"', async () => { + const plugin = totp() + await ipalKit({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( + empty(), + ) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + }) + + test('defaults to admin.user when access is not configured', async () => { + const plugin = totp() + await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })( + empty({ admin: { user: 'staff' } } as Partial), + ) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' })) + }) + + test('an explicit collectionSlug still wins', async () => { + const plugin = totp() + await ipalKit({ + access: { authCollection: 'users' }, + i18n, + twoFactor: { collectionSlug: 'admins', issuer: 'A', plugin: plugin as never }, + })(empty()) + expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' })) + }) +}) + +describe('globals: public read, editor+ write', () => { + test.each(['site-settings', 'cookie-settings', 'notifications'])('%s', async (slug) => { + const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty()) + const access = (config.globals?.find((g) => g.slug === slug) as GlobalConfig).access ?? {} + expect(run(access.read, null)).toBe(true) + expect(run(access.update, user)).toBe(false) + expect(run(access.update, null)).toBe(false) + expect(run(access.update, editor)).toBe(true) + expect(run(access.update, admin)).toBe(true) + }) +}) + +describe('forms collection: public read, editor+ write, Emails hidden from plain users', () => { + const build = async () => { + const config = await ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty()) + return config.collections?.find((c) => c.slug === 'forms') as CollectionConfig + } + + test('create / update / delete need editor', async () => { + const { access = {} } = await build() + expect(run(access.read, null)).toBe(true) + for (const op of ['create', 'update', 'delete'] as const) { + expect(run(access[op], user)).toBe(false) + expect(run(access[op], editor)).toBe(true) + } + }) + + test('the Emails field (recipients, BCC) is unreadable for a plain user', async () => { + const forms = await build() + const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as { + access?: { read?: (a: unknown) => boolean } + } + expect(emails.access?.read?.({ req: { user } })).toBe(false) + expect(emails.access?.read?.({ req: { user: editor } })).toBe(true) + }) +})