2FA setup required: the missing-column log reads the error's cause chain
R3-1: the SQL adapters throw "Failed query: …" and put the database's own words
("column … does not exist", "no such column") in the error's cause, so the loud
start-up line never appeared on a real Postgres or SQLite. The reason is now
built from the whole cause chain; other failures (ECONNREFUSED, a locked
database) still only warn. Tested with wrapped errors and against the real
adapter with the column dropped.
Docs and the doctor's fix text name how the migration is applied
(deployment.md 4.3) wherever they said only "before the site serves".
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
01e3813723
commit
b52193ae47
@@ -497,6 +497,39 @@ describe('ipalKit and the 2FA plugin', () => {
|
||||
expect(other.logger.warn).toHaveBeenCalledTimes(1)
|
||||
}
|
||||
expect(String(pg.logger.error.mock.calls[0]?.[0])).toMatch(/prodMigrations.*not in a pre-deployment command/s)
|
||||
|
||||
// What the SQL adapters really throw: Drizzle's "Failed query: …" with the database's own words in `cause`.
|
||||
const wrapped = (name: string, cause: unknown, message = 'Failed query: select count(*) from "users" where …') => {
|
||||
const logger = { error: vi.fn(), warn: vi.fn() }
|
||||
return { logger, payload: { count: async () => { throw Object.assign(new Error(message), { cause }) }, db: { name }, logger } }
|
||||
}
|
||||
for (const real of [
|
||||
wrapped('postgres', Object.assign(new Error('column users.totp_setup_from does not exist'), { code: '42703' })),
|
||||
wrapped('sqlite', new Error('SQLITE_ERROR: no such column: users.totp_setup_from')),
|
||||
wrapped('sqlite', { message: 'no such column: totp_setup_from' }), // a plain object as the cause
|
||||
wrapped('postgres', Object.assign(new Error('driver'), { cause: new Error('column "totp_setup_from" does not exist') })), // two levels down
|
||||
]) {
|
||||
await backfillSetupFrom(real.payload as never, 'users')
|
||||
expect(real.logger.warn).not.toHaveBeenCalled()
|
||||
expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/NOBODY CAN LOG IN/)
|
||||
expect(String(real.logger.error.mock.calls[0]?.[0])).toMatch(/totp_setup_from/) // the database's own words are in the line
|
||||
}
|
||||
for (const other of [
|
||||
wrapped('postgres', Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:5432'), { code: 'ECONNREFUSED' })),
|
||||
wrapped('sqlite', new Error('SQLITE_BUSY: database is locked')),
|
||||
wrapped('postgres', new Error('relation "users" does not exist')),
|
||||
]) {
|
||||
await backfillSetupFrom(other.payload as never, 'users')
|
||||
expect(other.logger.error).not.toHaveBeenCalled()
|
||||
expect(other.logger.warn).toHaveBeenCalledTimes(1)
|
||||
}
|
||||
// a cause that points at itself does not loop
|
||||
const loop = new Error('Failed query') as { cause?: unknown } & Error
|
||||
loop.cause = loop
|
||||
const looping = { logger: { error: vi.fn(), warn: vi.fn() }, payload: {} as Record<string, unknown> }
|
||||
looping.payload = { count: async () => { throw loop }, db: { name: 'postgres' }, logger: looping.logger }
|
||||
await backfillSetupFrom(looping.payload as never, 'users')
|
||||
expect(looping.logger.warn).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
// The reset removes a second factor: by default only a session that entered its own TOTP code may do it.
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Postgres / SQLite without the migration that adds the 2FA column, against the REAL adapter: the start-up step
|
||||
* must log the loud line (the database's own words are in the error's `cause`, not in its message), and every
|
||||
* query on the collection fails — which is why the docs call the migration a required step of the same deploy.
|
||||
* SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` runs it on Postgres. Not for MongoDB (no columns).
|
||||
*/
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
|
||||
|
||||
import { backfillSetupFrom } from '../src/modules/security/totp/setupRequired.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
import { testDatabase } from './http/db.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const sql = !process.env.IPAL_TEST_MONGO_URI
|
||||
let payload: Payload
|
||||
|
||||
beforeAll(async () => {
|
||||
if (!sql) {return}
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } }],
|
||||
db: testDatabase('setupcol'),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, twoFactor: { issuer: 'Example', plugin: payloadTotp as never } })],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config })
|
||||
}, 120_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy?.()
|
||||
})
|
||||
|
||||
test.skipIf(!sql)('without the column: the loud log line, and every query on the collection fails; with it: the window starts', async () => {
|
||||
await payload.create({ collection: 'users' as never, data: { email: '[email protected]', password: 'a-long-test-password-1', roles: ['admin'] } as never })
|
||||
const db = payload.db as unknown as { client?: { execute: (q: string) => Promise<unknown> }; name: string; pool?: { query: (q: string) => Promise<unknown> }; schemaName?: string }
|
||||
const run = (statement: string) => (db.pool ? db.pool.query(statement) : db.client!.execute(statement))
|
||||
const table = db.pool && db.schemaName ? `"${db.schemaName}"."users"` : '"users"'
|
||||
// the schema as the previous version left it
|
||||
await run(`ALTER TABLE ${table} DROP COLUMN "totp_setup_from"`)
|
||||
|
||||
const error = vi.spyOn(payload.logger, 'error').mockImplementation(() => undefined as never)
|
||||
const warn = vi.spyOn(payload.logger, 'warn').mockImplementation(() => undefined as never)
|
||||
expect(await backfillSetupFrom(payload, 'users')).toBe(0) // does not throw: the public site must keep running
|
||||
expect(error).toHaveBeenCalledTimes(1)
|
||||
expect(String(error.mock.calls[0]?.[0])).toMatch(/the column for "totpSetupFrom" is missing.*NOBODY CAN LOG IN.*prodMigrations/s)
|
||||
expect(warn).not.toHaveBeenCalled()
|
||||
// what "nobody can log in" means: the account cannot even be read
|
||||
await expect(payload.find({ collection: 'users' as never })).rejects.toThrow()
|
||||
await expect(payload.login({ collection: 'users' as never, data: { email: '[email protected]', password: 'a-long-test-password-1' } as never })).rejects.toThrow()
|
||||
|
||||
// the migration: the column is there → the start-up step gives the existing account its window, once
|
||||
await run(`ALTER TABLE ${table} ADD COLUMN "totp_setup_from" ${db.pool ? 'timestamp(3) with time zone' : 'text'}`)
|
||||
error.mockClear()
|
||||
expect(await backfillSetupFrom(payload, 'users')).toBe(1)
|
||||
expect(await backfillSetupFrom(payload, 'users')).toBe(0)
|
||||
expect(error).not.toHaveBeenCalled()
|
||||
expect((await payload.login({ collection: 'users' as never, data: { email: '[email protected]', password: 'a-long-test-password-1' } as never })).token).toBeTruthy()
|
||||
error.mockRestore()
|
||||
warn.mockRestore()
|
||||
})
|
||||
Reference in New Issue
Block a user