M1 (7): a password rule for staff accounts (accounts.password)
When a password is set on a staff collection — a new account, the first-user
screen, a change, a reset by e-mail; panel, API and Local API alike — it must
have at least 12 characters and not be the account's own e-mail address.
Existing passwords are never checked: a shorter one keeps logging in and meets
the rule when it is next changed. accounts.password: { minLength } | false.
No breached-password lookup; checkPassword and the hook are exported.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
c6fc0d21fe
commit
5d35b2c3f4
@@ -5,12 +5,16 @@
|
||||
import type { Config, Payload } from 'payload'
|
||||
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import { pbkdf2Sync, randomBytes } from 'node:crypto'
|
||||
import os from 'os'
|
||||
import path from 'path'
|
||||
import { getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { countBelowPanelRole, panelAccess, resolvePanelRole } from '../src/modules/access/panelRole.js'
|
||||
import { checkPassword, resolvePasswordRule } from '../src/modules/access/passwordRule.js'
|
||||
import { buildFirstUserGuard, openSignUpCollections, staffCreateAccess } from '../src/modules/access/selfRegistration.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
import { buildTestConfig } from './helpers.js'
|
||||
@@ -19,7 +23,7 @@ import { startPayloadServer, type TestServer } from './http/server.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
const i18n = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
const PASSWORD = 'a-long-test-password-1'
|
||||
let server: TestServer
|
||||
let payload: Payload
|
||||
@@ -150,6 +154,85 @@ describe('the lowest role stays out of the admin panel (accounts.panelRole)', ()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the password rule (accounts.password): twelve characters when a password is set', () => {
|
||||
let admin: Session
|
||||
const messageOf = async (res: Response) => JSON.stringify(await res.json())
|
||||
|
||||
beforeAll(async () => {
|
||||
admin = await login('users', '[email protected]')
|
||||
})
|
||||
|
||||
test('a new account: 11 characters refused with a clear message, 12 accepted', async () => {
|
||||
const short = await post('/users', { email: '[email protected]', password: 'abcdefghijk', roles: ['editor'] }, admin)
|
||||
expect(short.status).toBe(400)
|
||||
expect(await messageOf(short)).toMatch(/at least 12 characters/)
|
||||
expect((await post('/users', { email: '[email protected]', password: 'abcdefghijkl', roles: ['editor'] }, admin)).status).toBe(201)
|
||||
// counted in characters, not bytes
|
||||
expect((await post('/users', { email: '[email protected]', password: 'zażółć gęślą', roles: ['editor'] }, admin)).status).toBe(201)
|
||||
})
|
||||
|
||||
test('in Polish for a Polish panel', async () => {
|
||||
const res = await post('/users', { email: '[email protected]', password: 'krotkie', roles: ['editor'] }, { ...admin, 'accept-language': 'pl' })
|
||||
expect(res.status).toBe(400)
|
||||
expect(await messageOf(res)).toMatch(/co najmniej 12 znaków/)
|
||||
})
|
||||
|
||||
test('not the account\'s own e-mail address', async () => {
|
||||
const same = await post('/users', { email: '[email protected]', password: '[email protected]', roles: ['editor'] }, admin)
|
||||
expect(same.status).toBe(400)
|
||||
expect(await messageOf(same)).toMatch(/same as the e-mail/)
|
||||
})
|
||||
|
||||
test('changing a password: checked; changing anything else: not', async () => {
|
||||
const doc = (await payload.find({ collection: 'users' as never, where: { email: { equals: '[email protected]' } } })).docs[0]
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'tooshort' }), method: 'PATCH' })).status).toBe(400)
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: '[email protected]' }), method: 'PATCH' })).status).toBe(400) // its own address, looked up
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ roles: ['user'] }), method: 'PATCH' })).status).toBe(200)
|
||||
expect((await call(`/users/${doc.id}`, admin, { body: JSON.stringify({ password: 'a-new-long-password' }), method: 'PATCH' })).status).toBe(200)
|
||||
await login('users', '[email protected]', 'a-new-long-password')
|
||||
})
|
||||
|
||||
test('an EXISTING shorter password keeps logging in — nothing is checked at login', async () => {
|
||||
// an account as an earlier version left it: a 6-character password, stored the way Payload stored it then
|
||||
const old = await make('users', { email: '[email protected]', roles: ['editor'] })
|
||||
const salt = randomBytes(32).toString('hex')
|
||||
const hash = pbkdf2Sync('short1', salt, 25000, 512, 'sha256').toString('hex')
|
||||
await payload.db.updateOne({ id: old.id, collection: 'users' as never, data: { hash, salt } as never })
|
||||
const session = await login('users', '[email protected]', 'short1')
|
||||
expect(((await (await call('/users/me', session)).json()) as { user?: { email?: string } }).user?.email).toBe('[email protected]')
|
||||
// the rule meets it the next time the password is changed
|
||||
expect((await call(`/users/${old.id}`, session, { body: JSON.stringify({ password: 'short2' }), method: 'PATCH' })).status).toBe(400)
|
||||
})
|
||||
|
||||
test('a reset by e-mail is held to the rule too', async () => {
|
||||
const token = await payload.forgotPassword({ collection: 'users' as never, data: { email: '[email protected]' }, disableEmail: true })
|
||||
const short = await post('/users/reset-password', { password: 'tooshort', token })
|
||||
expect(short.status).toBe(400)
|
||||
expect(await messageOf(short)).toMatch(/at least 12 characters/)
|
||||
expect((await post('/users/reset-password', { password: 'reset-to-a-long-one', token })).status).toBe(200)
|
||||
})
|
||||
|
||||
test('visitor collections are not touched', async () => {
|
||||
expect((await post('/customers', { email: '[email protected]', password: 'abc123' })).status).toBe(201)
|
||||
})
|
||||
|
||||
test('the option, the checker and the switch', async () => {
|
||||
expect(resolvePasswordRule(undefined)).toEqual({ minLength: 12 })
|
||||
expect(resolvePasswordRule({ minLength: 16 })).toEqual({ minLength: 16 })
|
||||
expect(resolvePasswordRule(false)).toBeNull()
|
||||
for (const bad of ['12', 0, -1, 1.5, Number.NaN]) {expect(() => resolvePasswordRule({ minLength: bad as never })).toThrow(/minLength must be/)}
|
||||
expect(checkPassword('abcdefghijk')).toBe('short')
|
||||
expect(checkPassword('abcdefghijkl')).toBeNull()
|
||||
expect(checkPassword('abcd', { minLength: 4 })).toBeNull()
|
||||
expect(checkPassword('[email protected] ', { email: '[email protected]', minLength: 4 })).toBe('email')
|
||||
const hooks = async (options: Record<string, unknown>) =>
|
||||
(await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ admin: { user: 'users' }, collections: [{ slug: 'customers', auth: true, fields: [] }], secret: 'x' } as unknown as Config)).collections!.map((c) => [c.slug, c.hooks?.beforeOperation?.length ?? 0])
|
||||
expect(await hooks({})).toEqual([['customers', 1], ['users', 2]]) // customers: the first-user guard only
|
||||
expect(await hooks({ accounts: { password: false } })).toEqual([['customers', 1], ['users', 1]])
|
||||
expect(await hooks({ accounts: false })).toEqual([['customers', 0], ['users', 0]])
|
||||
})
|
||||
})
|
||||
|
||||
describe('accounts.panelRole: the config', () => {
|
||||
const build = (options: Record<string, unknown>, incoming: Partial<Config> = {}) =>
|
||||
ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false, ...options } as never)({ collections: [], secret: 'x', ...incoming } as unknown as Config)
|
||||
@@ -219,8 +302,9 @@ describe('accounts.adminOnlyCreate / firstUserRoute: the config', () => {
|
||||
test('the switches', async () => {
|
||||
const guards = (config: Config, slug: string) => of(config, slug).hooks?.beforeOperation?.length ?? 0
|
||||
const on = await build({})
|
||||
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([1, 1, 1, 0])
|
||||
const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all' } })
|
||||
// staff collections: the first-user guard and the password rule; a visitor collection: the guard only
|
||||
expect([guards(on, 'users'), guards(on, 'staff2'), guards(on, 'customers'), guards(on, 'pages')]).toEqual([2, 2, 1, 0])
|
||||
const payloadWay = await build({ accounts: { adminOnlyCreate: false, firstUserRoute: 'all', password: false } })
|
||||
expect(of(payloadWay, 'staff2').access?.create).toBeUndefined()
|
||||
expect(guards(payloadWay, 'staff2')).toBe(0)
|
||||
const off = await build({ accounts: false })
|
||||
|
||||
@@ -167,7 +167,7 @@ describe('forms against a real Payload', () => {
|
||||
test('open sign-up cannot self-assign admin — roles fall back to the default', async () => {
|
||||
const user = (await payload.create({
|
||||
collection: 'users',
|
||||
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
|
||||
data: { email: '[email protected]', password: 'Passw0rd!x-long', roles: ['admin'] } as never,
|
||||
overrideAccess: false,
|
||||
})) as unknown as { roles: string[] }
|
||||
expect(user.roles).toEqual(['user'])
|
||||
@@ -176,7 +176,7 @@ describe('forms against a real Payload', () => {
|
||||
test('seed / Local API with overrideAccess can still create an admin', async () => {
|
||||
const admin = (await payload.create({
|
||||
collection: 'users',
|
||||
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
|
||||
data: { email: '[email protected]', password: 'Passw0rd!x-long', roles: ['admin'] } as never,
|
||||
})) as unknown as { roles: string[] }
|
||||
expect(admin.roles).toEqual(['admin'])
|
||||
})
|
||||
@@ -401,7 +401,7 @@ describe('forms access', () => {
|
||||
|
||||
const user = (await payload.create({
|
||||
collection: 'users',
|
||||
data: { email: '[email protected]', password: 'Passw0rd!x' } as never,
|
||||
data: { email: '[email protected]', password: 'Passw0rd!x-long' } as never,
|
||||
})) as unknown as Record<string, unknown>
|
||||
await expect(
|
||||
payload.find({ collection: 'form-submissions' as never, overrideAccess: false, user: { ...user, collection: 'users' } as never }),
|
||||
|
||||
Reference in New Issue
Block a user