Files
ipal-kit/test/signInRules.test.ts
T
Radosław SmolińskiandClaude Opus 5.5 52710021ef 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]>
2026-12-01 11:12:40 +01:00

122 lines
7.9 KiB
TypeScript

/** 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)
})
})