Staff sign-in rules: failures per IP and address, own origin, current password for own changes (1.18.0)
Q2 (IAWL idea 16): Payload locks a staff account after 5 wrong passwords from anybody, so a stranger kept the owner out without a password. Failed sign-ins are now counted per client IP and typed address (folded: NFKC, lower case, trim): 5 in 15 min, then 429 for that IP and address only; only failures count (a place taken before the compare, given back on success or refusal; "try again in a moment" while others are being checked). Payload's own lock stays as the net at 50 failures for an hour where the project set none. The mail service's account-mail limit now counts per address per visitor (5) with 20 per address in all, so one stranger no longer blocks the owner's own reset mail. Q3 (idea 7): staff login, forgot and reset password refuse a request a browser marks as coming from another origin (403 before anything is counted or sent); visitor collections untouched. Q5 (idea 29): an account that changes its own e-mail, username or password must send its current password (panel field on the account page via the plugin's MaskedField, no import-map change; REST and GraphQL). Admins changing others, server code and API keys are not asked; wrong ones count like failed sign-ins. Options accounts.signInLimit / signInSameOrigin / confirmOwnChanges, all validated at start. Tests: 15 HTTP tests (2FA on/off, all off), fail before on 1.17.1; built-site spec own-account.spec.ts in e2e:built. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
fc70a34f3e
commit
52710021ef
@@ -1397,3 +1397,23 @@ describe('the adapter on its own, and the deprecated Graph line', () => {
|
||||
expect(quiet.logger.warn.mock.calls.map((c) => String(c[0])).filter((m) => m.includes('deprecated'))).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('account mail per address is counted per visitor too (1.18.0)', () => {
|
||||
test('a stranger who uses up an address from one IP does not stop the owner\'s own reset mail; all visitors together stop at perAddressTotal', async () => {
|
||||
const { fake, options, payload } = relaySite({ fake: { allow: [HOST], limits: { messagesPerHour: 100 } } })
|
||||
const send = (visitor: string, subject: string) => {
|
||||
expectMailTo('[email protected]', 'account', { visitor })
|
||||
// as Payload's "forgot password" goes: marked as account mail for this address, with the requesting visitor
|
||||
return sendThroughRelay(payload, options, { html: 'reset', subject, to: '[email protected]' })
|
||||
}
|
||||
for (let i = 0; i < 5; i++) {expect((await send('203.0.113.9', `Reset ${i}`)).sent).toBe(true)}
|
||||
expect(await send('203.0.113.9', 'Reset 5')).toMatchObject({ cause: 'client-account-mail-limit', sent: false })
|
||||
// the owner, from another address
|
||||
expect(await send('198.51.100.20', 'Reset owner')).toMatchObject({ sent: true })
|
||||
// many visitors together: perAddressTotal (20) for the address
|
||||
let sent = 6
|
||||
for (let i = 1; sent < 20; i++) {if ((await send(`192.0.2.${i}`, `Reset v${i}`)).sent) {sent++}}
|
||||
expect(await send('192.0.2.200', 'Reset over')).toMatchObject({ cause: 'client-account-mail-limit', sent: false })
|
||||
expect(fake.outbox.filter((m) => m.kind === 'account')).toHaveLength(20)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
/** Sign-in rules of the staff collections, 2FA on (signInRulesSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { foldSignInName, passwordMatches } from '../src/modules/access/signInRules.js'
|
||||
import { FOREIGN, PASSWORD, signInSite } from './signInRulesSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { call, gqlLogin, idOf, login, session, state, stored } = signInSite()
|
||||
|
||||
describe('accounts.signInLimit: a stranger cannot lock a staff account out', () => {
|
||||
test('five wrong passwords from one IP: that IP gets 429 for the address; the owner, elsewhere, signs in', async () => {
|
||||
for (let i = 0; i < 5; i++) {expect((await login('[email protected]', 'a-wrong-password', '198.51.100.66')).status).toBe(401)}
|
||||
const refused = await login('[email protected]', PASSWORD, '198.51.100.66')
|
||||
expect(refused.status).toBe(429)
|
||||
expect(refused.body).toMatch(/Too many failed sign-ins/)
|
||||
expect((await login('[email protected]', PASSWORD, '203.0.113.7')).status).toBe(200)
|
||||
expect((await stored('[email protected]'))?.lockUntil ?? null).toBeNull()
|
||||
})
|
||||
|
||||
test('the answer for "too many" is the same for a real and an invented address', async () => {
|
||||
for (let i = 0; i < 5; i++) {await login('[email protected]', 'a-wrong-password', '198.51.100.67')}
|
||||
for (let i = 0; i < 5; i++) {await login('[email protected]', 'a-wrong-password', '198.51.100.68')}
|
||||
const invented = await login('[email protected]', 'a-wrong-password', '198.51.100.67')
|
||||
const real = await login('[email protected]', 'a-wrong-password', '198.51.100.68')
|
||||
expect(invented.status).toBe(429)
|
||||
expect(real).toEqual(invented)
|
||||
})
|
||||
|
||||
test('correct sign-ins never count; spellings of one address share one count (case, width)', async () => {
|
||||
for (let i = 0; i < 8; i++) {expect((await login('[email protected]', PASSWORD, '198.51.100.69')).status).toBe(200)}
|
||||
for (const spelling of ['[email protected]', 'fold@example.com', ' [email protected]', '[email protected]', '[email protected]']) {
|
||||
await login(spelling, 'a-wrong-password', '198.51.100.70')
|
||||
}
|
||||
expect((await login('[email protected]', PASSWORD, '198.51.100.70')).status).toBe(429)
|
||||
expect(foldSignInName('fold@Example.COM ')).toBe('[email protected]')
|
||||
})
|
||||
|
||||
test('GraphQL counts and answers the same way', async () => {
|
||||
for (let i = 0; i < 5; i++) {await gqlLogin('[email protected]', 'a-wrong-password', '198.51.100.71')}
|
||||
const refused = await gqlLogin('[email protected]', PASSWORD, '198.51.100.71')
|
||||
expect(refused.status).toBe(429)
|
||||
expect(refused.message).toMatch(/Too many failed sign-ins/)
|
||||
})
|
||||
|
||||
test("Payload's per-account lock stays as the net, at 50 failures for an hour", () => {
|
||||
const auth = state.payload.collections['users' as never].config.auth as { lockTime: number; maxLoginAttempts: number }
|
||||
expect([auth.maxLoginAttempts, auth.lockTime]).toEqual([50, 3_600_000])
|
||||
const customers = state.payload.collections['customers' as never].config.auth as { maxLoginAttempts: number }
|
||||
expect(customers.maxLoginAttempts).toBe(5) // not staff: Payload's default
|
||||
})
|
||||
})
|
||||
|
||||
describe('accounts.signInSameOrigin: staff sign-in only from the site\'s own origin', () => {
|
||||
test('login, forgot password and reset password from a foreign page: 403, nothing counted or sent', async () => {
|
||||
const before = state.mails.length
|
||||
expect((await login('[email protected]', PASSWORD, '198.51.100.80', FOREIGN)).status).toBe(403)
|
||||
expect((await call('/users/forgot-password', { email: '[email protected]' }, { 'sec-fetch-site': 'cross-site' })).status).toBe(403)
|
||||
expect((await call('/users/reset-password', { password: 'a-new-password-123', token: 'x'.repeat(40) }, FOREIGN)).status).toBe(403)
|
||||
expect((await gqlLogin('[email protected]', PASSWORD, '198.51.100.80', FOREIGN)).status).toBe(403)
|
||||
expect(state.mails.length).toBe(before)
|
||||
// the site's own page and a script without browser headers go through
|
||||
expect((await login('[email protected]', PASSWORD, '198.51.100.80', { origin: state.server.url, 'sec-fetch-site': 'same-origin' })).status).toBe(200)
|
||||
expect((await login('[email protected]', PASSWORD, '198.51.100.80')).status).toBe(200)
|
||||
expect((await call('/users/forgot-password', { email: '[email protected]' })).status).toBe(200)
|
||||
})
|
||||
|
||||
test('a visitor collection is not staff: its login from another origin is untouched', async () => {
|
||||
expect((await call('/customers/login', { email: '[email protected]', password: PASSWORD }, FOREIGN)).status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accounts.confirmOwnChanges: one\'s own e-mail or password needs the current password', () => {
|
||||
test('REST: without it 400, wrong 400, right 200; never read back', async () => {
|
||||
const cookie = await session('[email protected]', PASSWORD, '203.0.113.30')
|
||||
const id = await idOf('[email protected]')
|
||||
const patch = (data: object) => call(`/users/${id}`, data, { cookie, 'x-real-ip': '203.0.113.30' }, 'PATCH')
|
||||
const none = await patch({ email: '[email protected]' })
|
||||
expect([none.status, none.body]).toEqual([400, expect.stringMatching(/Enter your current password/)])
|
||||
const wrong = await patch({ currentPassword: 'not-my-password', email: '[email protected]' })
|
||||
expect([wrong.status, wrong.body]).toEqual([400, expect.stringMatching(/current password is not right/)])
|
||||
const right = await patch({ currentPassword: PASSWORD, email: '[email protected]' })
|
||||
expect(right.status).toBe(200)
|
||||
expect(right.body).not.toMatch(/a-long-test-password/)
|
||||
expect(await idOf('[email protected]')).toBe(id)
|
||||
// other fields of one's own account need nothing
|
||||
expect((await call(`/users/${id}`, { roles: ['editor'] }, { cookie }, 'PATCH')).status).not.toBe(400)
|
||||
})
|
||||
|
||||
test('GraphQL: the same rule; the password too', async () => {
|
||||
const cookie = await session('[email protected]', PASSWORD, '203.0.113.31')
|
||||
const id = await idOf('[email protected]')
|
||||
const gql = async (data: string) => JSON.parse((await call('/graphql', { query: `mutation { updateUser(id: ${JSON.stringify(id)}, data: { ${data} }) { email } }` }, { cookie })).body) as { data?: { updateUser?: unknown }; errors?: { message: string }[] }
|
||||
expect((await gql('password: "a-new-password-456"')).errors?.[0]?.message).toBeTruthy()
|
||||
expect((await gql(`password: "a-new-password-456", currentPassword: "${PASSWORD}"`)).data?.updateUser).toBeTruthy()
|
||||
expect((await login('[email protected]', 'a-new-password-456', '203.0.113.31')).status).toBe(200)
|
||||
})
|
||||
|
||||
test('an admin changing ANOTHER account is not asked', async () => {
|
||||
const cookie = await session('[email protected]', PASSWORD, '203.0.113.32')
|
||||
const id = await idOf('[email protected]')
|
||||
expect((await call(`/users/${id}`, { email: '[email protected]' }, { cookie }, 'PATCH')).status).toBe(200)
|
||||
})
|
||||
|
||||
test('wrong current passwords count like failed sign-ins (429 after five)', async () => {
|
||||
const cookie = await session('[email protected]', PASSWORD, '203.0.113.33')
|
||||
const id = await idOf('[email protected]')
|
||||
for (let i = 0; i < 5; i++) {
|
||||
expect((await call(`/users/${id}`, { currentPassword: `wrong-${i}`, password: 'another-password-1' }, { cookie, 'x-real-ip': '203.0.113.33' }, 'PATCH')).status).toBe(400)
|
||||
}
|
||||
expect((await call(`/users/${id}`, { currentPassword: PASSWORD, password: 'another-password-1' }, { cookie, 'x-real-ip': '203.0.113.33' }, 'PATCH')).status).toBe(429)
|
||||
})
|
||||
|
||||
test("passwordMatches: Payload's hash formats; an unknown prefix is refused", async () => {
|
||||
const doc = (await state.payload.db.findOne({ collection: 'users', where: { email: { equals: '[email protected]' } } })) as unknown as { hash: string; salt: string }
|
||||
expect(await passwordMatches(doc, PASSWORD)).toBe(true)
|
||||
expect(await passwordMatches(doc, 'nope')).toBe(false)
|
||||
expect(await passwordMatches({ hash: `pbkdf2-sha512-v9:${doc.hash.split(':')[1]}`, salt: doc.salt }, PASSWORD)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Sign-in rules of the staff collections with twoFactor: false (signInRulesSuite.ts). */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { FOREIGN, PASSWORD, signInSite } from './signInRulesSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const { call, gqlLogin, idOf, login, session } = signInSite({ twoFactor: false })
|
||||
|
||||
describe('sign-in rules without 2FA', () => {
|
||||
test('a stranger\'s five failures do not keep the owner out; foreign origin refused; own e-mail needs the current password', async () => {
|
||||
for (let i = 0; i < 5; i++) {await login('[email protected]', 'a-wrong-password', '198.51.100.90')}
|
||||
expect((await login('[email protected]', PASSWORD, '198.51.100.90')).status).toBe(429)
|
||||
expect((await login('[email protected]', PASSWORD, '203.0.113.90')).status).toBe(200)
|
||||
expect((await gqlLogin('[email protected]', PASSWORD, '203.0.113.91', FOREIGN)).status).toBe(403)
|
||||
const cookie = await session('[email protected]', PASSWORD, '203.0.113.92')
|
||||
const id = await idOf('[email protected]')
|
||||
expect((await call(`/users/${id}`, { email: '[email protected]' }, { cookie }, 'PATCH')).status).toBe(400)
|
||||
expect((await call(`/users/${id}`, { currentPassword: PASSWORD, email: '[email protected]' }, { cookie }, 'PATCH')).status).toBe(200)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
/** accounts: { signInLimit: false, signInSameOrigin: false, confirmOwnChanges: false } — Payload's behaviour as before 1.18.0. */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { iapl } from '../src/plugin.js'
|
||||
import { FOREIGN, PASSWORD, signInSite } from './signInRulesSuite.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
|
||||
|
||||
const { call, idOf, login, session, state } = signInSite({ off: true })
|
||||
|
||||
describe('the sign-in rules switched off', () => {
|
||||
test("Payload's lock (5 from anywhere), foreign sign-in taken, own e-mail without a question", async () => {
|
||||
expect((await login('[email protected]', PASSWORD, '203.0.113.1', FOREIGN)).status).toBe(200)
|
||||
for (let i = 0; i < 5; i++) {await login('[email protected]', 'a-wrong-password', '198.51.100.95')}
|
||||
const locked = await login('[email protected]', PASSWORD, '203.0.113.95')
|
||||
expect(locked.status).toBe(401)
|
||||
expect((state.payload.collections['users' as never].config.auth as { maxLoginAttempts: number }).maxLoginAttempts).toBe(5)
|
||||
const cookie = await session('[email protected]', PASSWORD, '203.0.113.96')
|
||||
expect((await call(`/users/${await idOf('[email protected]')}`, { email: '[email protected]' }, { cookie }, 'PATCH')).status).toBe(200)
|
||||
})
|
||||
|
||||
test('values nobody understands stop the start', async () => {
|
||||
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const start = (accounts: unknown) => (async () => iapl({ accounts, i18n } as never)({ collections: [], secret: 'x' } as never))()
|
||||
await expect(start({ signInLimit: 0 })).rejects.toThrow(/accounts\.signInLimit must be/)
|
||||
await expect(start({ signInLimit: { perAddress: 0 } })).rejects.toThrow(/perAddress must be/)
|
||||
await expect(start({ signInSameOrigin: 'false' })).rejects.toThrow(/signInSameOrigin must be/)
|
||||
await expect(start({ confirmOwnChanges: 'no' })).rejects.toThrow(/confirmOwnChanges must be/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* Sign-in rules of the staff collections (1.18.0, accounts.signInLimit / signInSameOrigin / confirmOwnChanges), through
|
||||
* real HTTP requests against a running Payload. Shared by signInRules.test.ts (2FA on), signInRules2faOff.test.ts and
|
||||
* signInRulesOff.test.ts (every rule switched off): 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 { cookiesOf, startPayloadServer, type TestServer } from './http/server.js'
|
||||
import { totp } from './http/totp.js'
|
||||
|
||||
export const SECRET = 'JBSWY3DPEHPK3PXP'
|
||||
export const PASSWORD = 'a-long-test-password-1'
|
||||
export const FOREIGN = { origin: 'https://blog.site.example', 'sec-fetch-site': 'same-site' }
|
||||
|
||||
export type Answer = { body: string; status: number }
|
||||
|
||||
export function signInSite({ off = false, twoFactor = true }: { off?: boolean; twoFactor?: boolean } = {}) {
|
||||
const state = {} as { mails: string[]; payload: Payload; server: TestServer }
|
||||
beforeAll(async () => {
|
||||
state.mails = []
|
||||
const config = buildTestConfig({
|
||||
admin: { user: 'users' },
|
||||
collections: [
|
||||
{ slug: 'customers', access: { create: () => true }, auth: true, fields: [] },
|
||||
{ slug: 'media', fields: [], upload: { staticDir: '/tmp/iapl-sign-in-rules-media' } },
|
||||
],
|
||||
db: testDatabase('signinrules'),
|
||||
editor: lexicalEditor(),
|
||||
email: () => ({ name: 'count', defaultFromAddress: '[email protected]', defaultFromName: 'Site', sendEmail: async (m: { to?: unknown }) => void state.mails.push(String(m.to)) }) as never,
|
||||
plugins: [
|
||||
iapl({
|
||||
access: { authCollection: 'users' },
|
||||
...(off ? { accounts: { confirmOwnChanges: false, signInLimit: false, signInSameOrigin: false } } : {}),
|
||||
i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] },
|
||||
mail: { relay: false },
|
||||
twoFactor: twoFactor ? { issuer: 'Example', plugin: payloadTotp } : false,
|
||||
}),
|
||||
],
|
||||
secret: 'integration-test-secret-0123456789',
|
||||
telemetry: false,
|
||||
})
|
||||
state.payload = await getPayload({ config })
|
||||
state.server = await startPayloadServer(config)
|
||||
const make = (email: string, roles: string[]) =>
|
||||
state.payload.create({ collection: 'users' as never, data: { email, password: PASSWORD, roles, ...(twoFactor ? { totpSecret: SECRET } : {}) } as never })
|
||||
for (const [email, role] of [['[email protected]', 'admin'], ['[email protected]', 'admin'], ['[email protected]', 'editor'], ['[email protected]', 'editor'], ['[email protected]', 'editor'], ['[email protected]', 'editor']] as const) {
|
||||
await make(email, [role])
|
||||
}
|
||||
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 call = async (path: string, body: unknown, headers: Record<string, string> = {}, method = 'POST'): Promise<Answer> => {
|
||||
const res = await fetch(`${state.server.url}/api${path}`, { body: JSON.stringify(body), headers: { 'content-type': 'application/json', ...headers }, method })
|
||||
return { body: await res.text(), status: res.status }
|
||||
}
|
||||
const login = (email: string, password: string, ip: string, extra: Record<string, string> = {}) => call('/users/login', { email, password }, { 'x-real-ip': ip, ...extra })
|
||||
const gqlLogin = async (email: string, password: string, ip: string, extra: Record<string, string> = {}) => {
|
||||
const res = await call('/graphql', { query: `mutation { loginUser(email: ${JSON.stringify(email)}, password: ${JSON.stringify(password)}) { token } }` }, { 'x-real-ip': ip, ...extra })
|
||||
const error = (JSON.parse(res.body) as { errors?: { extensions?: { statusCode?: number }; message: string }[] }).errors?.[0]
|
||||
return { message: error?.message, status: error?.extensions?.statusCode }
|
||||
}
|
||||
/** A fully signed-in session (password, then the code when 2FA is on): the cookie header. */
|
||||
const session = async (email: string, password = PASSWORD, ip = '203.0.113.200') => {
|
||||
const res = await fetch(`${state.server.url}/api/users/login`, { body: JSON.stringify({ email, password }), headers: { 'content-type': 'application/json', 'x-real-ip': ip }, method: 'POST' })
|
||||
const first = cookiesOf(res)
|
||||
if (!twoFactor) {return first.join('; ')}
|
||||
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' })
|
||||
return [...first, ...cookiesOf(verify)].join('; ')
|
||||
}
|
||||
const idOf = async (email: string) => ((await state.payload.find({ collection: 'users' as never, overrideAccess: true, where: { email: { equals: email } } })).docs[0] as { id: number | string }).id
|
||||
const stored = async (email: string) => (await state.payload.find({ collection: 'users' as never, overrideAccess: true, showHiddenFields: true, where: { email: { equals: email } } })).docs[0] as { lockUntil?: null | string } | undefined
|
||||
return { call, gqlLogin, idOf, login, session, state, stored }
|
||||
}
|
||||
Reference in New Issue
Block a user