Panel actions only from the site's own origin (adminSameOrigin); doctor reads serverURL from the running config
The plugin's panel actions (mail service connect / disconnect, test e-mail,
cookie scan, approval, crawl) act with the panel's login cookie and read a
text/plain body, which another origin sends without a CORS preflight; a
sibling subdomain is same-site and Payload's csrf list is empty without
serverURL. On 1.17.1 such a page reached connect with an admin's cookie
(it called the mail service). Now each refuses a request a browser marks as
coming from elsewhere (403 before anything is read), the rule of the 2FA
endpoints; only endpoints the plugin added; logged once per origin, naming
adminSameOrigin. adminSameOrigin: false / { origins } (owner's Q6).
iapl-doctor csrf-empty: the deep status reports originKnown (serverURL or
csrf in the running config, never the value) and it wins over the file.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
97c62f21f0
commit
03f5cf1a8d
@@ -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 }
|
||||
}
|
||||
+14
-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 () => {
|
||||
@@ -230,6 +233,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 +542,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'])
|
||||
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
|
||||
expect(status.mail).toBeNull() // no Site integrations global in this config
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user