Files
ipal-kit/test/routeInventory.test.ts

122 lines
5.7 KiB
TypeScript

/**
* The route inventory behind `pnpm routes:check` (IAWL idea 34): every REST route, GraphQL operation and Next route
* file of a built config, compared with a judged snapshot. The list is made from the config only, so the same
* config on MongoDB, Postgres and SQLite gives the same list (the check must not be flaky across databases).
*/
import type { Config, SanitizedConfig } from 'payload'
import { mongooseAdapter } from '@payloadcms/db-mongodb'
import { postgresAdapter } from '@payloadcms/db-postgres'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import { realpathSync } from 'node:fs'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { describe, expect, test, vi } from 'vitest'
import type { GraphqlSchemaLike } from '../src/modules/security/routeInventory.js'
import { compareRouteSnapshot, listNextRouteFiles, listPublicRoutes, updateRouteSnapshot } from '../src/modules/security/routeInventory.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
vi.mock('server-only', () => ({}))
async function configToSchema(config: SanitizedConfig): Promise<GraphqlSchemaLike> {
const next = realpathSync(path.resolve(import.meta.dirname, '../node_modules/@payloadcms/next'))
const graphql = realpathSync(path.join(next, '..', 'graphql'))
const mod = (await import(pathToFileURL(path.join(graphql, 'dist/index.js')).href)) as { configToSchema: (c: SanitizedConfig) => { schema: GraphqlSchemaLike } }
return mod.configToSchema(config).schema
}
const adapters = {
mongodb: () => mongooseAdapter({ url: 'mongodb://127.0.0.1:1/never-connected' }),
postgres: () => postgresAdapter({ pool: { connectionString: 'postgres://[email protected]:1/never-connected' } }),
sqlite: () => sqliteAdapter({ client: { url: 'file::memory:' } }),
}
const build = (db: Config['db']) =>
buildTestConfig({
collections: [
{ slug: 'users', auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }], versions: { drafts: true } },
{ slug: 'media', fields: [], upload: true },
],
db,
editor: lexicalEditor(),
plugins: [
iapl({
access: { authCollection: 'users' },
cookieScanner: { crawl: { serviceUrl: 'http://crawler.test', siteUrl: 'http://site.test', token: 'x' } },
forms: { attachments: true, emailLayout: true },
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
pages: { slug: 'pages' },
seo: { collections: ['pages'] },
stats: true,
twoFactor: false,
} as never),
],
secret: 'route-inventory-test',
telemetry: false,
} as unknown as Config)
describe('listPublicRoutes', () => {
test('lists Payload\'s routes, the plugin\'s own and GraphQL; the same on MongoDB, Postgres and SQLite', async () => {
const lists: Record<string, string[]> = {}
for (const [name, adapter] of Object.entries(adapters)) {
const config = await build(adapter())
lists[name] = listPublicRoutes(config, { graphqlSchema: await configToSchema(config) })
}
const sqlite = lists.sqlite
expect(lists.mongodb).toEqual(sqlite)
expect(lists.postgres).toEqual(sqlite)
for (const id of [
'POST /api/users/login',
'POST /api/users/first-register',
'GET /api/pages/versions',
'POST /api/ipal/forms/submit',
'POST /api/ipal/hit',
'POST /api/ipal/cookie-crawl/results',
'POST /api/globals/site-integrations',
'graphql query Users',
'graphql mutation loginUser',
]) {
expect(sqlite, id).toContain(id)
}
expect(sqlite).toEqual([...sqlite].sort())
}, 60_000)
test('Next route files: exported methods, route groups left out, metadata routes', () => {
const code: Record<string, string> = {
'(frontend)/[locale]/page.tsx': 'export default function Page() {}',
'(payload)/api/[...slug]/route.ts': 'export const GET = a\nexport const POST = b\nexport const OPTIONS = c',
'api/health/route.ts': 'export async function GET() {}',
'api/mcp/route.ts': "export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'",
'md/[locale]/[[...slug]]/route.ts': 'export const dynamic = "force-dynamic"\nexport function GET() {}',
'robots.ts': 'export default function robots() {}',
'sitemap.xml/route.ts': 'export const GET = handler',
}
expect(listNextRouteFiles(Object.keys(code), (f) => code[f])).toEqual([
{ methods: ['GET', 'OPTIONS', 'POST'], path: '/api/[...slug]' },
{ methods: ['GET'], path: '/api/health' },
{ methods: ['GET', 'POST'], path: '/api/mcp' },
{ methods: ['GET'], path: '/md/[locale]/[[...slug]]' },
{ methods: ['GET'], path: '/robots.txt' },
{ methods: ['GET'], path: '/sitemap.xml' },
])
})
})
describe('the judged snapshot', () => {
test('a new route, an empty or TODO reason fail; a gone route is listed', () => {
const diff = compareRouteSnapshot(['GET /a', 'GET /b', 'GET /new', 'GET /todo'], { 'GET /a': 'public: published pages', 'GET /b': ' ', 'GET /old': 'x', 'GET /todo': 'TODO judge' })
expect(diff).toEqual({ gone: ['GET /old'], unexplained: ['GET /b', 'GET /todo'], unjudged: ['GET /new'] })
})
test('--update adds new routes with an empty reason (still failing) and drops gone ones, keeping the reasons', () => {
const next = updateRouteSnapshot(['GET /a', 'GET /new'], { 'GET /a': 'kept reason', 'GET /old': 'x' })
expect(next).toEqual({ 'GET /a': 'kept reason', 'GET /new': '' })
expect(compareRouteSnapshot(['GET /a', 'GET /new'], next).unexplained).toEqual(['GET /new'])
})
})