readPublished on version history: readPublishedVersions, and the documented form works (1.17.2)

readVersions: readPublished(), as access.md showed, answered every version read with 500 on
MongoDB, Postgres and SQLite: the rule returns the document's `_status` path, a version query
runs on the versions collection where the status is `version._status` (SQL: "Cannot find field
for path at _status"; MongoDB: TypeError in sanitizeQueryValue). Reported by a client project
upgrading to 1.17.1.

- readPublishedVersions(minimum): the version form, for readVersions.
- readPublished() carries a symbol mark (READ_PUBLISHED); iapl() swaps it on readVersions of the
  collections and globals it sees (withVersionReadRules, exported for plugins listed after it).
- Tests on the three adapters: the version list (REST, depth 0/2, Local API, GraphQL), one version
  by id, the count, a global, an explicit role; the 1.17.1 HTTP test now checks the status too.
- access.md says where each rule goes; AGENT.md, iapl-collection and iapl-audit skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 10:39:41 +01:00
co-authored by Claude Opus 5.5
parent fc70a34f3e
commit 4b17254135
10 changed files with 252 additions and 12 deletions
+5 -1
View File
@@ -140,7 +140,11 @@ describe('idea 23: drafts over REST and GraphQL', () => {
expect(asked.status).toBe(404)
expect(await asked.text()).not.toContain('szkic')
// the version list: a visitor sees published versions only
expect(await (await api('/guarded-pages/versions?limit=50')).text()).not.toContain('szkic')
const versions = await api('/guarded-pages/versions?limit=50&locale=pl')
expect(versions.status).toBe(200) // 1.17.1 answered 500 here: the check below alone passed on an error page
const list = await versions.text()
expect(list).toContain('Cennik')
expect(list).not.toContain('szkic')
})
test('readPublished(): an editor still sees the draft', async () => {
+173
View File
@@ -0,0 +1,173 @@
/**
* readPublished() on version history (`readVersions`) — reported by a client project upgrading to 1.17.1:
* `GET /api/pages/versions` answered 500 on MongoDB. The rule answered `{ _status: { equals: 'published' } }`, a path
* of the document, while a version query runs on the versions collection, where the status is `version._status`.
*
* Every way a version is read, for a visitor, a plain `user` account and an editor: the list (REST, Local API,
* GraphQL, `depth`), one version by id (REST, GraphQL — the panel's version view reads it the same way), the count.
* Real HTTP; SQLite by default, Postgres / MongoDB with IPAL_TEST_POSTGRES_URI / IPAL_TEST_MONGO_URI.
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { READ_PUBLISHED, readPublished, readPublishedVersions, withVersionReadRules } from '../src/modules/access/access.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
const PASSWORD = 'a-long-test-password-1'
let server: TestServer
let payload: Payload
const tokens: Record<'editor' | 'user', string> = { editor: '', user: '' }
let pageId: number | string
let neverPublishedId: number | string
const versionIds: { draft: (number | string)[]; published: (number | string)[] } = { draft: [], published: [] }
type Who = 'editor' | 'user' | 'visitor'
const headers = (who: Who) => ({ 'content-type': 'application/json', ...(who === 'visitor' ? {} : { authorization: `JWT ${tokens[who]}` }) })
const rest = async (pathname: string, who: Who) => {
const res = await fetch(`${server.url}/api${pathname}`, { headers: headers(who) })
return { body: await res.text(), status: res.status }
}
const gql = async (query: string, who: Who) => {
const res = await fetch(`${server.url}/api/graphql`, { body: JSON.stringify({ query }), headers: headers(who), method: 'POST' })
return { body: await res.text(), status: res.status }
}
const titles = (body: string) => [...body.matchAll(/"title":"([^"]+)"/g)].map((m) => m[1])
beforeAll(async () => {
const config = buildTestConfig({
admin: { user: 'users' },
collections: [
{
slug: 'pages',
access: { read: readPublished(), readVersions: readPublished() },
fields: [{ name: 'title', type: 'text', localized: true }, { name: 'related', type: 'relationship', relationTo: 'pages' }],
versions: { drafts: true, maxPerDoc: 20 },
},
// the explicit version rule, and a role other than the default
{ slug: 'notes', access: { read: readPublished('admin'), readVersions: readPublishedVersions('admin') }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } },
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-read-published-versions') } },
],
db: testDatabase('read_published_versions'),
editor: lexicalEditor(),
globals: [{ slug: 'banner', access: { read: readPublished(), readVersions: readPublished() }, fields: [{ name: 'title', type: 'text' }], versions: { drafts: true } }],
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] }, mail: { relay: false }, twoFactor: false })],
secret: 'read-published-versions-0123456789',
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
for (const role of ['editor', 'user'] as const) {
await payload.create({ collection: 'users' as never, data: { email: `${role}@example.com`, password: PASSWORD, roles: [role] } as never })
tokens[role] = ((await (await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: `${role}@example.com`, password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' })).json()) as { token: string }).token
}
await payload.create({ collection: 'notes' as never, data: { _status: 'published', title: 'Note published' } as never })
await payload.create({ collection: 'notes' as never, data: { _status: 'draft', title: 'Note draft' } as never, draft: true })
await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'published', title: 'Banner published' } as never })
await payload.updateGlobal({ slug: 'banner' as never, data: { _status: 'draft', title: 'Banner draft' } as never, draft: true })
pageId = (await payload.create({ collection: 'pages' as never, data: { _status: 'published', title: 'Published one' } as never, locale: 'pl' })).id
await payload.update({ id: pageId, collection: 'pages' as never, data: { _status: 'draft', title: 'Draft over it' } as never, draft: true, locale: 'pl' })
neverPublishedId = (await payload.create({ collection: 'pages' as never, data: { _status: 'draft', related: pageId, title: 'Never published' } as never, draft: true, locale: 'pl' })).id
const all = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl' })
for (const v of all.docs as unknown as { id: number | string; version: { _status?: string } }[]) {
versionIds[v.version._status === 'published' ? 'published' : 'draft'].push(v.id)
}
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
})
describe('readPublished() as readVersions', () => {
test.each(['visitor', 'user'] as const)('the version list answers a %s with published versions only (REST, depth 0 and 2)', async (who) => {
for (const q of ['?limit=100&depth=0', '?limit=100&depth=2&locale=pl']) {
const { body, status } = await rest(`/pages/versions${q}`, who)
expect(status).toBe(200)
expect(titles(body)).toContain('Published one')
expect(body).not.toContain('Draft over it')
expect(body).not.toContain('Never published')
}
})
test('an editor lists every version', async () => {
const { body, status } = await rest('/pages/versions?limit=100&depth=0&locale=pl', 'editor')
expect(status).toBe(200)
expect(titles(body)).toEqual(expect.arrayContaining(['Published one', 'Draft over it', 'Never published']))
})
test('one version by id: a published one is answered, a draft one is not found (REST)', async () => {
expect((await rest(`/pages/versions/${versionIds.published[0]}?locale=pl`, 'visitor')).status).toBe(200)
for (const id of versionIds.draft) {
const { body, status } = await rest(`/pages/versions/${id}?locale=pl`, 'visitor')
expect([403, 404]).toContain(status) // Payload refuses a version the rule's condition leaves out
expect(body).not.toMatch(/Draft over it|Never published/)
}
expect((await rest(`/pages/versions/${versionIds.draft[0]}?locale=pl`, 'editor')).status).toBe(200)
})
test('GraphQL: the list and one version, as a visitor', async () => {
const list = await gql('{ versionsPages(limit: 100, locale: pl) { totalDocs docs { id version { title _status } } } }', 'visitor')
expect(list.status).toBe(200)
expect(list.body).not.toContain('"errors"')
expect(list.body).toContain('Published one')
expect(list.body).not.toMatch(/Draft over it|Never published/)
const draft = await gql(`{ versionPage(id: "${versionIds.draft[0]}", locale: pl) { version { title } } }`, 'visitor')
expect(draft.body).not.toMatch(/Draft over it|Never published/)
})
test('Local API with access control: findVersions and countVersions as a visitor', async () => {
const found = await payload.findVersions({ collection: 'pages' as never, depth: 0, limit: 100, locale: 'pl', overrideAccess: false })
expect((found.docs as unknown as { version: { title?: string } }[]).map((d) => d.version.title)).toEqual(['Published one'])
const counted = await payload.countVersions({ collection: 'pages' as never, overrideAccess: false })
expect(counted.totalDocs).toBe(versionIds.published.length)
})
test('reading the documents still works as before (read: readPublished())', async () => {
expect((await rest(`/pages/${neverPublishedId}`, 'visitor')).status).toBe(404)
expect(titles((await rest(`/pages/${pageId}?locale=pl`, 'visitor')).body)).toContain('Published one')
expect(titles((await rest(`/pages/${pageId}?draft=true&locale=pl`, 'editor')).body)).toContain('Draft over it')
})
})
describe('the other ways in', () => {
test('readPublishedVersions(), with its own role: an editor is a visitor when the role is admin', async () => {
for (const who of ['visitor', 'editor'] as const) {
const { body, status } = await rest('/notes/versions?limit=50', who)
expect(status).toBe(200)
expect(body).toContain('Note published')
expect(body).not.toContain('Note draft')
}
})
test('a global: readVersions: readPublished() lists published versions only', async () => {
const { body, status } = await rest('/globals/banner/versions?limit=50', 'visitor')
expect(status).toBe(200)
expect(body).toContain('Banner published')
expect(body).not.toContain('Banner draft')
expect((await rest('/globals/banner/versions?limit=50', 'editor')).body).toContain('Banner draft')
})
test('withVersionReadRules swaps only a readPublished() rule, keeping its role (a plugin listed after iapl)', () => {
const own = () => true
const [swapped, kept, none] = withVersionReadRules([
{ slug: 'late', access: { readVersions: readPublished('admin') } },
{ slug: 'mine', access: { readVersions: own } },
{ slug: 'open' },
] as { access?: { readVersions?: unknown }; slug: string }[])!
const rule = swapped.access!.readVersions as (a: unknown) => unknown
expect(READ_PUBLISHED in rule).toBe(false)
expect(rule({ req: { payload: undefined, user: undefined } })).toEqual({ 'version._status': { equals: 'published' } })
expect(kept.access!.readVersions).toBe(own)
expect(none).toEqual({ slug: 'open' })
})
})