From 78d07f87523c2b3559450b5fdf9537051402a9fc Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 31 Jul 2026 04:57:05 +0000 Subject: [PATCH 1/4] security: lock public globals update to payloadAdminOnly (Pass 4 P0) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The four public globals (site-settings, home, metadata, privacy-policy) spelled update access as "any authenticated user" — and campaign JWTs authenticate against /api/*, so any campaign session (leader included) could PATCH the public site. payloadAdminOnly matches the collection lockdown precedent; editors lose config-global writes deliberately (content editing stays on canManagePublishedContent collections). Pins: identity + deny (coordinator/editor) + allow (admin fn) + anonymous read in collectionAccessLockdown.int.spec.ts. Recurrence guard: globalAccessConventions.unit.spec.ts bans the Boolean(user) shape in src/globals. Co-authored-by: Francisco Solla --- src/globals/HomePage.ts | 4 +- src/globals/Metadata.ts | 4 +- src/globals/PrivacyPolicy.ts | 5 +- src/globals/SiteSettings.ts | 5 +- .../int/collectionAccessLockdown.int.spec.ts | 75 ++++++++++++++++++- .../unit/globalAccessConventions.unit.spec.ts | 30 ++++++++ 6 files changed, 118 insertions(+), 5 deletions(-) create mode 100644 tests/unit/globalAccessConventions.unit.spec.ts diff --git a/src/globals/HomePage.ts b/src/globals/HomePage.ts index 72b65538..b23a2178 100644 --- a/src/globals/HomePage.ts +++ b/src/globals/HomePage.ts @@ -1,3 +1,4 @@ +import { payloadAdminOnly } from '@/utilities/campaignAccess' import { revalidateGlobal } from '@/utilities/globals' import { GlobalConfig } from 'payload' @@ -13,7 +14,8 @@ export const HomePage: GlobalConfig = { }, access: { read: () => true, - update: ({ req: { user } }) => Boolean(user), + // Admin-only like the other site globals (Pass 4) — campaign JWTs reach /api/*. + update: payloadAdminOnly, }, hooks: { afterChange: [revalidate], diff --git a/src/globals/Metadata.ts b/src/globals/Metadata.ts index 8b3802e9..7e96431b 100644 --- a/src/globals/Metadata.ts +++ b/src/globals/Metadata.ts @@ -1,3 +1,4 @@ +import { payloadAdminOnly } from '@/utilities/campaignAccess' import { revalidateGlobal } from '@/utilities/globals' import { GlobalConfig } from 'payload' @@ -13,7 +14,8 @@ export const Metadata: GlobalConfig = { }, access: { read: () => true, - update: ({ req: { user } }) => Boolean(user), + // Admin-only like the other site globals (Pass 4) — campaign JWTs reach /api/*. + update: payloadAdminOnly, }, hooks: { afterChange: [revalidate], diff --git a/src/globals/PrivacyPolicy.ts b/src/globals/PrivacyPolicy.ts index e3ed4749..09c68f89 100644 --- a/src/globals/PrivacyPolicy.ts +++ b/src/globals/PrivacyPolicy.ts @@ -1,3 +1,4 @@ +import { payloadAdminOnly } from '@/utilities/campaignAccess' import { revalidateGlobal } from '@/utilities/globals' import type { GlobalConfig } from 'payload' @@ -18,7 +19,9 @@ export const PrivacyPolicy: GlobalConfig = { }, access: { read: () => true, - update: ({ req: { user } }) => Boolean(user), + // Legal text: admin-only like the other site globals (Pass 4) — campaign + // JWTs reach /api/*. + update: payloadAdminOnly, }, hooks: { afterChange: [revalidate], diff --git a/src/globals/SiteSettings.ts b/src/globals/SiteSettings.ts index 624c255b..d1a09cb5 100644 --- a/src/globals/SiteSettings.ts +++ b/src/globals/SiteSettings.ts @@ -1,3 +1,4 @@ +import { payloadAdminOnly } from '@/utilities/campaignAccess' import { revalidateGlobal } from '@/utilities/globals' import type { GlobalConfig } from 'payload' @@ -13,7 +14,9 @@ export const SiteSettings: GlobalConfig = { }, access: { read: () => true, - update: ({ req: { user } }) => Boolean(user), + // Site-wide config: campaign JWTs authenticate against /api/*, so "any + // authenticated user" here was a write path into the public site (Pass 4). + update: payloadAdminOnly, }, hooks: { afterChange: [revalidate], diff --git a/tests/int/collectionAccessLockdown.int.spec.ts b/tests/int/collectionAccessLockdown.int.spec.ts index 4513b330..df1001f1 100644 --- a/tests/int/collectionAccessLockdown.int.spec.ts +++ b/tests/int/collectionAccessLockdown.int.spec.ts @@ -12,9 +12,13 @@ import { createLeaderSupporterRecord } from '@/app/(campaign)/campanha/actions/l import { Media } from '@/collections/Media' import { Post } from '@/collections/Post' import { Tag } from '@/collections/Tag' +import { HomePage } from '@/globals/HomePage' +import { Metadata } from '@/globals/Metadata' +import { PrivacyPolicy } from '@/globals/PrivacyPolicy' +import { SiteSettings } from '@/globals/SiteSettings' import { relationshipId } from '@/lib/relationship' import config from '@/payload.config' -import { canManagePublishedContent } from '@/utilities/access/shared' +import { canManagePublishedContent, payloadAdminOnly } from '@/utilities/access/shared' import { SUPPORTER_REGISTRATION_CONSENT_KEY } from '@/utilities/campaignConsent' import { installCampaignFixtures } from '../helpers/campaignFixtures' @@ -244,6 +248,75 @@ describe('CMS/PII collection access lockdown', () => { ) }) +/** + * The globals sibling of the collection lockdown above: until Pass 4 the four + * public globals spelled `update` as "any authenticated user", and campaign + * JWTs authenticate against `/api/*` — a campaign session (leader included) + * could PATCH the public site's settings, home, metadata and privacy policy. + * The allow path is asserted on the access function itself because a real + * `updateGlobal` fires the afterChange `revalidateTag` outside Next. + */ +describe('public globals update lockdown', () => { + const publicGlobals = [ + { config: SiteSettings, slug: 'site-settings' }, + { config: HomePage, slug: 'home' }, + { config: Metadata, slug: 'metadata' }, + { config: PrivacyPolicy, slug: 'privacy-policy' }, + ] as const + + beforeAll(async () => { + payload = await getPayload({ config: await config }) + }) + + it('spells update as payloadAdminOnly on every public global', () => { + for (const { config: globalConfig } of publicGlobals) { + expect(globalConfig.access?.update).toBe(payloadAdminOnly) + } + }) + + it.each(publicGlobals)('denies campaign users update on global %s', async ({ slug }) => { + const coordinator = await campaignFixtures().createCampaignUser('coordinator') + + await expect( + payload.updateGlobal({ + slug, + data: {}, + user: coordinator, + overrideAccess: false, + }), + ).rejects.toThrow(/permissão|not allowed/i) + }) + + it.each(publicGlobals)('denies editors update on global %s', async ({ slug }) => { + const editor = await campaignFixtures().createEditorUser() + + await expect( + payload.updateGlobal({ + slug, + data: {}, + user: editor, + overrideAccess: false, + }), + ).rejects.toThrow(/permissão|not allowed/i) + }) + + it('lets payload admins update through the access function', async () => { + const admin = await campaignFixtures().createAdminUser() + + for (const { config: globalConfig } of publicGlobals) { + expect(globalConfig.access?.update?.({ req: stub({ user: admin }) })).toBe( + true, + ) + } + }) + + it.each(publicGlobals)('keeps anonymous read access on global %s', async ({ slug }) => { + // Never-saved globals resolve with field defaults (no id) — the pin is + // that anonymous read is not denied, not the document shape. + await expect(payload.findGlobal({ slug, overrideAccess: false })).resolves.toBeDefined() + }) +}) + describe('leader supporter creation scope', () => { beforeAll(async () => { payload = await getPayload({ config: await config }) diff --git a/tests/unit/globalAccessConventions.unit.spec.ts b/tests/unit/globalAccessConventions.unit.spec.ts new file mode 100644 index 00000000..297c7451 --- /dev/null +++ b/tests/unit/globalAccessConventions.unit.spec.ts @@ -0,0 +1,30 @@ +import { readdirSync, readFileSync } from 'node:fs' +import { resolve } from 'node:path' +import { describe, expect, it } from 'vitest' + +// Pass 4 (2026-07-31): the four public globals spelled `update` as +// `({ req: { user } }) => Boolean(user)` — "any authenticated user" — and +// campaign JWTs authenticate against `/api/*`, so a campaign session (leader +// included) could PATCH the public site's settings, home, metadata and privacy +// policy. The lockdown is `payloadAdminOnly`; this guard keeps the +// any-authenticated shape out of global update access for good. Collections +// are covered elsewhere (every collection declares access; lockdown pins live +// in `collectionAccessLockdown.int.spec.ts`). +describe('global update access lockdown (Pass 4)', () => { + const globalsRoot = resolve(process.cwd(), 'src/globals') + + it('never spells global update access as "any authenticated user"', () => { + const offenders: string[] = [] + + for (const entry of readdirSync(globalsRoot, { withFileTypes: true })) { + if (!entry.isFile() || !entry.name.endsWith('.ts')) continue + const source = readFileSync(resolve(entry.parentPath, entry.name), 'utf8') + if (/=>\s*Boolean\(user\)/.test(source)) offenders.push(entry.name) + } + + expect( + offenders, + 'global update access must name a policy (payloadAdminOnly, isPayloadAdmin…), not Boolean(user)', + ).toEqual([]) + }) +}) From a7f0bdc1f7df024a34f2a72212f877a8af4ea08a Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 31 Jul 2026 04:57:05 +0000 Subject: [PATCH 2/4] refactor(notifications): bell loaders read through owner access, no bypass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit countUnreadNotifications/loadNotificationList took a caller-supplied recipientID with module-level admin bypass — one misuse away from reading someone else's inbox. They now take the actor (CampaignUser) and read with overrideAccess: false under canReadOwnNotifications, keeping the explicit recipient filter as a second fence. Pin: owner isolation at the loader level in campaignNotifications.int.spec.ts. Co-authored-by: Francisco Solla --- .../campanha/actions/notifications.ts | 4 +- .../notification/notificationList.ts | 27 ++++++++----- tests/int/campaignNotifications.int.spec.ts | 40 +++++++++++++++++++ 3 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/app/(campaign)/campanha/actions/notifications.ts b/src/app/(campaign)/campanha/actions/notifications.ts index a31c3902..ecefb661 100644 --- a/src/app/(campaign)/campanha/actions/notifications.ts +++ b/src/app/(campaign)/campanha/actions/notifications.ts @@ -43,7 +43,7 @@ export const loadNotificationBellData = async (): Promise diff --git a/src/utilities/notification/notificationList.ts b/src/utilities/notification/notificationList.ts index 1a49b9dc..bf98dd92 100644 --- a/src/utilities/notification/notificationList.ts +++ b/src/utilities/notification/notificationList.ts @@ -1,13 +1,13 @@ import 'server-only' -/** Trusted server reads in this module use admin bypass (`overrideAccess: true`). */ +import type { Payload } from 'payload' import type { NotificationListItem, NotificationPayload, NotificationType, } from '@/lib/notificationContract' -import type { Notification } from '@/payload-types' +import type { CampaignUser, Notification } from '@/payload-types' export type { NotificationListItem } from '@/lib/notificationContract' @@ -33,33 +33,40 @@ const toNotificationListItem = (doc: Notification): NotificationListItem | null } } +// Reads go through collection access (`canReadOwnNotifications` scopes to the +// recipient) with the explicit recipient filter as a second fence: the actor +// is the only thing these loaders accept, so a caller cannot ask for someone +// else's inbox. No admin bypass — that is what the create/update paths are +// for, and they live in the domain hooks/actions with their own justifications. export const countUnreadNotifications = async ( - payload: import('payload').Payload, - recipientID: number, + payload: Payload, + user: CampaignUser, ): Promise => { const result = await payload.count({ collection: 'notification', where: { - and: [{ recipient: { equals: recipientID } }, { readAt: { exists: false } }], + and: [{ recipient: { equals: user.id } }, { readAt: { exists: false } }], }, - overrideAccess: true, + user, + overrideAccess: false, }) return result.totalDocs } export const loadNotificationList = async ( - payload: import('payload').Payload, - recipientID: number, + payload: Payload, + user: CampaignUser, limit = 40, ): Promise => { const result = await payload.find({ collection: 'notification', - where: { recipient: { equals: recipientID } }, + where: { recipient: { equals: user.id } }, depth: 0, limit, sort: '-createdAt', - overrideAccess: true, + user, + overrideAccess: false, }) return result.docs diff --git a/tests/int/campaignNotifications.int.spec.ts b/tests/int/campaignNotifications.int.spec.ts index fb244b26..526c2422 100644 --- a/tests/int/campaignNotifications.int.spec.ts +++ b/tests/int/campaignNotifications.int.spec.ts @@ -4,6 +4,10 @@ import { getPayload, type Payload } from 'payload' import { beforeAll, describe, expect, it } from 'vitest' import config from '@/payload.config' +import { + countUnreadNotifications, + loadNotificationList, +} from '@/utilities/notification/notificationList' import { installCampaignFixtures } from '../helpers/campaignFixtures' @@ -69,6 +73,42 @@ describe('notification access', () => { expect(visible.docs.map((doc) => doc.id)).toEqual([own.id]) }) + + it('reads the bell loaders through owner-scoped access (no bypass)', async () => { + const fixtures = campaignFixtures() + const [owner, other] = await Promise.all([ + fixtures.createCampaignUser('advisor'), + fixtures.createCampaignUser('advisor'), + ]) + + const own = await payload.create({ + collection: 'notification', + data: { + recipient: owner.id, + type: 'municipality_update', + payload: { title: 'Sino — própria', detail: 'Detalhe', href: '/campanha' }, + }, + overrideAccess: true, + }) + await payload.create({ + collection: 'notification', + data: { + recipient: other.id, + type: 'new_supporter', + payload: { title: 'Sino — alheia', detail: 'Detalhe', href: '/campanha' }, + }, + overrideAccess: true, + }) + + // The loaders take the actor, not a recipientID — a caller cannot ask for + // someone else's inbox (Pass 4: the previous recipientID+bypass shape + // trusted every call site). + await expect(loadNotificationList(payload, owner)).resolves.toEqual([ + expect.objectContaining({ id: own.id }), + ]) + await expect(countUnreadNotifications(payload, owner)).resolves.toBe(1) + await expect(countUnreadNotifications(payload, other)).resolves.toBe(1) + }) }) describe('pushSubscription access', () => { From c3fa60a4e88624003782eca0ff0d1831ca74a485 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20Ign=C3=A1cio=20Fontoura=20Solla?= Date: Fri, 31 Jul 2026 14:13:02 -0300 Subject: [PATCH 3/4] fix(e2e): scope B42 trend drawer past QuickActions (B79) --- tests/e2e/campaignMunicipalities.e2e.spec.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/e2e/campaignMunicipalities.e2e.spec.ts b/tests/e2e/campaignMunicipalities.e2e.spec.ts index e6d36d1d..fcc80a20 100644 --- a/tests/e2e/campaignMunicipalities.e2e.spec.ts +++ b/tests/e2e/campaignMunicipalities.e2e.spec.ts @@ -382,7 +382,8 @@ test.describe('Municípios — cards no celular (B42)', () => { await expect(page.getByRole('link', { name: 'Abrir município' })).toHaveCount(0) await card.getByRole('button', { name: 'Editar tendência política' }).click() - const drawer = page.locator('[data-slot="drawer-popup"]') + // B79 keeps CampaignQuickActionsDrawer mounted (modal=false); scope to the trend dialog. + const drawer = page.getByRole('dialog', { name: 'Editar tendência' }) await expect(drawer).toBeVisible() await expect(drawer.getByText(municipality.name, { exact: true })).toBeVisible() await expect(page).toHaveURL(listURL) From 2a93d012ddfe999bdb3dae086a53ed317d028625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Francisco=20Ign=C3=A1cio=20Fontoura=20Solla?= Date: Fri, 31 Jul 2026 14:18:25 -0300 Subject: [PATCH 4/4] style: prettier A6-pre dobradinha baseline plan --- docs/plans/dobradinha-baseline-2022-pre-reconcile.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plans/dobradinha-baseline-2022-pre-reconcile.md b/docs/plans/dobradinha-baseline-2022-pre-reconcile.md index e6553712..24085136 100644 --- a/docs/plans/dobradinha-baseline-2022-pre-reconcile.md +++ b/docs/plans/dobradinha-baseline-2022-pre-reconcile.md @@ -7,7 +7,7 @@ Responsável: — ## Contexto -O PR #82 (A6) entrega o card **"Dobradinhas potenciais para 2026"** na aba Eleições do detalhe do município: candidatos proporcionais com `runningAgain2026 = sim`, ranqueados por score `0,6 alinhamento + 0,4 força local 2022`. Enquanto o TSE não publica as candidaturas de 2026 e a Fase 5 não reconcilia `runningAgain2026`, o loader retorna `{ status: 'pending2026' }` e o card mostra *"Indisponível até as candidaturas de 2026"*. +O PR #82 (A6) entrega o card **"Dobradinhas potenciais para 2026"** na aba Eleições do detalhe do município: candidatos proporcionais com `runningAgain2026 = sim`, ranqueados por score `0,6 alinhamento + 0,4 força local 2022`. Enquanto o TSE não publica as candidaturas de 2026 e a Fase 5 não reconcilia `runningAgain2026`, o loader retorna `{ status: 'pending2026' }` e o card mostra _"Indisponível até as candidaturas de 2026"_. Os dados de **2022 já estão no banco** (`electionCandidate` + `electionCandidateVote` via `pnpm db:seed:tse`). O staff precisa da inteligência **agora** — quem teve força local em 2022 e qual o alinhamento partidário — para priorizar dobradinhas antes de agosto. @@ -30,7 +30,7 @@ Os dados de **2022 já estão no banco** (`electionCandidate` + `electionCandida ## Questões em aberto — RESOLVIDAS (proposta) -- **Copy do estado provisório** — RESOLVIDA. Título mantém "Dobradinhas potenciais para 2026"; subtítulo/aviso: *"Lista provisória com base em quem concorreu aqui em 2022. Atualiza automaticamente quando o TSE publicar as candidaturas de 2026."* +- **Copy do estado provisório** — RESOLVIDA. Título mantém "Dobradinhas potenciais para 2026"; subtítulo/aviso: _"Lista provisória com base em quem concorreu aqui em 2022. Atualiza automaticamente quando o TSE publicar as candidaturas de 2026."_ - **Candidatos `runningAgain2026 = desconhecido` após reconcile** — RESOLVIDA. Fora da lista confirmada (mesmo critério conservador de A6: só `sim` entra). Não inventar parceiro sem confirmação. - **Badge "eleito em 2022"** — RESOLVIDA. Mantém no modo provisório e confirmado (campo `elected` já no registry).