Files
ipal-kit/test/iawlIdeasB.test.ts
Radosław SmolińskiandClaude Opus 5.5 ecf03c8dc0 IAWL ideas, group B: sizes before work, one link rule, no stand-in locale, strict switches
- Request bodies from strangers are read only up to a cap, declared length or not:
  mail-service confirm, CSP reports, page views, MCP (maxBytes, 413). readCappedBody moves
  to shared/ (the consent log keeps exporting it).
- searchContent / createSearchRoute / MCP search: queryLimit (default 200 characters,
  10 words) before the database; an unknown ?locale is the default locale throughout.
- Rich text: autolinks and links marked internal pass safeHref too; lexicalToMarkdown
  drops unsafe link targets.
- truncate() never returns more than its limit (summary / meta autofill after validation).
- resolveRoute answers null for a locale the site does not have (xx, all, *): no
  default-locale page under another code (page route past the proxy, /md/xx, MCP).
- A 404 page that is a draft is not shown (resolveNotFoundPage, getNotFoundPage).
- readPublished() access rule (exported); Site integrations readVersions: admin.
- Plugin switches, buildCsp, buildSecurityHeaders and the seed guard refuse nonsense
  values at start; an unknown role name is met by nobody, requireRole throws on one.
- Docs, AGENT.md, iapl-collection and iapl-audit skills.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:25:26 +01:00

200 lines
11 KiB
TypeScript

/**
* IAWL security ideas, group B (locales, save and state, signatures, switches, secret fields, HTML) — the unit
* proofs of what was fixed. The HTTP proofs are in iawlIdeasBHttp.test.ts.
*/
import { describe, expect, test } from 'vitest'
import { describeFromMarkdown, truncate } from '../src/modules/seo/plainText.js'
/** Idea 2: a value the plugin writes after validation must still fit the limit it was cut to. */
describe('a cut value fits its limit', () => {
test.each([10, 155, 300])('truncate(…, %i) is never longer than the limit', (max) => {
for (const text of ['x'.repeat(max * 2), `${'word '.repeat(max)}`, `${'y'.repeat(max - 1)} ${'z'.repeat(max)}`]) {
const out = truncate(text, max)
expect(out.length).toBeLessThanOrEqual(max)
expect(out.endsWith('…')).toBe(true)
}
})
test('describeFromMarkdown keeps to its length when it has to cut', () => {
expect(describeFromMarkdown('a'.repeat(400), 155).length).toBeLessThanOrEqual(155)
})
test('a text within the limit is left as it is', () => {
expect(truncate('short text', 155)).toBe('short text')
})
})
/** A body sent without a content-length (chunked): the stream is the only thing that tells its size. */
const chunked = (url: string, size: number, init: RequestInit = {}) => {
const chunk = new TextEncoder().encode('x'.repeat(1024))
let sent = 0
let pulled = 0
const body = new ReadableStream<Uint8Array>({
pull(controller) {
pulled += 1
if (sent >= size) {return controller.close()}
sent += chunk.byteLength
controller.enqueue(chunk)
},
})
const request = new Request(url, { ...init, body, duplex: 'half', method: 'POST' } as RequestInit)
return { pulled: () => pulled, request }
}
/** Idea 1: the size of a request is checked before it is read whole, the length of a query before it is searched. */
describe('request size and list length before the work', () => {
test('the CSP report route stops reading a chunked body at its cap', async () => {
const { createCspReportRoute } = await import('../src/modules/security/createCspReportRoute.js')
const reports: unknown[] = []
const route = createCspReportRoute({ maxBytes: 4096, onReport: (v) => void reports.push(v) })
const big = chunked('http://site.test/api/csp-report', 1024 * 1024)
expect((await route(big.request)).status).toBe(413)
expect(big.pulled()).toBeLessThan(16)
})
test('the mail service confirm call stops reading a chunked body at its cap', async () => {
const { relayConfirmEndpoint } = await import('../src/modules/email/relay/confirm.js')
const endpoint = relayConfirmEndpoint()
const big = chunked('http://site.test/api/iapl/mail-relay/confirm', 1024 * 1024, { headers: { 'x-forwarded-for': '203.0.113.9' } })
const res = await endpoint.handler(big.request as never)
expect(res.status).toBe(404)
expect(big.pulled()).toBeLessThan(16)
})
test('the MCP route refuses a body over its cap before parsing it', async () => {
const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js')
const { POST } = createMcpRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
getCachedPayload: () => Promise.reject(new Error('must not be reached')),
rateLimit: false,
})
const big = chunked('http://site.test/api/mcp', 4 * 1024 * 1024)
const res = await POST(big.request)
expect(res.status).toBe(413)
expect(big.pulled()).toBeLessThan(200)
})
test('searchContent cuts a huge query before it reaches the database', async () => {
const { searchContent } = await import('../src/modules/content/searchContent.js')
const seen: string[] = []
const payload = {
find: async ({ where }: { where: { or: { title: { like: string } }[] } }) => {
seen.push(where.or[0].title.like)
return { docs: [] }
},
findGlobal: async () => ({}),
}
const query = Array.from({ length: 5000 }, (_, i) => `w${i}`).join(' ')
await searchContent({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, payload: payload as never, query })
expect(seen).toHaveLength(1)
expect(seen[0].length).toBeLessThanOrEqual(200)
expect(seen[0].split(' ').length).toBeLessThanOrEqual(10)
// a normal query is passed as it is
await searchContent({ config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, payload: payload as never, query: 'cennik usług' })
expect(seen[1]).toBe('cennik usług')
})
test('the visit counter does not read a chunked body past its cap', async () => {
const { buildStatsEndpoint } = await import('../src/modules/stats/endpoint.js')
const endpoint = buildStatsEndpoint({} as never)
const big = chunked('http://site.test/api/ipal/hit', 1024 * 1024, { headers: { 'user-agent': 'Mozilla/5.0', 'x-forwarded-for': '203.0.113.10' } })
const res = await endpoint.handler(Object.assign(big.request, { payload: {} }) as never)
expect(res.status).toBe(204)
expect(big.pulled()).toBeLessThan(16)
})
})
/** Idea 21: a value nobody understands as off is refused at start, never read as off or open. */
describe('switches refuse nonsense at start', () => {
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
const start = async (options: Record<string, unknown>) => {
const { iapl } = await import('../src/plugin.js')
return () => iapl({ i18n, ...options } as never)
}
test.each([
['accounts', { accounts: 0 }],
['accounts', { accounts: '' }],
['stats', { stats: 'false' }],
['cookieScanner', { cookieScanner: 'off' }],
['indexNow', { indexNow: 'false' }],
['forms.attachments', { forms: { attachments: 'false' } }],
['twoFactor.allowCollectionMismatch', { twoFactor: { allowCollectionMismatch: 'false', collection: 'users', totp: { issuer: 'x' } } }],
['consentLog.retentionDays', { consentLog: { retentionDays: null } }],
['consentLog.retentionDays', { consentLog: { retentionDays: 0 } }],
['adminMeta.robots.index', { adminMeta: { robots: { index: 'false' } } }],
['dashboardAlerts.integrations', { dashboardAlerts: { integrations: 'Admin' } }],
['mail.relay.accountMail.windowMinutes', { mail: { relay: { accountMail: { windowMinutes: 0 } } } }],
['mail.relay.confirmRateLimit.windowMs', { mail: { relay: { confirmRateLimit: { windowMs: 0 } } } }],
['mail.relay', { mail: { relay: 'off' } }],
['storageNames', { storageNames: 'IAPL' }],
['forms.attachments.submit.maxPerMinute', { forms: { attachments: { submit: { maxPerMinute: 'off' } } } }],
])('%s: %j fails at start', async (name, options) => {
expect(await start(options)).toThrow(name)
})
test.each([
[{}],
[{ accounts: false, consentLog: { retentionDays: 30 }, cookieScanner: false, indexNow: true, stats: true }],
[{ dashboardAlerts: { cookies: 'all', integrations: 'editor' }, mail: { relay: { accountMail: false } } }],
[{ adminMeta: { robots: { follow: false, index: false } }, forms: { attachments: { submit: { maxPerMinute: 0 } } } }],
])('real values start as before: %j', async (options) => {
expect(await start(options)).not.toThrow()
})
test('an unknown role name is met by nobody, and requireRole refuses it where it is written', async () => {
const { hasMinimumRole, userMeetsRole } = await import('../src/modules/access/predicates.js')
const { requireRole, requireRoleField } = await import('../src/modules/access/access.js')
const payload = { collections: { users: { config: { fields: [{ name: 'roles' }] } } }, config: { admin: { user: 'users' }, collections: [{ slug: 'users', auth: true }] } }
const admin = { id: 1, collection: 'users', roles: ['admin'] }
expect(hasMinimumRole(admin as never, 'admin', payload as never)).toBe(true)
expect(hasMinimumRole(admin as never, 'Admin' as never, payload as never)).toBe(false)
expect(userMeetsRole({ payload: payload as never, user: { ...admin, roles: [] } }, 'admins' as never)).toBe(false)
expect(() => requireRole('superadmin' as never)).toThrow('requireRole')
expect(() => requireRoleField('Editor' as never)).toThrow('requireRoleField')
expect(() => requireRole('editor')).not.toThrow()
})
test('buildCsp refuses a string where sources are a list, and a dev flag that is not a boolean', async () => {
const { buildCsp } = await import('../src/modules/security/buildCsp.js')
expect(() => buildCsp({ extra: { 'img-src': 'https://*.cdn.com' as never } })).toThrow("extra['img-src']")
expect(() => buildCsp({ dev: 'false' as never })).toThrow('buildCsp.dev')
expect(buildCsp({ dev: false, extra: { 'img-src': ['https://cdn.example.com'] } }).value).toContain('img-src')
})
test('buildSecurityHeaders refuses values a browser would drop', async () => {
const { buildSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js')
expect(() => buildSecurityHeaders({ hsts: null as never })).toThrow('hsts')
expect(() => buildSecurityHeaders({ hstsMaxAge: 'abc' as never })).toThrow('hstsMaxAge')
expect(() => buildSecurityHeaders({ frameOptions: 'false' as never })).toThrow('frameOptions')
expect(buildSecurityHeaders({ frameOptions: null, permissionsPolicy: null }).map((h) => h.key)).not.toContain('X-Frame-Options')
expect(buildSecurityHeaders().map((h) => h.key)).toContain('Strict-Transport-Security')
})
test('the seed guard cannot be switched off by 0 or allowed by "false"', async () => {
const { createSeeder } = await import('../src/modules/seed/seeder.js')
const payload = { logger: { info: () => {} } } as never
expect(() => createSeeder(payload, { guard: 0 as never })).toThrow('seed guard')
expect(() => createSeeder(payload, { guard: { allowFull: 'false' as never } })).toThrow('seed guard.allowFull')
})
})
/** Idea 25 at the search route: a code the site does not have is the default locale, in the search and the answer. */
test('createSearchRoute never passes an unknown ?locale on', async () => {
const { createSearchRoute } = await import('../src/modules/content/createSearchRoute.js')
const asked: string[] = []
const route = createSearchRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] },
getCachedPayload: async () => ({ find: async () => ({ docs: [{ id: 1, slug: 'o-nas', title: 'O nas' }] }), findGlobal: async () => ({}) }) as never,
isPathVisible: async (_path, locale) => {
asked.push(locale)
return true
},
rateLimit: false,
})
const body = (await (await route(new Request('http://site.test/api/search?q=nas&locale=../xx'))).json()) as { locale: string }
expect(body.locale).toBe('pl')
expect(asked.every((l) => l === 'pl')).toBe(true)
})