M1 (2, 3): the Turnstile env secret is deprecated; doctor rules access-missing, turnstile-degraded, turnstile-env-key

(2) Stage one of the deprecation: TURNSTILE_SECRET_KEY from the environment still
works when the panel field is empty, logs once that it is deprecated, and the
doctor's deep status reports it (rule turnstile-env-key, warning). Nothing is
removed.
(3) access-missing (static, warning): ipalKit without `access` means every panel
account is an admin. turnstile-degraded (deep): Turnstile is not checking forms —
warning, error after a day. The deep status carries the recorded state and where
the secret comes from, never a key.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-25 00:39:12 +01:00
co-authored by Claude Fable 5.2
parent 8fa71238ce
commit 42fdad8c2d
8 changed files with 214 additions and 16 deletions
+49 -1
View File
@@ -150,6 +150,54 @@ describe('2FA setup required: what a project must have', () => {
})
})
describe('M1 rules: access-missing, turnstile-degraded, turnstile-env-key', () => {
const run = async (config: string, only: string[], deepStatus?: object) =>
rules(await doctor(project({ ...base(), 'src/payload.config.ts': config }), only, deepStatus ? { deepStatus } : {}))
test('access-missing: ipalKit without `access` means every account is an admin', async () => {
expect(await run("plugins: [ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: payloadTotp } })]", ['access-missing'])).toEqual(['access-missing:warning'])
// a collection's own access rules are not the plugin option
expect(await run("collections: [{ slug: 'pages', access: { read: () => true } }], plugins: [ipalKit({ i18n })]", ['access-missing'])).toEqual(['access-missing:warning'])
for (const ok of ["ipalKit({ access: { authCollection: 'users' }, i18n })", "ipalKit({ i18n, access: { defaultRole: 'editor' } })", 'ipalKit({ access: {}, i18n })', 'ipalKit({ access: accessOptions, i18n })', '// no plugin here']) {
expect([ok, await run(`plugins: [${ok}]`, ['access-missing'])]).toEqual([ok, []])
}
})
test('turnstile-degraded: a warning, an error after a day', async () => {
const at = (hoursAgo: number) => new Date(Date.parse(`${TODAY}T12:00:00Z`) - hoursAgo * 3_600_000).toISOString()
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(2), state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { code: 'invalid-input-secret', since: at(48), state: 'degraded' } })).toEqual(['turnstile-degraded:error'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { state: 'degraded' } })).toEqual(['turnstile-degraded:warning'])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: { since: at(48), state: 'ok' } })).toEqual([])
expect(await run(cfg, ['turnstile-degraded'], { turnstile: null })).toEqual([])
expect(await run(cfg, ['turnstile-degraded'])).toEqual([]) // no deep status: nothing to say
})
test('turnstile-env-key: the secret still comes from the environment', async () => {
const cfg = "ipalKit({ access: { authCollection: 'users' } })"
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: true })).toEqual(['turnstile-env-key:warning'])
expect(await run(cfg, ['turnstile-env-key'], { turnstileSecretFromEnv: false })).toEqual([])
expect(await run(cfg, ['turnstile-env-key'])).toEqual([])
})
test('the deep status reports the state and where the secret comes from, never a key', async () => {
vi.stubEnv('TURNSTILE_SECRET_KEY', 'env-secret-value')
const fake = (integrations: object) => ({
config: { admin: { user: 'users' }, collections: [{ slug: 'users', fields: [] }], globals: [{ slug: 'site-integrations' }] },
findGlobal: async () => integrations,
})
const degraded = await collectDoctorStatus(fake({ turnstileSecretKey: 'panel-secret-value', turnstileStatus: { code: 'invalid-input-secret', message: 'x', since: '2026-10-28T10:00:00.000Z', state: 'degraded' } }) as never)
expect(degraded.turnstile).toEqual({ code: 'invalid-input-secret', since: '2026-10-28T10:00:00.000Z', state: 'degraded' })
expect(degraded.turnstileSecretFromEnv).toBe(false)
expect(JSON.stringify(degraded)).not.toMatch(/secret-value/)
const fromEnv = await collectDoctorStatus(fake({ turnstileSiteKey: 'site' }) as never)
expect(fromEnv.turnstile).toBeNull()
expect(fromEnv.turnstileSecretFromEnv).toBe(true)
expect(JSON.stringify(fromEnv)).not.toMatch(/secret-value/)
})
})
describe('helpers', () => {
test('parseEnvFile reads KEY=value, strips quotes, skips comments', () => {
expect(parseEnvFile('# c\nA=1\nexport B="two"\n C = \'3\'\nbad line')).toEqual({ A: '1', B: 'two', C: '3' })
@@ -433,7 +481,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(['node', 'pendingCookies', 'plugin', 'usersSetupClosed', 'usersWithout2fa'])
expect(Object.keys(status).sort()).toEqual(['node', 'pendingCookies', 'plugin', 'turnstile', 'turnstileSecretFromEnv', 'usersSetupClosed', 'usersWithout2fa'])
expect(status.usersSetupClosed).toBeNull() // no setup window in this config
})
test('collectDoctorStatus counts the accounts whose 2FA setup window has passed', async () => {
+60
View File
@@ -0,0 +1,60 @@
/**
* M1: the Turnstile secret key from the environment is deprecated — it still works, and says so once.
* Cloudflare is the mocked `fetch`.
*/
import { afterEach, describe, expect, test, vi } from 'vitest'
import { passTurnstile } from '../src/modules/forms/submitForm.js'
import { getTurnstileConfig, turnstileSecretFromEnv } from '../src/modules/turnstile/config.js'
vi.mock('server-only', () => ({}))
type Option = 'allow' | 'reject' | { files?: 'allow' | 'reject'; text?: 'allow' | 'reject' } | undefined
const payloadWith = (integrations: Record<string, unknown>, option?: Option) => ({
config: { custom: { ipal: { forms: option ? { turnstileOnConfigError: option } : {} } }, globals: [{ slug: 'site-integrations' }] },
findGlobal: async () => integrations,
logger: { error: () => undefined, info: () => undefined, warn: () => undefined },
updateGlobal: async () => ({}),
})
const KEYS = { turnstileSecretKey: 'secret', turnstileSiteKey: 'site' }
const cloudflare = (body: unknown, status = 200) => vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(body), { status })))
afterEach(() => {
vi.unstubAllGlobals()
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
describe('the Turnstile secret from the environment (deprecated)', () => {
test('turnstileSecretFromEnv: only when the panel field is empty and the variable is set', () => {
vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env')
expect(turnstileSecretFromEnv({})).toBe(true)
expect(turnstileSecretFromEnv({ turnstileSecretKey: ' ' })).toBe(true)
expect(turnstileSecretFromEnv({ turnstileSecretKey: 'from-panel' })).toBe(false)
vi.stubEnv('TURNSTILE_SECRET_KEY', '')
expect(turnstileSecretFromEnv({})).toBe(false)
})
test('it still works, and says once that it is deprecated', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env')
const payload = payloadWith({ turnstileSiteKey: 'site' })
expect(await getTurnstileConfig(payload as never)).toEqual({ enabled: true, siteKey: 'site' })
expect(await getTurnstileConfig(payload as never)).toEqual({ enabled: true, siteKey: 'site' })
const lines = warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('Deprecated'))
expect(lines).toHaveLength(1)
expect(lines[0]).toMatch(/TURNSTILE_SECRET_KEY.*Site integrations.*keeps working for now/)
// the check itself runs with the env secret
cloudflare({ success: true })
expect(await passTurnstile({ payload: payload as never, turnstileToken: 'token' })).toBeNull()
const sent = String((vi.mocked(fetch).mock.calls[0] as unknown as [string, { body: URLSearchParams }])[1].body)
expect(sent).toContain('secret=from-env')
})
test('with the key in the panel there is nothing to say', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
vi.stubEnv('TURNSTILE_SECRET_KEY', 'from-env')
await getTurnstileConfig(payloadWith(KEYS) as never)
expect(warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('Deprecated'))).toEqual([])
})
})