teqo-backup/tests/int/collectionAccessLockdown.int.spec.ts
Francisco Ignácio Fontoura Solla 473c82d09d Lock down CMS/PII collection access and leader routes
- users/signature/subscription/consent: all operations Payload-admin-only
  (Payload's default allowed ANY authenticated user, incl. campaign JWTs
  via /api — privilege escalation + PII exposure)
- post/tag/media/petition: public read kept, writes admin-only,
  readVersions admin-only on drafted collections
- leader lockdown: staff gates on /campanha/demandas* and /campanha/planos*;
  removed the dead leader branch of the demand detail page
- fix createLeaderSupporter: scope now asserted via the leader's engaged
  leadership municipalities (canReadMunicipality always denied leaders)
- candidate alignment: supporter area, invite creation, and escalated
  demand decisions now treat candidate as unrestricted staff consistently
- tests: collectionAccessLockdown.int.spec pins the lockdown; leased-consent
  helpers generalized (supporter keys); fixtures purge deletes residue
  invites before leaderships; stale leader-phone tests updated to the
  lockdown model; 'sem Praça' copy renamed to 'sem município'
2026-07-23 22:25:18 -03:00

207 lines
7.1 KiB
TypeScript

// @vitest-environment node
import { getPayload, type Payload } from 'payload'
import { beforeAll, describe, expect, it } from 'vitest'
import { createLeaderSupporterRecord } from '@/app/(campaign)/campanha/actions/leaderSupporter'
import config from '@/payload.config'
import { SUPPORTER_REGISTRATION_CONSENT_KEY } from '@/utilities/campaignConsent'
import { installCampaignFixtures } from '../helpers/campaignFixtures'
import {
SUPPORTER_REGISTRATION_CONSENT_LEASE_KEY,
withLeasedConsent,
} from '../helpers/testDatabaseLease'
let payload: Payload
const campaignFixtures = installCampaignFixtures({
getPayload: () => payload,
setPayload: (nextPayload) => {
payload = nextPayload
},
})
/** Runs `operation` with the shared supporter-registration consent guaranteed present. */
const withSupporterRegistrationConsent = <Result>(
operation: () => Promise<Result>,
): Promise<Result> =>
withLeasedConsent(
payload,
{
consentKey: SUPPORTER_REGISTRATION_CONSENT_KEY,
leaseKey: SUPPORTER_REGISTRATION_CONSENT_LEASE_KEY,
},
operation,
)
/**
* Collections without explicit `access` fall back to Payload's "any
* authenticated user" default — which includes campaign users presenting the
* `campaign-token` JWT against `/api/*`. These tests pin the lockdown added to
* the CMS/PII collections: campaign users (even the coordinator) must be
* denied, admins keep working, and the public keeps read-only access where
* intended.
*/
describe('CMS/PII collection access lockdown', () => {
beforeAll(async () => {
payload = await getPayload({ config: await config })
})
it('denies campaign users any access to admin accounts (users)', async () => {
const coordinator = await campaignFixtures().createCampaignUser('coordinator')
await expect(
payload.count({ collection: 'users', where: {}, user: coordinator, overrideAccess: false }),
).rejects.toThrow(/permissão|not allowed/i)
await expect(
payload.create({
collection: 'users',
data: { email: 'escalated@example.com', password: 'owned-by-attacker' },
user: coordinator,
overrideAccess: false,
}),
).rejects.toThrow(/permissão|not allowed/i)
})
it('lets admin users keep managing the users collection', async () => {
const fixtures = campaignFixtures()
const admin = await fixtures.createAdminUser()
const result = await payload.count({
collection: 'users',
where: { id: { equals: admin.id } },
user: admin,
overrideAccess: false,
})
expect(result.totalDocs).toBe(1)
})
it.each(['signature', 'subscription', 'consent'] as const)(
'denies campaign users and anonymous requests access to %s (PII/legal)',
async (collection) => {
const coordinator = await campaignFixtures().createCampaignUser('coordinator')
await expect(
payload.count({ collection, where: {}, user: coordinator, overrideAccess: false }),
).rejects.toThrow(/permissão|not allowed/i)
await expect(payload.count({ collection, where: {}, overrideAccess: false })).rejects.toThrow(
/permissão|not allowed/i,
)
},
)
it('lets admin users keep reading signatures and subscriptions', async () => {
const fixtures = campaignFixtures()
const admin = await fixtures.createAdminUser()
await expect(
payload.count({ collection: 'signature', where: {}, user: admin, overrideAccess: false }),
).resolves.toMatchObject({ totalDocs: expect.any(Number) })
await expect(
payload.count({ collection: 'subscription', where: {}, user: admin, overrideAccess: false }),
).resolves.toMatchObject({ totalDocs: expect.any(Number) })
})
it.each(['post', 'tag', 'petition', 'media'] as const)(
'denies campaign users create access to public-content collection %s',
async (collection) => {
const coordinator = await campaignFixtures().createCampaignUser('coordinator')
await expect(
payload.create({
collection,
data: {},
user: coordinator,
overrideAccess: false,
} as never),
).rejects.toThrow(/permissão|not allowed/i)
},
)
it.each(['post', 'tag', 'petition', 'media'] as const)(
'keeps anonymous read access to public-content collection %s',
async (collection) => {
await expect(
payload.count({ collection, where: {}, overrideAccess: false }),
).resolves.toMatchObject({ totalDocs: expect.any(Number) })
},
)
})
describe('leader supporter creation scope', () => {
beforeAll(async () => {
payload = await getPayload({ config: await config })
})
it('lets an engaged leader register a supporter in a linked municipality', async () => {
const fixtures = campaignFixtures()
const leaderAccount = await fixtures.createCampaignUser('leader')
const leaderContact = await fixtures.createContact()
const linked = await fixtures.getMunicipality()
await fixtures.createLeadership({
contact: leaderContact.id,
municipalities: [linked.id],
user: leaderAccount.id,
supportStatus: 'engajado',
})
const supporter = await withSupporterRegistrationConsent(() =>
createLeaderSupporterRecord(payload, leaderAccount, {
name: fixtures.value('Apoiador'),
phone: fixtures.phone(),
city: 'Salvador',
municipality: linked.id,
consentAccepted: true,
}),
)
fixtures.own('supporter', supporter.id)
expect(supporter.source).toBe('lideranca')
expect(fixtures.id(supporter.createdBy as never)).toBe(leaderAccount.id)
expect(fixtures.id(supporter.municipality as never)).toBe(linked.id)
})
it('rejects a supporter outside the leadership municipalities', async () => {
const fixtures = campaignFixtures()
const leaderAccount = await fixtures.createCampaignUser('leader')
const leaderContact = await fixtures.createContact()
const linked = await fixtures.getMunicipality()
const outside = await fixtures.getMunicipality()
await fixtures.createLeadership({
contact: leaderContact.id,
municipalities: [linked.id],
user: leaderAccount.id,
supportStatus: 'engajado',
})
await expect(
withSupporterRegistrationConsent(() =>
createLeaderSupporterRecord(payload, leaderAccount, {
name: fixtures.value('Apoiador'),
phone: fixtures.phone(),
city: 'Salvador',
municipality: outside.id,
consentAccepted: true,
}),
),
).rejects.toThrow('Você só pode cadastrar contatos nos municípios da sua liderança.')
})
it('rejects staff accounts on the leader-only contact tool', async () => {
const fixtures = campaignFixtures()
const advisor = await fixtures.createCampaignUser('advisor')
const municipality = await fixtures.getMunicipality()
await expect(
createLeaderSupporterRecord(payload, advisor, {
name: fixtures.value('Apoiador'),
phone: fixtures.phone(),
city: 'Salvador',
municipality: municipality.id,
consentAccepted: true,
}),
).rejects.toThrow('Somente lideranças podem cadastrar contatos por aqui.')
})
})