Merge local main (1.17.2) into security-a-118
Conflicts resolved by keeping both sides: lockedAnswer + sign-in rules in plugin.ts and switches.ts, IPv6 grouping in the mail service's new per-visitor address count, both built-site specs in e2e:built, docs and skills (reference copies synced). The lockedAnswer suite and the sign-in-answers spec now reach Payload's lock the 1.18.0 way: a spray from 50 IPs, one failure each (one IP alone gets 429 after five). Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* Access callbacks of a project (`cookieScanner.access`, the doctor's `access`), owner's decision Q4, 1.18.0:
|
||||
* still allowed on any truthy answer, but an answer that is not a boolean is reported once per option, so a
|
||||
* project sees it before the next minor version allows only `true`. Every call site goes through one function.
|
||||
*/
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { accessAllowed, resetAccessWarnings } from '../src/modules/shared/accessAnswer.js'
|
||||
|
||||
beforeEach(() => resetAccessWarnings())
|
||||
|
||||
describe('accessAllowed', () => {
|
||||
test('true and false are read as they are, without a word', () => {
|
||||
const warn = vi.fn()
|
||||
expect(accessAllowed('cookieScanner.access', true, { warn })).toBe(true)
|
||||
expect(accessAllowed('cookieScanner.access', false, { warn })).toBe(false)
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test.each([
|
||||
[{ id: 1 }, true, 'an object'],
|
||||
['no', true, 'a string'],
|
||||
[1, true, 'a number'],
|
||||
[null, false, 'null'],
|
||||
[undefined, false, 'a undefined'],
|
||||
])('%j is read as before (%s) and reported once', (answer, allowed, kind) => {
|
||||
const warn = vi.fn()
|
||||
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
|
||||
expect(accessAllowed('doctor.access', answer, { warn })).toBe(allowed)
|
||||
expect(warn).toHaveBeenCalledTimes(1)
|
||||
expect(warn.mock.calls[0][0]).toContain(`doctor.access returned ${kind}`)
|
||||
expect(warn.mock.calls[0][0]).toContain('only `true` allows')
|
||||
})
|
||||
|
||||
test('each option is reported on its own', () => {
|
||||
const warn = vi.fn()
|
||||
accessAllowed('doctor.access', 'x', { warn })
|
||||
accessAllowed('cookieScanner.access', 'x', { warn })
|
||||
expect(warn).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
|
||||
test('every call of a project access callback goes through accessAllowed', () => {
|
||||
const sites = ['src/modules/consent/scanner/endpoint.ts', 'src/modules/consent/scanner/approval.ts', 'src/modules/consent/scanner/crawl/endpoints.ts', 'src/modules/doctor/status.ts']
|
||||
for (const file of sites) {
|
||||
const text = readFileSync(file, 'utf8')
|
||||
const calls = text.match(/await options\.access\(\{ req \}\)/g) ?? []
|
||||
expect(calls.length, file).toBeGreaterThan(0)
|
||||
expect(text.match(/accessAllowed\('[\w.]+', await options\.access\(\{ req \}\)\)/g)?.length, file).toBe(calls.length)
|
||||
}
|
||||
})
|
||||
@@ -159,6 +159,30 @@ describe('forms collection: public read, editor+ write, Emails hidden from plain
|
||||
})
|
||||
})
|
||||
|
||||
describe('form submissions over REST / GraphQL: staff only (1.17.2)', () => {
|
||||
const build = async (forms: object = {}) => {
|
||||
const config = await iapl({ access: { authCollection: 'users' }, forms, i18n, twoFactor: false })(
|
||||
empty({ collections: [{ slug: 'customers', auth: true, fields: [] }] }),
|
||||
)
|
||||
return config.collections?.find((c) => c.slug === 'form-submissions') as CollectionConfig
|
||||
}
|
||||
// the staff check reads the panel's collection from the request's Payload, as in a request
|
||||
const runAs = (fn: Access | undefined, u: unknown) =>
|
||||
(fn as Access)({ req: { payload: { config: { admin: { user: 'users' } } }, user: u } } as never)
|
||||
|
||||
test('a customer account, or nobody, cannot create a submission; any staff role can', async () => {
|
||||
const { access = {} } = await build()
|
||||
expect(runAs(access.create, null)).toBe(false)
|
||||
expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(false)
|
||||
for (const staff of [user, editor, admin]) {expect(runAs(access.create, staff)).toBe(true)}
|
||||
})
|
||||
|
||||
test('formSubmissionOverrides.access.create is the way back', async () => {
|
||||
const { access = {} } = await build({ formSubmissionOverrides: { access: { create: () => true } } })
|
||||
expect(runAs(access.create, { id: 9, collection: 'customers' })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('roles field: the first-register account becomes admin', () => {
|
||||
const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => {
|
||||
const config = await iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/** The plugin's panel actions refuse other origins (adminSameOriginSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { guardAdminEndpoints } from '../src/modules/security/adminSameOrigin.js'
|
||||
import { clearReportedOrigins } from '../src/modules/security/totp/sameOrigin.js'
|
||||
import { ACTIONS, adminSite, SIBLING } from './adminSameOriginSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { action, state } = adminSite()
|
||||
|
||||
describe('adminSameOrigin (default): panel actions only from the site\'s own origin', () => {
|
||||
test('a page on a sibling subdomain, or a cross-site page, gets 403 on every panel action, with the admin cookie', async () => {
|
||||
clearReportedOrigins()
|
||||
for (const path of ACTIONS) {
|
||||
expect([path, (await action(path, SIBLING)).status]).toEqual([path, 403])
|
||||
expect([path, (await action(path, { 'sec-fetch-site': 'cross-site' })).status]).toEqual([path, 403])
|
||||
}
|
||||
// said in the log once per origin, naming this option
|
||||
const lines = state.warn.filter((l) => l.includes('blog.site.example'))
|
||||
expect(lines).toHaveLength(1)
|
||||
expect(lines[0]).toMatch(/adminSameOrigin/)
|
||||
})
|
||||
|
||||
test('the site\'s own page and a script without browser headers still reach them', async () => {
|
||||
const own = await action('/ipal/cookie-approval', { origin: state.server.url, 'sec-fetch-site': 'same-origin' }, '{"ids":[]}')
|
||||
expect(own.status).toBe(200)
|
||||
const script = await action('/ipal/cookie-approval', {}, '{"ids":[]}')
|
||||
expect(script.status).toBe(200)
|
||||
})
|
||||
|
||||
test('a project\'s own endpoint on one of these paths is left as it is', () => {
|
||||
const own = { handler: () => Response.json({ ok: true }), method: 'post' as const, path: '/ipal/test-email' }
|
||||
const config = guardAdminEndpoints({ endpoints: [own] } as never, new Set([own]), undefined)
|
||||
expect(config.endpoints?.[0]).toBe(own)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,22 @@
|
||||
/** adminSameOrigin: false leaves the origin check out (adminSameOriginSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { adminSite, SIBLING } from './adminSameOriginSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { action } = adminSite(false)
|
||||
|
||||
describe('adminSameOrigin: false', () => {
|
||||
test('a request from a sibling subdomain reaches the action, as before 1.17.2', async () => {
|
||||
expect((await action('/ipal/cookie-approval', SIBLING, '{"ids":[]}')).status).toBe(200)
|
||||
})
|
||||
|
||||
test('a value nobody understands stops the start', async () => {
|
||||
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
await expect((async () => iapl({ adminSameOrigin: 0 as never, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin must be/)
|
||||
await expect((async () => iapl({ adminSameOrigin: { origins: 'https://a.example' as never }, i18n } as never)({ collections: [], secret: 'x' } as never))()).rejects.toThrow(/adminSameOrigin\.origins must be a list/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* The plugin's panel actions only from the site's own origin (adminSameOrigin, 1.17.2). Shared by
|
||||
* adminSameOrigin.test.ts (default) and adminSameOriginOff.test.ts (`adminSameOrigin: false`): one Payload per file.
|
||||
* A signed-in administrator's cookie rides on a `text/plain` POST (no CORS preflight) from a page on a sibling
|
||||
* subdomain. Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll } from 'vitest'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
|
||||
import { totp } from './http/totp.js'
|
||||
|
||||
const SECRET = 'JBSWY3DPEHPK3PXP'
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
export const SIBLING = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' }
|
||||
/** Every panel action the rule covers (path under /api). */
|
||||
export const ACTIONS = ['/iapl/mail-relay/connect', '/iapl/mail-relay/disconnect', '/ipal/test-email', '/ipal/cookie-scan', '/ipal/cookie-approval', '/ipal/cookie-crawl']
|
||||
|
||||
export function adminSite(adminSameOrigin?: false) {
|
||||
const state = {} as { cookie: string; payload: Payload; server: TestServer; warn: string[] }
|
||||
beforeAll(async () => {
|
||||
process.env.IAPL_COOKIE_SCAN_URL ??= 'http://127.0.0.1:9'
|
||||
process.env.IAPL_COOKIE_SCAN_TOKEN ??= 'test-token-0123456789abcdef0123456789'
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-admin-origin-media' } }],
|
||||
db: testDatabase('adminorigin'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
...(adminSameOrigin === false ? { adminSameOrigin } : {}),
|
||||
cookieScanner: { crawl: true },
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
state.payload = await getPayload({ config })
|
||||
state.warn = []
|
||||
const warn = state.payload.logger.warn.bind(state.payload.logger)
|
||||
state.payload.logger.warn = ((msg: unknown, ...rest: unknown[]) => {
|
||||
state.warn.push(String(msg))
|
||||
return (warn as (...a: unknown[]) => void)(msg, ...rest)
|
||||
}) as never
|
||||
state.server = await startPayloadServer(config)
|
||||
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'], totpSecret: SECRET } as never })
|
||||
const login = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })
|
||||
const first = cookiesOf(login)
|
||||
const verify = await fetch(`${state.server.url}/api/verify-totp`, { body: JSON.stringify({ token: totp(SECRET) }), headers: { 'content-type': 'application/json', cookie: first.join('; ') }, method: 'POST' })
|
||||
state.cookie = [...first, ...cookiesOf(verify)].join('; ')
|
||||
}, 120_000)
|
||||
afterAll(async () => {
|
||||
await state.server?.close()
|
||||
await state.payload?.destroy?.()
|
||||
})
|
||||
/** A POST as a foreign page can send it: text/plain, the admin's cookie. */
|
||||
const action = (path: string, headers: Record<string, string>, body = '{"to":"[email protected]"}') =>
|
||||
fetch(`${state.server.url}/api${path}`, { body, headers: { 'content-type': 'text/plain', cookie: state.cookie, ...headers }, method: 'POST', signal: AbortSignal.timeout(20_000) })
|
||||
return { action, state }
|
||||
}
|
||||
@@ -168,7 +168,7 @@ describe('server render', () => {
|
||||
test('firstPaint={false}: nothing in the HTML, as before 1.17.0', () => {
|
||||
const html = renderToString(tree({ banner: { firstPaint: false } }))
|
||||
expect(html).not.toContain('data-ipal="banner"')
|
||||
expect(html).not.toContain('<script')
|
||||
expect(html).not.toContain('data-ipal="banner-script"')
|
||||
})
|
||||
|
||||
test('nonce: from the provider, or the banner prop', () => {
|
||||
@@ -444,9 +444,11 @@ describe('tags: nothing earlier than before', () => {
|
||||
const pixels = { clarityProjectId: 'clar', consentMode: 'basic', gtmContainerId: 'GTM-TEST', metaPixelId: '123' }
|
||||
const layer = () => [...((window.dataLayer ?? []))].map((entry) => (Object.prototype.toString.call(entry) === '[object Arguments]' ? Array.from(entry as ArrayLike<unknown>) : entry))
|
||||
|
||||
test('the server HTML holds one script, the banner one, and it names no tag', () => {
|
||||
test("the server HTML holds two scripts, the banner's and the cookie button's (1.17.2), and neither names a tag", () => {
|
||||
const html = renderToString(tree({ analytics: pixels }))
|
||||
expect(html.match(/<script/g)).toHaveLength(1)
|
||||
expect(html.match(/<script[^>]*data-ipal="(?:banner|cookie-button)-script"/g)).toHaveLength(2)
|
||||
expect(html.match(/<script/g)).toHaveLength(2)
|
||||
expect(html).not.toMatch(/createElement\(["']script|\.src\s*=|fetch\(|XMLHttpRequest|dataLayer|document\.cookie\s*=[^=]/)
|
||||
expect(html).not.toMatch(/googletagmanager|facebook|clarity|GTM-TEST/)
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
// @vitest-environment happy-dom
|
||||
/**
|
||||
* Where <CookieButton> sits (1.17.2): the bottom corner of the window, always. It never moves — not above the
|
||||
* footer, not at the end of the page. So that it covers nothing there, the footer gets room under its last row
|
||||
* while the button is shown (measured, only what is missing). The placement before 1.17.2 stays available.
|
||||
*/
|
||||
import { act, createElement, type ReactElement } from 'react'
|
||||
import { createRoot, hydrateRoot, type Root } from 'react-dom/client'
|
||||
import { renderToString } from 'react-dom/server'
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { ConsentProvider } from '../src/modules/consent/ConsentContext.js'
|
||||
import { resetConsentStore } from '../src/modules/consent/consentStore.js'
|
||||
import { COOKIE_BUTTON_AVOID, CookieButton } from '../src/modules/consent/CookieButton.js'
|
||||
import { COOKIE_BUTTON_RESERVE, COOKIE_BUTTON_SPACE_ATTRIBUTE, reserveCookieButtonSpace } from '../src/modules/consent/cookieButtonSpace.js'
|
||||
import { CONSENT_FALLBACK } from '../src/modules/consent/getConsentTexts.js'
|
||||
import { CONSENT_COOKIE, serializeConsent } from '../src/modules/consent/storage.js'
|
||||
|
||||
const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement
|
||||
|
||||
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
type Box = { bottom: number; left: number; right: number; top: number }
|
||||
const box = (top: number, bottom: number, left = 16, right = 60): Box => ({ bottom, left, right, top })
|
||||
const rect = (r: Box) => ({ ...r, height: r.bottom - r.top, width: r.right - r.left, x: r.left, y: r.top }) as DOMRect
|
||||
/** The button's place in an 800 px high window: 44 px, 16 px from the bottom and the left. Zone to keep free: 68 px. */
|
||||
const REST = box(740, 784)
|
||||
const ZONE = 800 - 740 + 8
|
||||
const NONE = box(0, 0, 0, 0)
|
||||
|
||||
/** A fake layout: boxes per element, text boxes per element whose text they are, own bottom padding per element. */
|
||||
let boxes: Map<Element, Box>
|
||||
let page: { height: number; scrollY: number }
|
||||
|
||||
const place = (el: Element, r: Box) => (boxes.set(el, r), el)
|
||||
const add = (html: string, parent: Element = document.body) => {
|
||||
const holder = document.createElement('div')
|
||||
holder.innerHTML = html
|
||||
const el = holder.firstElementChild!
|
||||
parent.appendChild(el)
|
||||
return el as HTMLElement
|
||||
}
|
||||
const liveCookies = () => document.cookie.split('; ').filter((c) => c.split('=')[1])
|
||||
const clearCookies = () => {
|
||||
for (const c of document.cookie.split('; ')) {
|
||||
if (c.split('=')[0]) {document.cookie = `${c.split('=')[0]}=;path=/;max-age=0`}
|
||||
}
|
||||
}
|
||||
const decide = () => {
|
||||
document.cookie = `${CONSENT_COOKIE}=${serializeConsent({ analytics: false, functional: false, marketing: false, necessary: true })};path=/`
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
clearCookies()
|
||||
resetConsentStore()
|
||||
boxes = new Map()
|
||||
page = { height: 3000, scrollY: 2200 } // scrolled to the end: the page ends at y = 800, the window's bottom edge
|
||||
vi.spyOn(Element.prototype, 'getBoundingClientRect').mockImplementation(function (this: Element) {
|
||||
// the real button, once React has put it in the page
|
||||
if (this.getAttribute('data-ipal') === 'cookie-button') {return rect(REST)}
|
||||
// the probe that stands in for a button that is not there yet
|
||||
if (!boxes.has(this) && (this as HTMLElement).style?.position === 'fixed') {return rect(REST)}
|
||||
return rect(boxes.get(this) ?? NONE)
|
||||
})
|
||||
vi.spyOn(Range.prototype, 'getClientRects').mockImplementation(function (this: Range) {
|
||||
const parent = this.startContainer.parentElement
|
||||
return [rect((parent && boxes.get(parent)) ?? NONE)] as unknown as DOMRectList
|
||||
})
|
||||
vi.spyOn(window, 'innerHeight', 'get').mockReturnValue(800)
|
||||
vi.spyOn(window, 'scrollY', 'get').mockImplementation(() => page.scrollY)
|
||||
vi.spyOn(document.documentElement, 'scrollHeight', 'get').mockImplementation(() => page.height)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })
|
||||
document.body.innerHTML = ''
|
||||
document.body.removeAttribute('style')
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
/** A footer whose last row (a link) ends `gap` px above the end of the page, in the button's corner or elsewhere. */
|
||||
function footer({ gap = 20, left = 30, padding = '' }: { gap?: number; left?: number; padding?: string } = {}) {
|
||||
const el = add(`<footer${padding ? ` style="padding-bottom:${padding}"` : ''}><p>© Example</p><a href="/x">Instagram</a></footer>`)
|
||||
place(el, box(500, 800, 0, 390))
|
||||
place(el.querySelector('p')!, box(700, 720, 200, 380)) // text elsewhere on the row above
|
||||
place(el.querySelector('a')!, box(800 - gap - 20, 800 - gap, left, left + 90))
|
||||
return el
|
||||
}
|
||||
const button = () => place(add('<button style="position:fixed">cookies</button>'), REST) as HTMLElement
|
||||
const reserve = (options: object = {}) => reserveCookieButtonSpace({ button: button(), selector: COOKIE_BUTTON_RESERVE, side: 'left', ...options })
|
||||
|
||||
describe('reserveCookieButtonSpace', () => {
|
||||
test('a link in the corner, 20 px above the end of the page: the footer gets the 48 px that are missing', () => {
|
||||
const el = footer()
|
||||
expect(reserve()).toBe(ZONE - 20)
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(true)
|
||||
})
|
||||
|
||||
test("the footer's own bottom padding counts: only the difference is added, and it is put back on release", () => {
|
||||
const el = footer({ gap: 32, padding: '32px' })
|
||||
expect(reserve()).toBe(ZONE - 32)
|
||||
expect(el.style.paddingBottom).toBe('68px') // 32 own + 36
|
||||
expect(reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(0)
|
||||
expect(el.style.paddingBottom).toBe('32px')
|
||||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||||
})
|
||||
|
||||
test('enough room already (a project with a generous footer): nothing is added, nothing is touched', () => {
|
||||
const el = footer({ gap: 80, padding: '80px' })
|
||||
expect(reserve()).toBe(0)
|
||||
expect(el.style.paddingBottom).toBe('80px')
|
||||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||||
})
|
||||
|
||||
test('nothing in the corner (the row is on the other side): no room', () => {
|
||||
const el = footer({ left: 250 })
|
||||
expect(reserve()).toBe(0)
|
||||
expect(el.style.paddingBottom).toBe('')
|
||||
})
|
||||
|
||||
test('side="right": the other corner is measured', () => {
|
||||
footer({ left: 250 })
|
||||
const right = place(add('<button style="position:fixed">cookies</button>'), box(740, 784, 330, 374)) as HTMLElement
|
||||
expect(reserveCookieButtonSpace({ button: right, selector: COOKIE_BUTTON_RESERVE, side: 'right' })).toBe(48)
|
||||
})
|
||||
|
||||
test('called again and again (resize, late content): the same room, never added twice', () => {
|
||||
const el = footer()
|
||||
const b = button()
|
||||
for (let i = 0; i < 4; i++) {expect(reserveCookieButtonSpace({ button: b, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(48)}
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
})
|
||||
|
||||
test('several footers (an article footer first): the last one on the page', () => {
|
||||
const article = place(add('<article><footer><a href="/a">author</a></footer></article>').querySelector('footer')!, box(300, 340, 0, 390)) as HTMLElement
|
||||
const el = footer()
|
||||
reserve()
|
||||
expect(article.style.paddingBottom).toBe('')
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
})
|
||||
|
||||
test('no footer on the page: <body> gets what its own padding does not cover', () => {
|
||||
expect(reserve()).toBe(ZONE)
|
||||
expect(document.body.style.paddingBottom).toBe('68px')
|
||||
reserveCookieButtonSpace({ release: true, selector: COOKIE_BUTTON_RESERVE, side: 'left' })
|
||||
expect(document.body.style.paddingBottom).toBe('')
|
||||
})
|
||||
|
||||
test('a selector of your own', () => {
|
||||
footer()
|
||||
const bar = place(add('<div class="legal"><a href="/t">Terms</a></div>'), box(760, 800, 0, 390)) as HTMLElement
|
||||
place(bar.querySelector('a')!, box(770, 790, 20, 80))
|
||||
expect(reserve({ selector: '.legal' })).toBe(ZONE - 10)
|
||||
expect(bar.style.paddingBottom).toBe('58px')
|
||||
expect(document.querySelector('footer')!.style.paddingBottom).toBe('')
|
||||
})
|
||||
|
||||
test('--ipal-cookie-button-space: the project sets the amount; 0 = none', () => {
|
||||
const el = footer()
|
||||
el.style.setProperty('--ipal-cookie-button-space', '5rem')
|
||||
reserve()
|
||||
expect(el.style.paddingBottom).toBe('calc(0px + 5rem)')
|
||||
el.style.setProperty('--ipal-cookie-button-space', '0px')
|
||||
expect(reserve()).toBe(0)
|
||||
expect(el.style.paddingBottom).toBe('')
|
||||
el.style.setProperty('--ipal-cookie-button-space', '0')
|
||||
expect(reserve()).toBe(0)
|
||||
})
|
||||
|
||||
test('a button the project placed in the flow (not fixed) covers nothing: no room', () => {
|
||||
const el = footer()
|
||||
const inFlow = place(add('<button>cookies</button>'), REST) as HTMLElement
|
||||
expect(reserveCookieButtonSpace({ button: inFlow, selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(0)
|
||||
expect(el.style.paddingBottom).toBe('')
|
||||
})
|
||||
|
||||
test('before the button exists: the default button is measured with a probe that leaves no trace', () => {
|
||||
const el = footer()
|
||||
const nodes = document.body.childElementCount
|
||||
expect(reserveCookieButtonSpace({ selector: COOKIE_BUTTON_RESERVE, side: 'left' })).toBe(48)
|
||||
expect(document.body.childElementCount).toBe(nodes)
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
})
|
||||
|
||||
test('sheet mode (before hydration): the element is not touched; the next plain call moves the room onto it', () => {
|
||||
const wrap = add('<div><span>x</span></div>')
|
||||
const el = footer()
|
||||
wrap.appendChild(el)
|
||||
expect(reserveCookieButtonSpace({ selector: COOKIE_BUTTON_RESERVE, sheet: true, side: 'left' })).toBe(48)
|
||||
expect(el.getAttribute('style')).toBeNull()
|
||||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||||
expect(document.adoptedStyleSheets).toHaveLength(1)
|
||||
expect(document.adoptedStyleSheets[0].cssRules[0].cssText.replace(/\s+/g, ' ')).toMatch(/^body > div:nth-child\(\d+\) > footer:nth-child\(2\) ?\{ ?padding-bottom: 48px !important;? ?\}$/)
|
||||
reserve()
|
||||
expect(document.adoptedStyleSheets).toHaveLength(0)
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
})
|
||||
})
|
||||
|
||||
describe('<CookieButton>', () => {
|
||||
let container: HTMLDivElement
|
||||
let root: Root | undefined
|
||||
let errors: ReturnType<typeof vi.spyOn>
|
||||
|
||||
const cookieButton = () => document.querySelector<HTMLButtonElement>('[data-ipal="cookie-button"]')
|
||||
const frame = () => act(() => new Promise((resolve) => setTimeout(resolve, 40)))
|
||||
const tree = (props: object = {}, provider: object = {}) => h(ConsentProvider, { texts: CONSENT_FALLBACK, ...provider }, h(CookieButton, props))
|
||||
const mount = async (props: object = {}) => {
|
||||
act(() => {
|
||||
root = createRoot(container)
|
||||
root.render(tree(props))
|
||||
})
|
||||
await frame()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
errors = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
if (root) {act(() => root!.unmount())}
|
||||
root = undefined
|
||||
})
|
||||
|
||||
test('default: fixed in the bottom corner with the safe-area insets, below dialogs, a labelled button', async () => {
|
||||
decide()
|
||||
await mount()
|
||||
const style = cookieButton()!.style
|
||||
expect(style.position).toBe('fixed')
|
||||
expect(style.bottom).toBe('calc(var(--ipal-cookie-button-offset, 1rem) + env(safe-area-inset-bottom, 0px))')
|
||||
expect(style.left).toBe('calc(var(--ipal-cookie-button-inset, 1rem) + env(safe-area-inset-left, 0px))')
|
||||
expect(style.zIndex).toBe('var(--ipal-z-header, 40)')
|
||||
expect(cookieButton()!.getAttribute('aria-label')).toBe(CONSENT_FALLBACK.settingsTitle)
|
||||
expect(cookieButton()!.type).toBe('button')
|
||||
})
|
||||
|
||||
test('it never moves: footer in view, scrolling, the end of the page with a link under it', async () => {
|
||||
decide()
|
||||
footer()
|
||||
await mount()
|
||||
for (const y of [0, 1000, 2200]) {
|
||||
page.scrollY = y
|
||||
window.dispatchEvent(new Event('scroll'))
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
await frame()
|
||||
expect(cookieButton()!.style.transform).toBe('')
|
||||
}
|
||||
})
|
||||
|
||||
test('the room is there while the button is shown, and goes when the banner is reopened or the button unmounts', async () => {
|
||||
decide()
|
||||
const el = footer()
|
||||
await mount()
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
act(() => cookieButton()!.click()) // reopens the banner: no button, no room
|
||||
expect(cookieButton()).toBeNull()
|
||||
expect(el.style.paddingBottom).toBe('')
|
||||
expect(el.hasAttribute(COOKIE_BUTTON_SPACE_ATTRIBUTE)).toBe(false)
|
||||
})
|
||||
|
||||
test('no decision yet: no button, no room', async () => {
|
||||
const el = footer()
|
||||
await mount()
|
||||
expect(cookieButton()).toBeNull()
|
||||
expect(el.style.paddingBottom).toBe('')
|
||||
expect(liveCookies()).toEqual([])
|
||||
})
|
||||
|
||||
test('reserve={false}: the button, no room', async () => {
|
||||
decide()
|
||||
const el = footer()
|
||||
await mount({ reserve: false })
|
||||
expect(cookieButton()).not.toBeNull()
|
||||
expect(el.style.paddingBottom).toBe('')
|
||||
})
|
||||
|
||||
test('avoid={COOKIE_BUTTON_AVOID}: the placement before 1.17.2 — above the footer, and no room', async () => {
|
||||
decide()
|
||||
const el = footer()
|
||||
await mount({ avoid: COOKIE_BUTTON_AVOID })
|
||||
expect(cookieButton()!.style.transform).toBe('translateY(-300px)')
|
||||
expect(el.style.paddingBottom).toBe('')
|
||||
})
|
||||
|
||||
test('avoid={false} (sites that set it): stays in the corner, with the room', async () => {
|
||||
decide()
|
||||
const el = footer()
|
||||
await mount({ avoid: false })
|
||||
expect(cookieButton()!.style.transform).toBe('')
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
})
|
||||
|
||||
describe('before the first paint (static HTML, the same for every visitor)', () => {
|
||||
const scriptOf = (html: string) => /<script[^>]*data-ipal="cookie-button-script"[^>]*>(?<code>.*?)<\/script>/s.exec(html)?.groups?.code
|
||||
|
||||
test('the server HTML carries a script instead of the button; nonce from the provider', () => {
|
||||
const html = renderToString(tree({}, { nonce: 'n-1' }))
|
||||
expect(html).not.toContain('data-ipal="cookie-button"')
|
||||
expect(html).toMatch(/<script[^>]*nonce="n-1"/)
|
||||
expect(scriptOf(html)).toContain('footer, [role=\\"contentinfo\\"]')
|
||||
expect(scriptOf(html)).not.toContain('</script')
|
||||
})
|
||||
|
||||
test('no script when there is nothing to prepare: reserve off, old placement, own classes, server-read cookie', () => {
|
||||
for (const props of [{ reserve: false }, { avoid: COOKIE_BUTTON_AVOID }, { className: 'mine' }]) {
|
||||
expect(renderToString(tree(props))).not.toContain('<script')
|
||||
}
|
||||
expect(renderToString(tree({}, { cookieValue: null }))).not.toContain('<script')
|
||||
})
|
||||
|
||||
test('a visitor who decided: the room is made by the script, the markup stays as the server sent it; no decision: nothing', () => {
|
||||
const html = renderToString(tree())
|
||||
const el = footer()
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
new Function(scriptOf(html)!)()
|
||||
expect(document.adoptedStyleSheets).toHaveLength(0)
|
||||
decide()
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
new Function(scriptOf(html)!)()
|
||||
expect(document.adoptedStyleSheets).toHaveLength(1)
|
||||
expect(document.adoptedStyleSheets[0].cssRules[0].cssText).toContain('48px')
|
||||
expect(el.getAttribute('style')).toBeNull()
|
||||
})
|
||||
|
||||
test('hydration: no warning; the room moves from the script’s style sheet onto the footer, the same size', async () => {
|
||||
const el = footer()
|
||||
decide()
|
||||
const node = tree()
|
||||
const html = renderToString(node)
|
||||
container.innerHTML = html
|
||||
// eslint-disable-next-line @typescript-eslint/no-implied-eval
|
||||
new Function(scriptOf(html)!)()
|
||||
act(() => {
|
||||
root = hydrateRoot(container, node)
|
||||
})
|
||||
await frame()
|
||||
expect(errors).not.toHaveBeenCalled()
|
||||
expect(cookieButton()).not.toBeNull()
|
||||
expect(document.querySelector('[data-ipal="cookie-button-script"]')).toBeNull()
|
||||
expect(document.adoptedStyleSheets).toHaveLength(0)
|
||||
expect(el.style.paddingBottom).toBe('48px')
|
||||
})
|
||||
})
|
||||
})
|
||||
+26
-1
@@ -193,6 +193,9 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
|
||||
expect(await run(build('{ serverURL: process.env.NEXT_PUBLIC_SERVER_URL, plugins: [] }'), ['csrf-empty'])).toEqual([])
|
||||
expect(await run(build("{ csrf: ['https://site.example'], plugins: [] }"), ['csrf-empty'])).toEqual([])
|
||||
expect(await run('// not a Payload config', ['csrf-empty'])).toEqual([])
|
||||
// deep (the running config, 1.17.2): it wins over the file — serverURL may come from a spread or a helper
|
||||
expect(await run(build('{ ...base, plugins: [] }'), ['csrf-empty'], { originKnown: false })).toEqual(['csrf-empty:warning'])
|
||||
expect(await run(build("{ plugins: [iapl({ access: { authCollection: 'users' } })] }"), ['csrf-empty'], { originKnown: true })).toEqual([])
|
||||
})
|
||||
|
||||
test('open-signup: an auth collection anyone can register in is said, as info', async () => {
|
||||
@@ -203,6 +206,18 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
|
||||
expect(await run(cfg, ['open-signup'])).toEqual([])
|
||||
})
|
||||
|
||||
test('visitor-writes: one warning per entity a visitor account may write, its operations named', async () => {
|
||||
const cfg = "iapl({ access: { authCollection: 'users' } })"
|
||||
const report = await doctor(project({ ...base(), 'src/payload.config.ts': cfg }), ['visitor-writes'], { deepStatus: { visitorWrites: ['globals/header:update', 'pages:create', 'pages:delete', 'pages:update'] } })
|
||||
expect(report.findings.map((f) => `${f.severity}: ${f.message}`)).toEqual([
|
||||
'warning: an account of a visitor login collection may update the global "header"',
|
||||
'warning: an account of a visitor login collection may create, delete, update in "pages"',
|
||||
])
|
||||
expect(await run(cfg, ['visitor-writes'], { visitorWrites: [] })).toEqual([])
|
||||
expect(await run(cfg, ['visitor-writes'], { visitorWrites: null })).toEqual([])
|
||||
expect(await run(cfg, ['visitor-writes'])).toEqual([])
|
||||
})
|
||||
|
||||
test('staff-accounts-open: a staff collection an account of another collection may write to is an error', async () => {
|
||||
const cfg = "iapl({ access: { authCollection: 'users' } })"
|
||||
expect(await run(cfg, ['staff-accounts-open'], { staffOpenToOthers: ['agents:delete', 'agents:update', 'users:create'] })).toEqual(['staff-accounts-open:error', 'staff-accounts-open:error', 'staff-accounts-open:error'])
|
||||
@@ -230,6 +245,16 @@ describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () =
|
||||
expect(fromEnv.turnstileSecretFromEnv).toBe(true)
|
||||
expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/)
|
||||
})
|
||||
|
||||
test('the deep status says whether the running config knows its own origin (serverURL or csrf), never the value', async () => {
|
||||
const fake = (extra: object) => ({ config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [], ...extra } })
|
||||
expect((await collectDoctorStatus(fake({}) as never)).originKnown).toBe(false)
|
||||
expect((await collectDoctorStatus(fake({ serverURL: '' }) as never)).originKnown).toBe(false)
|
||||
const known = await collectDoctorStatus(fake({ serverURL: 'https://secret-host.example' }) as never)
|
||||
expect(known.originKnown).toBe(true)
|
||||
expect(JSON.stringify(known)).not.toMatch(/secret-host/)
|
||||
expect((await collectDoctorStatus(fake({ csrf: ['https://site.example'] }) as never)).originKnown).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('helpers', () => {
|
||||
@@ -529,7 +554,7 @@ describe('security and deep status', () => {
|
||||
}
|
||||
const status = await collectDoctorStatus(payload as never)
|
||||
expect(status).toMatchObject({ pendingCookies: 4, usersWithout2fa: 2 })
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
|
||||
expect(Object.keys(status).sort()).toEqual(['mail', 'node', 'openSignUp', 'originKnown', 'pendingCookies', 'plugin', 'staffOnOwnRoles', 'staffOpenToOthers', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa', 'visitorWrites'])
|
||||
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
|
||||
expect(status.mail).toBeNull() // no Site integrations global in this config
|
||||
})
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
/**
|
||||
* Drafts as related documents (owner's decision Q5, 1.18.0): a block, a menu or a System pages link that points at a
|
||||
* page never published no longer brings that page's title, slug and text into what the public helpers answer.
|
||||
* `draftRelations: 'keep'` and a preview (`draft: true`) keep the old behaviour.
|
||||
* Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
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 { withoutDraftRelations } from '../src/modules/content/draftRelations.js'
|
||||
import { getArchiveEntries } from '../src/modules/content/getArchiveEntries.js'
|
||||
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
describe('withoutDraftRelations', () => {
|
||||
const draft = { id: 2, _status: 'draft', title: 'Secret' }
|
||||
const live = { id: 1, _status: 'published', title: 'Live' }
|
||||
|
||||
test('drops a draft related document: null alone, removed from a list, value null in a polymorphic one', () => {
|
||||
const doc = { id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live, draft], one: draft, poly: { relationTo: 'pages', value: draft } }] }
|
||||
expect(withoutDraftRelations(doc)).toEqual({ id: 9, _status: 'published', layout: [{ blockType: 'cards', items: [live], one: null, poly: { relationTo: 'pages', value: null } }] })
|
||||
})
|
||||
|
||||
test('the document itself, ids, uploads and documents without _status are left alone; nothing is mutated', () => {
|
||||
const doc = { id: 3, _status: 'draft', image: { id: 5, url: '/m.png' }, page: 2, pages: [1, 2] }
|
||||
expect(withoutDraftRelations(doc)).toBe(doc)
|
||||
const nested = { a: { b: draft } }
|
||||
const out = withoutDraftRelations(nested)
|
||||
expect(out).toEqual({ a: { b: null } })
|
||||
expect(nested.a.b).toBe(draft)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the public helpers on a real database', () => {
|
||||
let payload: Payload
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
collections: [
|
||||
{
|
||||
slug: 'pages',
|
||||
access: { read: () => true },
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'slug', type: 'text', localized: true },
|
||||
{ name: 'related', type: 'relationship', relationTo: 'pages' },
|
||||
{ name: 'list', type: 'relationship', hasMany: true, relationTo: 'pages' },
|
||||
{ name: 'layout', type: 'blocks', blocks: [{ slug: 'link', fields: [{ name: 'page', type: 'relationship', relationTo: ['pages', 'posts'] }] }] },
|
||||
],
|
||||
versions: { drafts: true },
|
||||
},
|
||||
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }, { name: 'see', type: 'relationship', relationTo: 'pages' }], versions: { drafts: true } },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-draft-relations') } },
|
||||
],
|
||||
db: testDatabase('draft_relations'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, content: { collections: [{ slug: 'posts' }] }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail: { relay: false }, pages: { slug: 'pages' }, twoFactor: false })],
|
||||
secret: 'draft-relations-0123456789-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
const secret = await payload.create({ collection: 'pages' as never, data: { slug: 'tajna', _status: 'draft', title: 'Secret price list' } as never, draft: true })
|
||||
const live = await payload.create({ collection: 'pages' as never, data: { slug: 'o-nas', _status: 'published', title: 'About' } as never })
|
||||
await payload.create({
|
||||
collection: 'pages' as never,
|
||||
data: { slug: 'start', _status: 'published', layout: [{ blockType: 'link', page: { relationTo: 'pages', value: secret.id } }], list: [live.id, secret.id], related: secret.id, title: 'Start' } as never,
|
||||
})
|
||||
await payload.create({ collection: 'posts' as never, data: { slug: 'wpis', _status: 'published', see: secret.id, title: 'Post' } as never })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
const start = async (options: Record<string, unknown> = {}) => (await resolveRoute({ locale: 'pl', payload, segments: ['start'], ...options }))?.doc as Record<string, unknown>
|
||||
|
||||
test('resolveRoute: the page answers without the draft it points at (single, list, polymorphic block)', async () => {
|
||||
const doc = await start()
|
||||
expect(doc.related).toBeNull()
|
||||
expect((doc.list as { title: string }[]).map((p) => p.title)).toEqual(['About'])
|
||||
expect((doc.layout as { page: { value: unknown } }[])[0].page.value).toBeNull()
|
||||
expect(JSON.stringify(doc)).not.toContain('Secret price list')
|
||||
})
|
||||
|
||||
test("draftRelations: 'keep' and a preview answer them as before", async () => {
|
||||
for (const options of [{ draftRelations: 'keep' }, { draft: true }]) {
|
||||
expect(JSON.stringify(await start(options))).toContain('Secret price list')
|
||||
}
|
||||
})
|
||||
|
||||
test('getArchiveEntries: an entry without the draft it points at; keep as before', async () => {
|
||||
const hidden = await getArchiveEntries({ collection: 'posts', locale: 'pl', payload })
|
||||
expect((hidden.docs[0] as { see: unknown }).see).toBeNull()
|
||||
const kept = await getArchiveEntries({ collection: 'posts', draftRelations: 'keep', locale: 'pl', payload })
|
||||
expect(JSON.stringify(kept.docs)).toContain('Secret price list')
|
||||
})
|
||||
})
|
||||
@@ -140,7 +140,11 @@ describe('idea 23: drafts over REST and GraphQL', () => {
|
||||
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')
|
||||
const versions = await api('/guarded-pages/versions?limit=50&locale=pl')
|
||||
expect(versions.status).toBe(200) // 1.17.1 answered 500 here: the check below alone passed on an error page
|
||||
const list = await versions.text()
|
||||
expect(list).toContain('Cennik')
|
||||
expect(list).not.toContain('szkic')
|
||||
})
|
||||
|
||||
test('readPublished(): an editor still sees the draft', async () => {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* Payload's job queue over HTTP (1.17.2, IAWL idea 35, owner's Q2): when the project writes no `jobs.access.run`,
|
||||
* only an admin signed in with the second factor, or `Authorization: Bearer <CRON_SECRET>`, may run it. Payload's
|
||||
* default let any signed-in account of any auth collection run the queue — a customer included.
|
||||
*/
|
||||
import type { Config, SanitizedConfig } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { jobsRunNotice, withJobsRunAccess } from '../src/modules/security/jobsAccess.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const SECRET = 'a-cron-secret-of-32-characters!!'
|
||||
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
|
||||
const project = (jobs?: Config['jobs']): Config =>
|
||||
({
|
||||
collections: [{ slug: 'customers', auth: true, fields: [] }, { slug: 'media', fields: [], upload: true }],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' } }),
|
||||
jobs: { ...jobs, tasks: [{ slug: 'noop', handler: () => ({ output: {} }) }] },
|
||||
secret: 'jobs-access-test',
|
||||
telemetry: false,
|
||||
}) as unknown as Config
|
||||
|
||||
const build = (jobs?: Config['jobs'], options: object = {}) =>
|
||||
buildTestConfig({ ...project(jobs), plugins: [iapl({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)] })
|
||||
|
||||
/** Calls the sanitized run rule the way Payload's run endpoint does. */
|
||||
const runAs = async (config: SanitizedConfig, user: unknown, authorization?: string) => {
|
||||
const req = { headers: new Headers(authorization ? { authorization } : {}), payload: { config }, user }
|
||||
return Boolean(await (config.jobs.access!.run as (a: { req: unknown }) => unknown)({ req }))
|
||||
}
|
||||
|
||||
const admin = { id: 1, collection: 'users', roles: ['admin'] }
|
||||
const editor = { id: 2, collection: 'users', roles: ['editor'] }
|
||||
const customer = { id: 3, collection: 'customers' }
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('jobs.access.run when the project writes none', () => {
|
||||
test('an admin, or the cron secret; not an editor, a customer or nobody', async () => {
|
||||
vi.stubEnv('CRON_SECRET', SECRET)
|
||||
const config = await build()
|
||||
expect(await runAs(config, admin)).toBe(true)
|
||||
expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true)
|
||||
expect(await runAs(config, null)).toBe(false)
|
||||
expect(await runAs(config, customer)).toBe(false)
|
||||
expect(await runAs(config, editor)).toBe(false)
|
||||
expect(await runAs(config, null, 'Bearer wrong-secret-wrong-secret')).toBe(false)
|
||||
expect(await runAs(config, customer, SECRET)).toBe(false) // without "Bearer "
|
||||
}, 30_000)
|
||||
|
||||
test('a missing or short secret never matches', async () => {
|
||||
vi.stubEnv('CRON_SECRET', 'short')
|
||||
const config = await build()
|
||||
expect(await runAs(config, null, 'Bearer short')).toBe(false)
|
||||
vi.stubEnv('CRON_SECRET', '')
|
||||
expect(await runAs(config, null, 'Bearer ')).toBe(false)
|
||||
}, 30_000)
|
||||
|
||||
test('secretVar names another variable', async () => {
|
||||
vi.stubEnv('MY_JOBS_SECRET', SECRET)
|
||||
const config = await build(undefined, { jobsRunAccess: { secretVar: 'MY_JOBS_SECRET' } })
|
||||
expect(await runAs(config, null, `Bearer ${SECRET}`)).toBe(true)
|
||||
}, 30_000)
|
||||
|
||||
test('the project\'s own rule wins; jobsRunAccess: false keeps Payload\'s default', async () => {
|
||||
const own = await build({ access: { run: () => true } })
|
||||
expect(await runAs(own, null)).toBe(true)
|
||||
const payloadDefault = await build(undefined, { jobsRunAccess: false })
|
||||
expect(await runAs(payloadDefault, customer)).toBe(true) // Payload: any signed-in account
|
||||
}, 30_000)
|
||||
|
||||
test('a config without jobs gets the rule too (Payload turns the queue on for scheduled publishing)', () => {
|
||||
const config = withJobsRunAccess({ secret: 'x' } as Config)
|
||||
expect(typeof config.jobs?.access?.run).toBe('function')
|
||||
expect(withJobsRunAccess({ secret: 'x' } as Config, false).jobs).toBeUndefined()
|
||||
})
|
||||
|
||||
test('at start: a note when the queue is on, the rule is iapl\'s and the secret is missing', () => {
|
||||
const custom = { iapl: { jobsRunDefault: { secretVar: 'CRON_SECRET' } } }
|
||||
vi.stubEnv('CRON_SECRET', '')
|
||||
expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toMatch(/Authorization: Bearer <CRON_SECRET>.*not set/)
|
||||
expect(jobsRunNotice({ custom, jobs: { enabled: false } })).toBeNull()
|
||||
expect(jobsRunNotice({ custom: {}, jobs: { enabled: true } })).toBeNull()
|
||||
vi.stubEnv('CRON_SECRET', SECRET)
|
||||
expect(jobsRunNotice({ custom, jobs: { enabled: true } })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
/** A locked staff account answers like a wrong password, REST and GraphQL (lockedAnswerSuite.ts). 2FA on. */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { gqlLogin, lock, restLogin, state } = lockedAnswerSite()
|
||||
|
||||
describe('accounts.lockedAnswer (default): a locked staff account looks like a wrong password', () => {
|
||||
test('REST: the locked owner, with any password, gets exactly what an invented address gets', async () => {
|
||||
await lock('users', '[email protected]')
|
||||
const invented = await restLogin('users', '[email protected]', 'a-wrong-password')
|
||||
expect(invented.status).toBe(401)
|
||||
expect(await restLogin('users', '[email protected]', 'a-wrong-password')).toEqual(invented)
|
||||
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(invented)
|
||||
expect(invented.body).not.toMatch(/locked/i)
|
||||
// the lock itself is still there
|
||||
const stored = (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: '[email protected]' } } })).docs[0] as { lockUntil?: string }
|
||||
expect(new Date(String(stored.lockUntil)).getTime()).toBeGreaterThan(Date.now())
|
||||
})
|
||||
|
||||
test('GraphQL: the same message, status and error name', async () => {
|
||||
const invented = await gqlLogin('loginUser', '[email protected]', 'a-wrong-password')
|
||||
expect(invented.name).toBe('AuthenticationError')
|
||||
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(invented)
|
||||
})
|
||||
|
||||
test('a visitor collection keeps Payload\'s answer (not staff)', async () => {
|
||||
await lock('customers', '[email protected]', 3)
|
||||
expect((await restLogin('customers', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
|
||||
expect((await gqlLogin('loginCustomer', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
/** A locked staff account answers like a wrong password with 2FA off too (lockedAnswerSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ twoFactor: false })
|
||||
|
||||
describe('accounts.lockedAnswer with twoFactor: false', () => {
|
||||
test('REST and GraphQL answer the locked owner like an invented address', async () => {
|
||||
await lock('users', '[email protected]')
|
||||
expect(await restLogin('users', '[email protected]', PASSWORD)).toEqual(await restLogin('users', '[email protected]', 'x-wrong-password-1'))
|
||||
expect(await gqlLogin('loginUser', '[email protected]', PASSWORD)).toEqual(await gqlLogin('loginUser', '[email protected]', 'x-wrong-password-1'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
/** accounts.lockedAnswer: 'payload' keeps Payload's "locked" answer (lockedAnswerSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { lockedAnswerSite, PASSWORD } from './lockedAnswerSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { gqlLogin, lock, restLogin } = lockedAnswerSite({ lockedAnswer: 'payload' })
|
||||
|
||||
describe("accounts.lockedAnswer: 'payload'", () => {
|
||||
test('the locked owner is told it is locked, REST and GraphQL', async () => {
|
||||
await lock('users', '[email protected]')
|
||||
expect((await restLogin('users', '[email protected]', PASSWORD)).body).toMatch(/locked/i)
|
||||
expect((await gqlLogin('loginUser', '[email protected]', PASSWORD)).name).toBe('LockedAuth')
|
||||
})
|
||||
|
||||
test('a value nobody understands stops the start', async () => {
|
||||
const config = { collections: [], secret: 'x' } as never
|
||||
await expect((async () => iapl({ accounts: { lockedAnswer: 'Payload' as never }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] } } as never)(config))()).rejects.toThrow(/accounts\.lockedAnswer must be one of/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* A locked staff account answers its login exactly like a wrong password (accounts.lockedAnswer, 1.17.2; IAWL
|
||||
* idea 6). Shared by lockedAnswer.test.ts (default, 2FA on), lockedAnswer2faOff.test.ts (2FA off) and
|
||||
* lockedAnswerPayload.test.ts (`lockedAnswer: 'payload'`): one Payload per file.
|
||||
* Database: SQLite in memory, or IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI (test/http/db.ts).
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll } from 'vitest'
|
||||
|
||||
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'
|
||||
|
||||
export const PASSWORD = 'a-long-test-password-1'
|
||||
|
||||
export type Answer = { body: string; status: number }
|
||||
|
||||
export function lockedAnswerSite({ lockedAnswer, twoFactor = true }: { lockedAnswer?: 'payload'; twoFactor?: boolean } = {}) {
|
||||
const state = {} as { payload: Payload; server: TestServer }
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
// a visitor collection with Payload's own lock: not staff, not changed
|
||||
{ slug: 'customers', access: { create: () => true }, auth: { maxLoginAttempts: 3 }, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-locked-answer-media' } },
|
||||
],
|
||||
db: testDatabase('lockedanswer'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
...(lockedAnswer ? { accounts: { lockedAnswer } } : {}),
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false,
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
state.payload = await getPayload({ config })
|
||||
state.server = await startPayloadServer(config)
|
||||
await state.payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['admin'] } as never })
|
||||
await state.payload.create({ collection: 'customers' as never, data: { email: '[email protected]', password: PASSWORD } as never })
|
||||
}, 120_000)
|
||||
afterAll(async () => {
|
||||
await state.server?.close()
|
||||
await state.payload?.destroy?.()
|
||||
})
|
||||
|
||||
const restLogin = async (collection: string, email: string, password: string, ip?: string): Promise<Answer> => {
|
||||
const res = await fetch(`${state.server.url}/api/${collection}/login`, {
|
||||
body: JSON.stringify({ email, password }),
|
||||
headers: { 'content-type': 'application/json', ...(ip ? { 'x-real-ip': ip } : {}) },
|
||||
method: 'POST',
|
||||
})
|
||||
return { body: await res.text(), status: res.status }
|
||||
}
|
||||
const gqlLogin = async (mutation: string, email: string, password: string) => {
|
||||
const res = await fetch(`${state.server.url}/api/graphql`, {
|
||||
body: JSON.stringify({ query: `mutation { ${mutation}(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }),
|
||||
headers: { 'content-type': 'application/json' },
|
||||
method: 'POST',
|
||||
})
|
||||
const body = (await res.json()) as { errors?: { extensions?: { name?: string; statusCode?: number }; message: string }[] }
|
||||
const e = body.errors?.[0]
|
||||
return { name: e?.extensions?.name, message: e?.message, status: res.status, statusCode: e?.extensions?.statusCode }
|
||||
}
|
||||
/**
|
||||
* Locks `email` with wrong passwords. A staff collection: since 1.18.0 (accounts.signInLimit) Payload's lock is at 50
|
||||
* failures and one IP may fail 5 times per address, so the lock comes from a spray of 50 IPs, one failure each. A
|
||||
* visitor collection: Payload's own count (`times`).
|
||||
*/
|
||||
const lock = async (collection: string, email: string, times = 50) => {
|
||||
for (let i = 0; i < times; i++) {await restLogin(collection, email, 'a-wrong-password', `198.51.${100 + Math.floor(i / 250)}.${(i % 250) + 1}`)}
|
||||
}
|
||||
return { gqlLogin, lock, restLogin, state }
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* Cookie settings → Consent version only goes up (owner's decision Q2, 1.17.2). A stored consent counts only under
|
||||
* the version it was given for: a LOWER number made old consent cookies valid again. A save through access control
|
||||
* with a lower number is refused with a message; the Local API with `overrideAccess` may still lower it;
|
||||
* `cookieSettings: { allowLowerPolicyVersion: true }` keeps the old behaviour.
|
||||
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
|
||||
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 { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
import { startPayloadServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
|
||||
async function site(name: string, cookieSettings?: { allowLowerPolicyVersion?: boolean }) {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), `iapl-${name}`) } }],
|
||||
db: testDatabase(name),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, ...(cookieSettings ? { cookieSettings } : {}), i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
|
||||
secret: `${name}-0123456789-0123456789`,
|
||||
telemetry: false,
|
||||
})
|
||||
const payload = await getPayload({ config })
|
||||
const server = await startPayloadServer(config)
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: PASSWORD, roles: ['editor'] } as never })
|
||||
const { token } = (await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: '[email protected]', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }
|
||||
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { policyVersion: 3 } as never })
|
||||
const save = (data: Record<string, unknown>) =>
|
||||
fetch(`${server.url}/api/globals/cookie-settings`, { body: JSON.stringify(data), headers: { authorization: `JWT ${token}`, 'content-type': 'application/json' }, method: 'POST' })
|
||||
const gql = (query: string) =>
|
||||
fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: { authorization: `JWT ${token}`, 'content-type': 'application/json' }, method: 'POST' }).then((r) => r.json() as Promise<{ errors?: { message: string }[] }>)
|
||||
const stored = async () => ((await payload.findGlobal({ slug: 'cookie-settings' as never })) as { policyVersion?: number }).policyVersion
|
||||
return { gql, payload, save, server, stored }
|
||||
}
|
||||
|
||||
describe('by default the consent version only goes up', () => {
|
||||
let s: Awaited<ReturnType<typeof site>>
|
||||
beforeAll(async () => {
|
||||
s = await site('policy_rising')
|
||||
}, 120_000)
|
||||
afterAll(async () => {
|
||||
await s?.server.close()
|
||||
await s?.payload.destroy?.()
|
||||
})
|
||||
|
||||
test('a lower number is refused with the message, and the stored one stays', async () => {
|
||||
const res = await s.save({ policyVersion: 1 })
|
||||
expect(res.status).toBe(400)
|
||||
expect(JSON.stringify(await res.json())).toContain('The consent version cannot go down: it is 3 now')
|
||||
expect(await s.stored()).toBe(3)
|
||||
})
|
||||
|
||||
test('over GraphQL too', async () => {
|
||||
const res = await s.gql('mutation { updateCookieSetting(data: { policyVersion: 2 }) { policyVersion } }')
|
||||
expect(res.errors?.[0]?.message ?? '').toMatch(/invalid|cannot go down/i)
|
||||
expect(await s.stored()).toBe(3)
|
||||
})
|
||||
|
||||
test('the same number, a higher one, and a save that does not send it all pass', async () => {
|
||||
expect((await s.save({ policyVersion: 3 })).status).toBe(200)
|
||||
expect((await s.save({ title: 'Cookies' })).status).toBe(200)
|
||||
expect((await s.save({ policyVersion: 4 })).status).toBe(200)
|
||||
expect(await s.stored()).toBe(4)
|
||||
})
|
||||
|
||||
test('the Local API with access control off may lower it (a script an admin runs)', async () => {
|
||||
await s.payload.updateGlobal({ slug: 'cookie-settings' as never, data: { policyVersion: 2 } as never })
|
||||
expect(await s.stored()).toBe(2)
|
||||
})
|
||||
|
||||
test('the Polish text exists', async () => {
|
||||
const { adminTexts } = await import('../src/modules/admin-i18n/texts/index.js')
|
||||
expect(JSON.stringify(adminTexts)).toContain('Wersji zgody nie można obniżyć')
|
||||
})
|
||||
})
|
||||
|
||||
describe('cookieSettings: { allowLowerPolicyVersion: true } keeps the old behaviour', () => {
|
||||
test('the field has no consent-version rule then, and has it by default', async () => {
|
||||
const { buildCookieSettings } = await import('../src/globals/CookieSettings/index.js')
|
||||
const { policyVersionNeverDown } = await import('../src/globals/CookieSettings/fields.js')
|
||||
const hooksOf = (g: { fields: unknown[] }) =>
|
||||
((g.fields as { hooks?: { beforeValidate?: unknown[] }; name?: string }[]).find((f) => f.name === 'policyVersion')?.hooks?.beforeValidate ?? [])
|
||||
expect(hooksOf(buildCookieSettings())).toContain(policyVersionNeverDown)
|
||||
expect(hooksOf(buildCookieSettings({ allowLowerPolicyVersion: true }))).not.toContain(policyVersionNeverDown)
|
||||
})
|
||||
|
||||
test('iapl() passes the option through', async () => {
|
||||
const { policyVersionNeverDown } = await import('../src/globals/CookieSettings/fields.js')
|
||||
const config = await iapl({ cookieSettings: { allowLowerPolicyVersion: true }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })({ collections: [], secret: 'x' } as never)
|
||||
const g = config.globals!.find((x) => x.slug === 'cookie-settings') as { fields: { hooks?: { beforeValidate?: unknown[] }; name?: string }[] }
|
||||
expect(g.fields.find((f) => f.name === 'policyVersion')?.hooks?.beforeValidate ?? []).not.toContain(policyVersionNeverDown)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* IPv6 is counted per network (1.17.2, IAWL idea 9): a /64 is one client in every limiter of the plugin; a second
|
||||
* counter per /48 when a project turns it on (`setIpv6Grouping({ wide: 48 })`).
|
||||
*/
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
|
||||
import { passRateLimit } from '../src/modules/forms/submitForm.js'
|
||||
import { checkRateLimit, clientIp, consumeRateLimit, ipRateKey, setIpv6Grouping } from '../src/modules/shared/rateLimit.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
let scope = 0
|
||||
const nextScope = () => `ipv6-test-${++scope}`
|
||||
const hex = (n: number) => n.toString(16)
|
||||
|
||||
afterEach(() => setIpv6Grouping())
|
||||
|
||||
describe('ipRateKey', () => {
|
||||
test('one key for every address of a /64, whatever the spelling', () => {
|
||||
const key = ipRateKey('2001:db8:1:2::1')
|
||||
expect(key).toBe('2001:db8:1:2:0:0:0:0/64')
|
||||
for (const a of ['2001:db8:1:2:ffff:ffff:ffff:ffff', '2001:0DB8:0001:0002:0000:0000:0000:0042', '[2001:db8:1:2::9]', '2001:db8:1:2::9%eth0']) {
|
||||
expect([a, ipRateKey(a)]).toEqual([a, key])
|
||||
}
|
||||
expect(ipRateKey('2001:db8:1:3::1')).not.toBe(key)
|
||||
})
|
||||
|
||||
test('IPv4 as it is; an IPv4-mapped IPv6 address is its IPv4; anything else unchanged', () => {
|
||||
expect(ipRateKey('198.51.100.7')).toBe('198.51.100.7')
|
||||
expect(ipRateKey('::ffff:198.51.100.7')).toBe('198.51.100.7')
|
||||
expect(ipRateKey('::ffff:c633:6407')).toBe('198.51.100.7')
|
||||
expect(ipRateKey('')).toBe('')
|
||||
expect(ipRateKey('not-an-ip')).toBe('not-an-ip')
|
||||
for (const bad of ['1::2::3', '2001:db8:1:2:3:4:5:6:7', '12345::1', '::ffff:300.1.1.1', 'to:abcdef', 'a:b']) {expect([bad, ipRateKey(bad)]).toEqual([bad, bad])}
|
||||
expect(ipRateKey('::')).toBe('0:0:0:0:0:0:0:0/64')
|
||||
expect(ipRateKey('256.1.1.1')).toBe('256.1.1.1')
|
||||
})
|
||||
|
||||
test('setIpv6Grouping: per address again, another prefix; nonsense is refused', () => {
|
||||
setIpv6Grouping({ prefix: 128 })
|
||||
expect(ipRateKey('2001:db8::1')).not.toBe(ipRateKey('2001:db8::2'))
|
||||
setIpv6Grouping({ prefix: 56 })
|
||||
expect(ipRateKey('2001:db8:0:ff::1')).toBe(ipRateKey('2001:db8:0:1::1'))
|
||||
expect(() => setIpv6Grouping({ prefix: 0 })).toThrow(/prefix must be/)
|
||||
expect(() => setIpv6Grouping({ prefix: '64' as never })).toThrow(/prefix must be/)
|
||||
expect(() => setIpv6Grouping({ prefix: 48, wide: 56 })).toThrow(/shorter prefix/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the limiters count a /64 as one client', () => {
|
||||
test('consumeRateLimit: fifty addresses of one /64 get five requests, not fifty', async () => {
|
||||
const s = nextScope()
|
||||
let allowed = 0
|
||||
for (let i = 1; i <= 50; i++) {
|
||||
if ((await consumeRateLimit({ key: clientIp(new Headers({ 'x-real-ip': `2001:db8:1:1::${hex(i)}` })), max: 5, scope: s })).ok) {allowed++}
|
||||
}
|
||||
expect(allowed).toBe(5)
|
||||
// another /64 of the same /48 is another client (the wide counter is off by default)
|
||||
expect((await consumeRateLimit({ key: '2001:db8:1:2::1', max: 5, scope: s })).ok).toBe(true)
|
||||
})
|
||||
|
||||
test('checkRateLimit (the synchronous one) too', () => {
|
||||
const s = nextScope()
|
||||
const results = Array.from({ length: 8 }, (_, i) => checkRateLimit({ key: `2001:db8:9:9::${hex(i + 1)}`, max: 3, scope: s }))
|
||||
expect(results.filter(Boolean)).toHaveLength(3)
|
||||
})
|
||||
|
||||
test('the forms gate (passRateLimit)', async () => {
|
||||
const results = []
|
||||
for (let i = 1; i <= 8; i++) {results.push(await passRateLimit({ ip: `2001:db8:abcd:1::${hex(i)}`, maxPerMinute: 5 }))}
|
||||
expect(results.filter((r) => r === null)).toHaveLength(5)
|
||||
expect(results[7]).toMatchObject({ reason: 'rate_limited' })
|
||||
})
|
||||
|
||||
test('a plugin endpoint (the consent log, 20 a minute): the 21st address of one /64 gets 429', async () => {
|
||||
const { handler } = buildConsentLogEndpoint()
|
||||
const statuses: number[] = []
|
||||
for (let i = 1; i <= 21; i++) {
|
||||
const req = { headers: new Headers({ 'x-real-ip': `2001:db8:feed:1::${hex(i)}` }), text: () => Promise.resolve('{') }
|
||||
statuses.push((await (handler as (r: never) => Promise<Response>)(req as never)).status)
|
||||
}
|
||||
expect(statuses.slice(0, 20)).not.toContain(429)
|
||||
expect(statuses[20]).toBe(429)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the wide counter (setIpv6Grouping({ wide: 48 }))', () => {
|
||||
test('three hundred /64s of one /48: at most wideFactor × max requests', async () => {
|
||||
setIpv6Grouping({ wide: 48, wideFactor: 10 })
|
||||
const s = nextScope()
|
||||
let allowed = 0
|
||||
for (let i = 1; i <= 300; i++) {
|
||||
if ((await consumeRateLimit({ key: `2001:db8:7:${hex(i)}::1`, max: 5, scope: s })).ok) {allowed++}
|
||||
}
|
||||
expect(allowed).toBe(50)
|
||||
// another /48 is untouched
|
||||
expect((await consumeRateLimit({ key: '2001:db8:8:1::1', max: 5, scope: s })).ok).toBe(true)
|
||||
})
|
||||
|
||||
test('IPv4 is not affected by it', async () => {
|
||||
setIpv6Grouping({ wide: 48 })
|
||||
const s = nextScope()
|
||||
const ok = []
|
||||
for (let i = 1; i <= 6; i++) {ok.push((await consumeRateLimit({ key: `198.51.100.${i}`, max: 1, scope: s })).ok)}
|
||||
expect(ok).toEqual([true, true, true, true, true, true])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* readPublished() on version history (`readVersions`) — reported by a client project upgrading to 1.17.1:
|
||||
* `GET /api/pages/versions` answered 500 on MongoDB. The rule answered `{ _status: { equals: 'published' } }`, a path
|
||||
* of the document, while a version query runs on the versions collection, where the status is `version._status`.
|
||||
*
|
||||
* Every way a version is read, for a visitor, a plain `user` account and an editor: the list (REST, Local API,
|
||||
* GraphQL, `depth`), one version by id (REST, GraphQL — the panel's version view reads it the same way), the count.
|
||||
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
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 { READ_PUBLISHED, readPublished, readPublishedVersions, withVersionReadRules } from '../src/modules/access/access.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'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
const tokens: Record<'editor' | 'user', string> = { editor: '', user: '' }
|
||||
let pageId: number | string
|
||||
let neverPublishedId: number | string
|
||||
const versionIds: { draft: (number | string)[]; published: (number | string)[] } = { draft: [], published: [] }
|
||||
|
||||
type Who = 'editor' | 'user' | 'visitor'
|
||||
const headers = (who: Who) => ({ 'content-type': 'application/json', ...(who === 'visitor' ? {} : { authorization: `JWT ${tokens[who]}` }) })
|
||||
const rest = async (pathname: string, who: Who) => {
|
||||
const res = await fetch(`${server.url}/api${pathname}`, { headers: headers(who) })
|
||||
return { body: await res.text(), status: res.status }
|
||||
}
|
||||
const gql = async (query: string, who: Who) => {
|
||||
const res = await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: headers(who), method: 'POST' })
|
||||
return { body: await res.text(), status: res.status }
|
||||
}
|
||||
const titles = (body: string) => [...body.matchAll(/"title":"([^"]+)"/g)].map((m) => m[1])
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
{
|
||||
slug: 'pages',
|
||||
access: { read: readPublished(), readVersions: readPublished() },
|
||||
fields: [{ name: 'title', type: 'text', localized: true }, { name: 'related', type: 'relationship', relationTo: 'pages' }],
|
||||
versions: { drafts: true, maxPerDoc: 20 },
|
||||
},
|
||||
// the explicit version rule, and a role other than the default
|
||||
{ slug: 'notes', access: { read: readPublished('admin'), readVersions: readPublishedVersions('admin') }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-read-published-versions') } },
|
||||
],
|
||||
db: testDatabase('read_published_versions'),
|
||||
editor: lexicalEditor(),
|
||||
globals: [{ slug: 'banner', access: { read: readPublished(), readVersions: readPublished() }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } }],
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
|
||||
secret: 'read-published-versions-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
server = await startPayloadServer(config)
|
||||
for (const role of ['editor', 'user'] as const) {
|
||||
await payload.create({ collection: 'users' as never, data: { email: `${role}@example.com`, password: PASSWORD, roles: [role] } as never })
|
||||
tokens[role] = ((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 }).token
|
||||
}
|
||||
await payload.create({ collection: 'notes' as never, data: { _status: 'published', title: 'Note published' } as never })
|
||||
await payload.create({ collection: 'notes' as never, data: { _status: 'draft', title: 'Note draft' } as never, draft: true })
|
||||
await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'published', title: 'Banner published' } as never })
|
||||
await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'draft', title: 'Banner draft' } as never, draft: true })
|
||||
pageId = (await payload.create({ collection: 'pages' as never, data: { _status: 'published', title: 'Published one' } as never, locale: 'pl' })).id
|
||||
await payload.update({ id: pageId, collection: 'pages' as never, data: { _status: 'draft', title: 'Draft over it' } as never, draft: true, locale: 'pl' })
|
||||
neverPublishedId = (await payload.create({ collection: 'pages' as never, data: { _status: 'draft', related: pageId, title: 'Never published' } as never, draft: true, locale: 'pl' })).id
|
||||
const all = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl' })
|
||||
for (const v of all.docs as unknown as { id: number | string; version: { _status?: string } }[]) {
|
||||
versionIds[v.version._status === 'published' ? 'published' : 'draft'].push(v.id)
|
||||
}
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await server?.close()
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
describe('readPublished() as readVersions', () => {
|
||||
test.each(['visitor', 'user'] as const)('the version list answers a %s with published versions only (REST, depth 0 and 2)', async (who) => {
|
||||
for (const q of ['?limit=100&depth=0', '?limit=100&depth=2&locale=pl']) {
|
||||
const { body, status } = await rest(`/pages/versions${q}`, who)
|
||||
expect(status).toBe(200)
|
||||
expect(titles(body)).toContain('Published one')
|
||||
expect(body).not.toContain('Draft over it')
|
||||
expect(body).not.toContain('Never published')
|
||||
}
|
||||
})
|
||||
|
||||
test('an editor lists every version', async () => {
|
||||
const { body, status } = await rest('/pages/versions?limit=100&depth=0&locale=pl', 'editor')
|
||||
expect(status).toBe(200)
|
||||
expect(titles(body)).toEqual(expect.arrayContaining(['Published one', 'Draft over it', 'Never published']))
|
||||
})
|
||||
|
||||
test('one version by id: a published one is answered, a draft one is not found (REST)', async () => {
|
||||
expect((await rest(`/pages/versions/${versionIds.published[0]}?locale=pl`, 'visitor')).status).toBe(200)
|
||||
for (const id of versionIds.draft) {
|
||||
const { body, status } = await rest(`/pages/versions/${id}?locale=pl`, 'visitor')
|
||||
expect([403, 404]).toContain(status) // Payload refuses a version the rule's condition leaves out
|
||||
expect(body).not.toMatch(/Draft over it|Never published/)
|
||||
}
|
||||
expect((await rest(`/pages/versions/${versionIds.draft[0]}?locale=pl`, 'editor')).status).toBe(200)
|
||||
})
|
||||
|
||||
test('GraphQL: the list and one version, as a visitor', async () => {
|
||||
const list = await gql('{ versionsPages(limit: 100, locale: pl) { totalDocs docs { id version { title _status } } } }', 'visitor')
|
||||
expect(list.status).toBe(200)
|
||||
expect(list.body).not.toContain('"errors"')
|
||||
expect(list.body).toContain('Published one')
|
||||
expect(list.body).not.toMatch(/Draft over it|Never published/)
|
||||
const draft = await gql(`{ versionPage(id: "${versionIds.draft[0]}", locale: pl) { version { title } } }`, 'visitor')
|
||||
expect(draft.body).not.toMatch(/Draft over it|Never published/)
|
||||
})
|
||||
|
||||
test('Local API with access control: findVersions and countVersions as a visitor', async () => {
|
||||
const found = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl', overrideAccess: false })
|
||||
expect((found.docs as unknown as { version: { title?: string } }[]).map((d) => d.version.title)).toEqual(['Published one'])
|
||||
const counted = await payload.countVersions({ collection: 'pages' as never, overrideAccess: false })
|
||||
expect(counted.totalDocs).toBe(versionIds.published.length)
|
||||
})
|
||||
|
||||
test('reading the documents still works as before (read: readPublished())', async () => {
|
||||
expect((await rest(`/pages/${neverPublishedId}`, 'visitor')).status).toBe(404)
|
||||
expect(titles((await rest(`/pages/${pageId}?locale=pl`, 'visitor')).body)).toContain('Published one')
|
||||
expect(titles((await rest(`/pages/${pageId}?draft=true&locale=pl`, 'editor')).body)).toContain('Draft over it')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the other ways in', () => {
|
||||
test('readPublishedVersions(), with its own role: an editor is a visitor when the role is admin', async () => {
|
||||
for (const who of ['visitor', 'editor'] as const) {
|
||||
const { body, status } = await rest('/notes/versions?limit=50', who)
|
||||
expect(status).toBe(200)
|
||||
expect(body).toContain('Note published')
|
||||
expect(body).not.toContain('Note draft')
|
||||
}
|
||||
})
|
||||
|
||||
test('a global: readVersions: readPublished() lists published versions only', async () => {
|
||||
const { body, status } = await rest('/globals/banner/versions?limit=50', 'visitor')
|
||||
expect(status).toBe(200)
|
||||
expect(body).toContain('Banner published')
|
||||
expect(body).not.toContain('Banner draft')
|
||||
expect((await rest('/globals/banner/versions?limit=50', 'editor')).body).toContain('Banner draft')
|
||||
})
|
||||
|
||||
test('withVersionReadRules swaps only a readPublished() rule, keeping its role (a plugin listed after iapl)', () => {
|
||||
const own = () => true
|
||||
const [swapped, kept, none] = withVersionReadRules([
|
||||
{ slug: 'late', access: { readVersions: readPublished('admin') } },
|
||||
{ slug: 'mine', access: { readVersions: own } },
|
||||
{ slug: 'open' },
|
||||
] as { access?: { readVersions?: unknown }; slug: string }[])!
|
||||
const rule = swapped.access!.readVersions as (a: unknown) => unknown
|
||||
expect(READ_PUBLISHED in rule).toBe(false)
|
||||
expect(rule({ req: { payload: undefined, user: undefined } })).toEqual({ 'version._status': { equals: 'published' } })
|
||||
expect(kept.access!.readVersions).toBe(own)
|
||||
expect(none).toEqual({ slug: 'open' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* Plugin writes that do not carry an old copy of a settings global back (owner's decision Q3, 1.18.0).
|
||||
*
|
||||
* - The integration status (`emailStatus`, `turnstileStatus`) is written after an ANONYMOUS form submit or a mail
|
||||
* send. Payload's `updateGlobal` reads the whole document, merges the change and writes the whole result: an
|
||||
* admin's SMTP or Turnstile change saved in between was put back silently. The status is now written alone.
|
||||
* - `addToCookieList` (cookie approval, review) read the cookie list, added a row and wrote the whole list: a row
|
||||
* an editor saved in between was lost. It now checks the list again right before writing and starts over when
|
||||
* it changed.
|
||||
*
|
||||
* The race is made exact by holding the plugin's read and letting the other save land in between.
|
||||
* Real database; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
|
||||
*/
|
||||
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 { addToCookieList } from '../src/modules/consent/scanner/sync.js'
|
||||
import { recordIntegrationStatus } from '../src/modules/integrations/status.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
let payload: Payload
|
||||
const SI = 'site-integrations'
|
||||
const si = async () => (await payload.findGlobal({ slug: SI as never })) as unknown as Record<string, unknown>
|
||||
|
||||
beforeAll(async () => {
|
||||
const config = buildTestConfig({
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-status-writes') } }],
|
||||
db: testDatabase('status_writes'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, cookieScanner: true, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
|
||||
secret: 'status-writes-0123456789-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
describe('the integration status is written alone', () => {
|
||||
test("an admin's SMTP change saved while the status is written stays", async () => {
|
||||
await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'old.example.com', smtpPassword: 'old-secret', smtpUser: 'u' } as never })
|
||||
// the copy any read-merge-write would hold: taken before the admin's save
|
||||
const before = await payload.db.findGlobal({ slug: SI, req: {} as never })
|
||||
const real = payload.db.findGlobal.bind(payload.db)
|
||||
let held = true
|
||||
const spy = vi.spyOn(payload.db, 'findGlobal').mockImplementation(async (args) => {
|
||||
if (args.slug === SI && held) {
|
||||
held = false
|
||||
// the admin's save lands while the status write is under way
|
||||
await payload.updateGlobal({ slug: SI as never, data: { smtpHost: 'new.example.com', smtpPassword: 'new-secret' } as never })
|
||||
return before as never
|
||||
}
|
||||
return real(args)
|
||||
})
|
||||
try {
|
||||
await recordIntegrationStatus(payload, 'emailStatus', null, { code: 'smtp-auth', message: 'Login refused', state: 'degraded' })
|
||||
} finally {
|
||||
spy.mockRestore()
|
||||
}
|
||||
const after = await si()
|
||||
expect(after).toMatchObject({ smtpHost: 'new.example.com', smtpPassword: 'new-secret' })
|
||||
expect(after.emailStatus).toMatchObject({ code: 'smtp-auth', state: 'degraded' })
|
||||
})
|
||||
|
||||
test('the status write changes nothing else in the document', async () => {
|
||||
await payload.updateGlobal({ slug: SI as never, data: { ga4MeasurementId: 'G-KEEP', smtpHost: 'keep.example.com', turnstileSiteKey: 'site-key' } as never })
|
||||
const { turnstileStatus: _t, updatedAt: _u, ...before } = await si()
|
||||
await recordIntegrationStatus(payload, 'turnstileStatus', null, { code: 'bad-secret', state: 'degraded' })
|
||||
const { turnstileStatus, updatedAt: _u2, ...after } = await si()
|
||||
expect(after).toEqual(before)
|
||||
expect(turnstileStatus).toMatchObject({ code: 'bad-secret', state: 'degraded' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('the cookie list keeps a row saved in between', () => {
|
||||
test('an editor adds a row while the scanner adds its own: both rows stay', async () => {
|
||||
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [{ name: 'first', category: 'necessary' }] } as never, locale: 'pl' })
|
||||
const real = payload.findGlobal.bind(payload)
|
||||
let held = true
|
||||
const spy = vi.spyOn(payload, 'findGlobal').mockImplementation(async (args) => {
|
||||
const result = await real(args as never)
|
||||
if ((args as { slug: string }).slug === 'cookie-settings' && held) {
|
||||
held = false
|
||||
// the editor's save lands after the scanner read the list
|
||||
const rows = ((await real({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: object[] }).cookies ?? []
|
||||
await payload.updateGlobal({ slug: 'cookie-settings' as never, data: { cookies: [...rows, { name: 'editor_cookie', category: 'analytics' }] } as never, locale: 'pl' })
|
||||
}
|
||||
return result as never
|
||||
})
|
||||
try {
|
||||
expect(await addToCookieList({ entry: { name: 'scanned_cookie', category: 'marketing' } as never, payload })).toBe('added')
|
||||
} finally {
|
||||
spy.mockRestore()
|
||||
}
|
||||
const names = (((await payload.findGlobal({ slug: 'cookie-settings' as never, depth: 0, locale: 'pl' as never })) as { cookies?: { name?: string }[] }).cookies ?? []).map((r) => r.name)
|
||||
expect(names).toEqual(expect.arrayContaining(['first', 'editor_cookie', 'scanned_cookie']))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* The doctor's `visitor-writes` probe (1.17.2, the owner's Q3 answer (b)): on a site with a visitor login collection,
|
||||
* every collection and global whose write rule lets such an account in — Payload's default "any signed-in account"
|
||||
* included — is listed. Asked by behaviour on the built config, never by a rule's name.
|
||||
*/
|
||||
import type { Config, SanitizedConfig } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { adminOrEditor } from '../src/modules/access/access.js'
|
||||
import { visitorWritableEntities } from '../src/modules/doctor/visitorWrites.js'
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const build = (collections: Config['collections'], globals: Config['globals'] = []) =>
|
||||
buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: true }, ...(collections ?? [])],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' } }),
|
||||
editor: lexicalEditor(),
|
||||
globals,
|
||||
plugins: [iapl({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false } as never)],
|
||||
secret: 'visitor-writes-test',
|
||||
telemetry: false,
|
||||
} as unknown as Config)
|
||||
/** The live shape the probe reads (`payload.collections`, `payload.config`), from a built config. */
|
||||
const live = (config: SanitizedConfig) => ({ collections: Object.fromEntries(config.collections.map((c) => [c.slug, { config: c }])), config }) as never
|
||||
|
||||
describe('visitorWritableEntities', () => {
|
||||
test('with a visitor login collection: Payload\'s defaults are listed, explicit staff rules and the plugin\'s own are not', async () => {
|
||||
const config = await build(
|
||||
[
|
||||
{ slug: 'customers', access: { create: () => true, delete: () => false, update: ({ req }) => ({ id: { equals: req.user?.id } }) }, auth: true, fields: [] },
|
||||
{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] },
|
||||
{ slug: 'posts', access: { create: adminOrEditor, delete: adminOrEditor, read: () => true, update: adminOrEditor }, fields: [{ name: 'title', type: 'text' }] },
|
||||
],
|
||||
[{ slug: 'header', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }],
|
||||
)
|
||||
const open = await visitorWritableEntities(live(config))
|
||||
expect(open).toEqual(expect.arrayContaining(['customers:create', 'globals/header:update', 'media:create', 'media:delete', 'media:update', 'pages:create', 'pages:delete', 'pages:update', 'payload-locked-documents:create']))
|
||||
// explicit staff rules, a rule that answers a query, "nobody", the plugin's own entities
|
||||
for (const closed of ['posts:create', 'posts:update', 'posts:delete', 'customers:update', 'customers:delete', 'form-submissions:create', 'forms:create', 'globals/site-settings:update', 'globals/site-integrations:update', 'payload-kv:create']) {
|
||||
expect(open).not.toContain(closed)
|
||||
}
|
||||
}, 30_000)
|
||||
|
||||
test('a site with only the staff login collection: nothing to report', async () => {
|
||||
const config = await build([{ slug: 'pages', access: { read: () => true }, fields: [{ name: 'title', type: 'text' }] }])
|
||||
expect(await visitorWritableEntities(live(config))).toEqual([])
|
||||
}, 30_000)
|
||||
})
|
||||
Reference in New Issue
Block a user