Merge claude/security-c-files-jobs-tests-cfba70: resolved paths in the bins and starter, proxy matcher ends at /, closed doors on the built site, every public route judged
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -493,6 +493,14 @@ describe('security and deep status', () => {
|
||||
expect(rules(await doctor(root, ['security']))).toContain('csp:info')
|
||||
expect(rules(await doctor(root, ['csp'], { config: { seen: { 'csp-report-only': '2026-09-01' } } }))).toEqual(['csp:warning'])
|
||||
})
|
||||
test('proxy-matcher: a lookahead that does not end api / admin / _next at "/" is a warning; the 1.17.1 literal is not', async () => {
|
||||
const proxy = (matcher: string) => project({ ...base(), 'src/proxy.ts': `export const config = { matcher: ['${matcher}'] }` })
|
||||
expect(rules(await doctor(proxy('/((?!api|admin|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning'])
|
||||
expect(rules(await doctor(proxy('/((?!api|cms|_next|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual(['proxy-matcher:warning'])
|
||||
expect(rules(await doctor(proxy('/((?!(?:api|admin|_next)(?:/|$)|.*\\\\..*).*)'), ['proxy-matcher']))).toEqual([])
|
||||
expect(rules(await doctor(project(base()), ['proxy-matcher']))).toEqual([])
|
||||
})
|
||||
|
||||
test('client-hints: withSecurityConfig inside withPayload is reported (info); outside, or kept on purpose, is not', async () => {
|
||||
const inner = project(next('export default withPayload(\n withSecurityConfig(nextConfig))'))
|
||||
expect(rules(await doctor(inner, ['client-hints']))).toEqual(['client-hints:info'])
|
||||
|
||||
@@ -367,6 +367,13 @@ describe('3 · refused files leave no submission and send no e-mail', () => {
|
||||
await refused([{ name: 'cv.docx', data: ARCHIVE }], notAcceptable('cv.docx')) // a ZIP that is not a Word file
|
||||
})
|
||||
|
||||
test('a program inside an Office file is found also with trailing dots or spaces (Windows drops them)', async () => {
|
||||
for (const entry of ['word/setup.exe', 'word/setup.exe.', 'word/setup.exe ', 'word/setup.EXE. .', 'word/vbaProject.bin.']) {
|
||||
const data = zip({ '[Content_Types].xml': '<Types/>', [entry]: 'x', 'word/document.xml': '<w:document/>' })
|
||||
await refused([{ name: 'cv.docx', data }], notAcceptable('cv.docx'))
|
||||
}
|
||||
})
|
||||
|
||||
test('extra files: more than the field allows, a file under a key that is no File field', async () => {
|
||||
await refused(
|
||||
[{ name: 'a.pdf', data: PDF }, { name: 'b.pdf', data: PDF }],
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* `iapl-skills --dest`: the "not the project root" rule is checked on RESOLVED paths. Before 1.17.1 the check
|
||||
* compared the paths as typed, so `--dest root-link` (a link to `.`), `--dest ..` or `--dest /` passed it, and the
|
||||
* run removed the `iapl-*` folders of the project root, its parent or the filesystem root (IAWL idea 13).
|
||||
*/
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterAll, describe, expect, test } from 'vitest'
|
||||
|
||||
const bin = path.resolve(import.meta.dirname, '../bin/iapl-skills.mjs')
|
||||
const made: string[] = []
|
||||
afterAll(() => {
|
||||
for (const dir of made) {rmSync(dir, { force: true, recursive: true })}
|
||||
})
|
||||
|
||||
/** A throw-away project: a parent folder holding `project/` with an `iapl-mine` folder in its root. */
|
||||
function project() {
|
||||
const parent = realpathSync(mkdtempSync(path.join(tmpdir(), 'iapl-skills-dest-')))
|
||||
made.push(parent)
|
||||
const dir = path.join(parent, 'project')
|
||||
mkdirSync(path.join(dir, 'iapl-mine'), { recursive: true })
|
||||
writeFileSync(path.join(dir, 'iapl-mine', 'keep.txt'), 'the project root holds this folder')
|
||||
mkdirSync(path.join(parent, 'iapl-next-door'))
|
||||
return { dir, parent }
|
||||
}
|
||||
|
||||
const run = (cwd: string, dest: string) =>
|
||||
spawnSync(process.execPath, [bin, '--dest', dest, '--no-pointer'], { cwd, encoding: 'utf8' })
|
||||
|
||||
describe('iapl-skills --dest is judged after the path is resolved', () => {
|
||||
test('a link to the project root is refused and the root keeps its iapl-* folders', () => {
|
||||
const { dir } = project()
|
||||
symlinkSync('.', path.join(dir, 'root-link'))
|
||||
const result = run(dir, 'root-link')
|
||||
expect(result.status, result.stdout).toBe(1)
|
||||
expect(result.stderr).toMatch(/not the project root/)
|
||||
expect(existsSync(path.join(dir, 'iapl-mine', 'keep.txt'))).toBe(true)
|
||||
})
|
||||
|
||||
test('a folder that holds the project (the parent, the filesystem root) is refused', () => {
|
||||
const { dir, parent } = project()
|
||||
for (const dest of ['..', '/', parent]) {
|
||||
const result = run(dir, dest)
|
||||
expect([dest, result.status]).toEqual([dest, 1])
|
||||
}
|
||||
expect(existsSync(path.join(parent, 'iapl-next-door'))).toBe(true)
|
||||
})
|
||||
|
||||
test('a folder inside the project, a new one, or one elsewhere still works', () => {
|
||||
const { dir, parent } = project()
|
||||
expect(run(dir, '.agents/skills').status).toBe(0)
|
||||
expect(existsSync(path.join(dir, '.agents/skills/iapl-setup/SKILL.md'))).toBe(true)
|
||||
const shared = path.join(parent, 'shared-skills')
|
||||
expect(run(dir, shared).status).toBe(0)
|
||||
expect(existsSync(path.join(shared, 'iapl-setup/SKILL.md'))).toBe(true)
|
||||
expect(existsSync(path.join(dir, 'iapl-mine', 'keep.txt'))).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* The documented proxy matcher, compiled by Next's own code (the function `next build` uses for `config.matcher`):
|
||||
* `api`, `admin` and `_next` are skipped only as a whole first segment. Before 1.17.1 `/administracja`, `/admin-guide`
|
||||
* or `/apis` skipped the proxy as well (IAWL idea 36: a deny rule by name must end at "/").
|
||||
*/
|
||||
import { readFileSync, realpathSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { DEFAULT_PROXY_MATCHER } from '../src/modules/i18n/createProxy.js'
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..')
|
||||
const next = realpathSync(path.join(root, 'node_modules/next'))
|
||||
const { getMiddlewareMatchers } = createRequire(import.meta.url)(path.join(next, 'dist/build/analysis/get-page-static-info.js')) as {
|
||||
getMiddlewareMatchers: (matchers: string[], nextConfig: object) => { regexp: string }[]
|
||||
}
|
||||
const runs = (matcher: string) => {
|
||||
const re = new RegExp(getMiddlewareMatchers([matcher], {})[0].regexp)
|
||||
return (pathname: string) => re.test(pathname)
|
||||
}
|
||||
|
||||
describe('the proxy matcher', () => {
|
||||
test('skips /api, /admin and /_next as whole segments and files; runs on pages that only START with those letters', () => {
|
||||
const proxy = runs(DEFAULT_PROXY_MATCHER[0])
|
||||
for (const skipped of ['/api', '/api/users', '/api/ipal/hit', '/admin', '/admin/', '/admin/collections/users', '/_next/static/chunk.js', '/robots.txt', '/sitemap.xml']) {
|
||||
expect([skipped, proxy(skipped)]).toEqual([skipped, false])
|
||||
}
|
||||
for (const page of ['/', '/o-nas', '/pl/o-nas', '/administracja', '/admin-guide', '/apis', '/api-docs', '/_nextish', '/md/pl/o-nas']) {
|
||||
expect([page, proxy(page)]).toEqual([page, true])
|
||||
}
|
||||
})
|
||||
|
||||
test('the reference site uses the same literal (Next reads it statically, it cannot be imported)', () => {
|
||||
const proxyFile = readFileSync(path.join(root, 'reference/src/proxy.ts'), 'utf8')
|
||||
expect(proxyFile).toContain(`matcher: ['${DEFAULT_PROXY_MATCHER[0].replace(/\\/g, '\\\\')}']`)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* 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'])
|
||||
})
|
||||
})
|
||||
+49
-2
@@ -1,4 +1,5 @@
|
||||
import { existsSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
@@ -29,7 +30,7 @@ import {
|
||||
unpackBundle,
|
||||
validateAnswers,
|
||||
} from '../src/exports/starter.js'
|
||||
import { externalSkillNames, resolveExternal } from '../src/modules/starter/cli.js'
|
||||
import { externalSkillNames, resolveExternal, writeFiles } from '../src/modules/starter/cli.js'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const reference = path.join(root, 'reference')
|
||||
@@ -257,3 +258,49 @@ describe.runIf(existsSync(path.join(reference, 'starter.manifest.json')))('start
|
||||
expect(files['src/instrumentation.ts']).not.toContain('cookieCrawl')
|
||||
})
|
||||
})
|
||||
|
||||
describe('starter: links and paths (IAWL ideas 12, 13)', () => {
|
||||
const site = () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'iapl-starter-links-'))
|
||||
const manifest: StarterManifest = { drop: [], keep: ['**'], placeholders: {}, schema: 1, template: [] }
|
||||
writeFileSync(path.join(dir, 'starter.manifest.json'), JSON.stringify(manifest))
|
||||
writeFileSync(path.join(dir, 'pnpm-lock.yaml'), "lockfileVersion: '9.0'\n")
|
||||
writeFileSync(path.join(dir, 'kept.ts'), 'export const a = 1\n')
|
||||
return dir
|
||||
}
|
||||
|
||||
it('a symbolic link is refused: its target is never read into the published bundle', () => {
|
||||
const dir = site()
|
||||
const secret = path.join(dir, '..', `${path.basename(dir)}-secret.txt`)
|
||||
writeFileSync(secret, 'PRIVATE KEY OF SOMEBODY ELSE')
|
||||
symlinkSync(secret, path.join(dir, 'leak.txt'))
|
||||
mkdirSync(path.join(dir, 'outside'))
|
||||
symlinkSync(path.dirname(secret), path.join(dir, 'outside', 'up'))
|
||||
try {
|
||||
expect(() => collectBundle(dir)).toThrow(/leak\.txt: symbolic link/)
|
||||
rmSync(path.join(dir, 'leak.txt'))
|
||||
// a link to a folder is not walked into either
|
||||
expect(() => collectBundle(dir)).toThrow(/outside\/up: symbolic link/)
|
||||
rmSync(path.join(dir, 'outside'), { force: true, recursive: true })
|
||||
expect(Object.keys(collectBundle(dir).files)).toEqual(['kept.ts'])
|
||||
} finally {
|
||||
rmSync(dir, { force: true, recursive: true })
|
||||
rmSync(secret, { force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('a bundle path outside the new folder stops the run before anything is written', () => {
|
||||
const parent = mkdtempSync(path.join(tmpdir(), 'iapl-starter-paths-'))
|
||||
const dir = path.join(parent, 'site')
|
||||
try {
|
||||
for (const bad of ['../escaped.txt', 'a/../../escaped.txt', path.join(parent, 'abs.txt')]) {
|
||||
expect(() => writeFiles(dir, { [bad]: 'no', 'ok.txt': 'fine' }), bad).toThrow(/outside the new folder/)
|
||||
}
|
||||
expect(readdirSync(parent)).toEqual([])
|
||||
writeFiles(dir, { 'ok.txt': 'fine', 'src/a/b.ts': 'x' })
|
||||
expect(readdirSync(dir).sort()).toEqual(['ok.txt', 'src'])
|
||||
} finally {
|
||||
rmSync(parent, { force: true, recursive: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user