/** * IAWL security ideas, group B, through real HTTP (REST and GraphQL) against a running Payload. * SQLite by default; Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts). * * 22/37 — the versions of Site integrations (a project may turn them on) are read by the people who read the * global, not by every signed-in account; the secrets stay masked there. * 23 — drafts over REST / GraphQL follow the collection's `read` rule: Payload's open `read: () => true` * answers `?draft=true` with the draft; readPublished() (exported) keeps drafts for the editors. * 24/25 — locales: every locale IAPL configures is public; an unknown `?locale=` is the default locale's text, * never another locale's draft. */ import type { Payload } from 'payload' import { lexicalEditor } from '@payloadcms/richtext-lexical' import os from 'os' import path from 'path' import { getPayload } from 'payload' import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest' import { readPublished } from '../src/modules/access/access.js' import { SECRET_MASK } from '../src/modules/secrets/writeOnly.js' import { iapl } from '../src/plugin.js' import { buildTestConfig } from './helpers.js' import { testDatabase } from './http/db.js' import { startPayloadServer, type TestServer } from './http/server.js' vi.mock('server-only', () => ({})) const PASSWORD = 'a-long-test-password-1' const SMTP = 'S3CRET-smtp-value' let server: TestServer let payload: Payload const tokens: Record<'admin' | 'editor' | 'user', string> = { admin: '', editor: '', user: '' } let openDraftId: number | string let guardedDraftId: number | string let guardedPublishedId: number | string const api = (pathname: string, as?: keyof typeof tokens, init: RequestInit = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...(as ? { authorization: `JWT ${tokens[as]}` } : {}) } }) const gql = async (query: string, as?: keyof typeof tokens) => (await (await api('/graphql', as, { body: JSON.stringify({ query }), method: 'POST' })).json()) as { data?: Record; errors?: { message: string }[] } const pageFields = [ { name: 'title', type: 'text' as const, localized: true }, { name: 'secretNote', type: 'text' as const }, ] beforeAll(async () => { const config = buildTestConfig({ admin: { user: 'users' }, collections: [ // a project collection with drafts and Payload's open read rule { slug: 'open-pages', access: { read: () => true }, fields: pageFields, versions: { drafts: true } }, // the same with the exported rule { slug: 'guarded-pages', access: { read: readPublished(), readVersions: readPublished() }, fields: pageFields, versions: { drafts: true } }, { slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iawlb-http-media') } }, ], db: testDatabase('iawlb_http'), editor: lexicalEditor(), plugins: [ iapl({ access: { authCollection: 'users' }, globalOverrides: { 'site-integrations': { versions: { drafts: true } } as never }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, twoFactor: false, }), ], secret: 'iawl-ideas-b-http-0123456789', telemetry: false, }) payload = await getPayload({ config }) server = await startPayloadServer(config) for (const role of ['admin', 'editor', 'user'] as const) { await payload.create({ collection: 'users' as never, data: { email: `${role}@example.com`, password: PASSWORD, roles: [role] } as never }) const login = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: `${role}@example.com`, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string } tokens[role] = login.token } await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailTransport: 'smtp', smtpHost: 'smtp.example.com', smtpPassword: SMTP, smtpPort: 587, smtpUser: 'mailer' } as never }) await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpHost: 'smtp2.example.com', smtpPassword: `${SMTP}-2` } as never }) const draft = { _status: 'draft', secretNote: 'draft only', title: 'Nowy cennik (szkic)' } openDraftId = (await payload.create({ collection: 'open-pages' as never, data: draft as never, draft: true, locale: 'pl' })).id guardedDraftId = (await payload.create({ collection: 'guarded-pages' as never, data: draft as never, draft: true, locale: 'pl' })).id guardedPublishedId = (await payload.create({ collection: 'guarded-pages' as never, data: { _status: 'published', secretNote: 'v1', title: 'Cennik' } as never, locale: 'pl' })).id await payload.update({ id: guardedPublishedId, collection: 'guarded-pages' as never, data: { _status: 'published', title: 'Prices' } as never, locale: 'en' }) // a newer draft on top of the published page await payload.update({ id: guardedPublishedId, collection: 'guarded-pages' as never, data: { _status: 'draft', title: 'Cennik — szkic podwyżki' } as never, draft: true, locale: 'pl' }) }, 120_000) afterAll(async () => { await server?.close() await payload?.destroy?.() }) describe('ideas 22/37: versions of Site integrations', () => { test.each(['user', 'editor'] as const)('a %s account cannot list them (REST)', async (as) => { expect((await api('/globals/site-integrations/versions', as)).status).toBe(403) }) test('an anonymous visitor cannot list them (REST)', async () => { expect((await api('/globals/site-integrations/versions')).status).toBe(403) }) test.each(['user', 'editor'] as const)('a %s account gets nothing over GraphQL', async (as) => { const res = await gql('{ versionsSiteIntegrations { docs { id version { smtpHost smtpUser } } } }', as) expect(JSON.stringify(res.data ?? {})).not.toContain('smtp') expect(res.errors?.length).toBeGreaterThan(0) }) test('an admin lists them, with every stored secret masked', async () => { const res = await api('/globals/site-integrations/versions?depth=0&limit=50', 'admin') expect(res.status).toBe(200) const body = JSON.stringify(await res.json()) expect(body).toContain('smtp2.example.com') expect(body).not.toContain(SMTP) expect(body).toContain(SECRET_MASK) }) }) describe('idea 23: drafts over REST and GraphQL', () => { test("Payload's open read rule answers ?draft=true with the draft (the project's rule, shown for the record)", async () => { const res = (await (await api(`/open-pages/${openDraftId}?draft=true`)).json()) as { secretNote?: string } expect(res.secretNote).toBe('draft only') }) test('readPublished(): a never-published page is not found for a visitor, by id, list, draft=true or GraphQL', async () => { expect((await api(`/guarded-pages/${guardedDraftId}`)).status).toBe(404) expect((await api(`/guarded-pages/${guardedDraftId}?draft=true`)).status).toBe(404) const list = (await (await api('/guarded-pages?draft=true&limit=50')).json()) as { docs: { id: unknown }[] } expect(list.docs.map((d) => d.id)).not.toContain(guardedDraftId) const res = await gql(`{ GuardedPages(draft: true, limit: 50) { docs { id title } } }`) expect(JSON.stringify(res.data)).not.toContain('szkic') }) test('readPublished(): a published page shows its published text, never the newer draft', async () => { const res = (await (await api(`/guarded-pages/${guardedPublishedId}?locale=pl`)).json()) as { title?: string } expect(res.title).toBe('Cennik') // asking for the draft: Payload applies the rule to the newest version, which is a draft — not found, no text const asked = await api(`/guarded-pages/${guardedPublishedId}?draft=true&locale=pl`) expect(asked.status).toBe(404) expect(await asked.text()).not.toContain('szkic') // the version list: a visitor sees published versions only expect(await (await api('/guarded-pages/versions?limit=50')).text()).not.toContain('szkic') }) test('readPublished(): an editor still sees the draft', async () => { const res = (await (await api(`/guarded-pages/${guardedPublishedId}?draft=true&locale=pl`, 'editor')).json()) as { title?: string } expect(res.title).toBe('Cennik — szkic podwyżki') expect((await api(`/guarded-pages/${guardedDraftId}`, 'editor')).status).toBe(200) }) test('readPublished(): a plain user account is a visitor', async () => { expect((await api(`/guarded-pages/${guardedDraftId}`, 'user')).status).toBe(404) }) }) describe('ideas 24/25: locales', () => { test('every configured locale is public; locale=all gives the published text of each', async () => { const res = (await (await api(`/guarded-pages/${guardedPublishedId}?locale=all`)).json()) as { title?: Record } expect(res.title).toEqual({ en: 'Prices', pl: 'Cennik' }) }) test('an unknown ?locale= and ?fallback-locale= give the default locale, never a draft', async () => { for (const q of ['locale=xx', 'locale=xx&fallback-locale=en', 'locale=en&fallback-locale=xx']) { const res = (await (await api(`/guarded-pages/${guardedPublishedId}?${q}`)).json()) as { title?: string } expect(['Cennik', 'Prices']).toContain(res.title) expect(await (await api(`/guarded-pages/${guardedPublishedId}?${q}&draft=true`)).text()).not.toContain('szkic') } }) })