import type { AddressInfo } from 'node:net' /** * The scanner service (services/cookie-crawler) without a browser, and the * site side's pure pieces: wire format, violations, token check, config. */ import type { BasePayload } from 'payload' import { afterEach, describe, expect, test, vi } from 'vitest' import { checkCrawlRequest, discoverPages, isFirstParty, mergeRuns, parseSites } from '../services/cookie-crawler/lib.mjs' import { createCrawlerServer } from '../services/cookie-crawler/server.mjs' import { resolveCrawlConfig } from '../src/modules/consent/scanner/crawl/config.js' import { bearerMatches } from '../src/modules/consent/scanner/crawl/endpoints.js' import { parseCrawlResult } from '../src/modules/consent/scanner/crawl/result.js' import { findCrawlViolations } from '../src/modules/consent/scanner/crawl/violations.js' const TOKEN = 'a'.repeat(32) const JOB = 'f'.repeat(32) const sites = parseSites(`acme.pl=${TOKEN}, shop.example.com=${'b'.repeat(32)},short.pl=123`) describe('crawler service — request checks', () => { test('sites: host=token pairs, www dropped, short tokens refused', () => { expect(sites).toEqual([ { host: 'acme.pl', token: TOKEN }, { host: 'shop.example.com', token: 'b'.repeat(32) }, ]) }) const body = { callbackUrl: 'https://www.acme.pl/api/ipal/cookie-crawl/results', jobId: JOB, siteUrl: 'https://www.acme.pl' } const check = (b: object, authorization = `Bearer ${TOKEN}`, allowHttp = false) => checkCrawlRequest({ allowHttp, authorization, body: b, sites }) test('a listed site with its own token passes', () => { expect(check(body)).toBeNull() }) test('refuses other sites, other tokens, foreign callbacks, http, bad job ids', () => { expect(check({ ...body, callbackUrl: 'https://evil.com/x', siteUrl: 'https://evil.com' })).toBe('site_not_allowed') expect(check(body, `Bearer ${'b'.repeat(32)}`)).toBe('unauthorized') // shop's token cannot crawl acme expect(check(body, '')).toBe('unauthorized') expect(check({ ...body, callbackUrl: 'https://evil.com/collect' })).toBe('callback_not_on_site') expect(check({ ...body, callbackUrl: 'http://acme.pl/x', siteUrl: 'http://acme.pl' })).toBe('https_only') expect(check({ ...body, callbackUrl: 'http://acme.pl/x', siteUrl: 'http://acme.pl' }, `Bearer ${TOKEN}`, true)).toBeNull() expect(check({ ...body, jobId: '../etc' })).toBe('bad_job_id') expect(check(null as never)).toBe('bad_request') }) }) describe('crawler service — pages and runs', () => { test('pages from the sitemap index: same origin only, capped', async () => { const files: Record = { 'https://acme.pl/sitemap.xml': 'https://acme.pl/sitemap-pages.xml', 'https://acme.pl/sitemap-pages.xml': 'https://acme.pl/plhttps://evil.com/xhttps://acme.pl/enhttps://acme.pl/de', } const fakeFetch = vi.fn(async (url: string) => new Response(files[url] ?? '', { status: files[url] ? 200 : 404 })) expect(await discoverPages('https://acme.pl/', 2, fakeFetch as unknown as typeof fetch)).toEqual(['https://acme.pl/', 'https://acme.pl/pl', 'https://acme.pl/en']) const offline = vi.fn(async () => { throw new Error('down') }) expect(await discoverPages('https://acme.pl/', 5, offline as unknown as typeof fetch)).toEqual(['https://acme.pl/']) }) test('first party includes subdomains', () => { expect(isFirstParty('www.acme.pl', 'acme.pl')).toBe(true) expect(isFirstParty('cdn.acme.pl', 'acme.pl')).toBe(true) expect(isFirstParty('notacme.pl', 'acme.pl')).toBe(false) }) test('two runs merge into before/after flags with the first pages', () => { const { observations, requests } = mergeRuns( { cookies: [{ name: 'sid', domain: '.acme.pl', page: '/' }], requests: [{ host: 'connect.facebook.net', page: '/' }], storage: [] }, { cookies: [{ name: 'sid', domain: 'acme.pl', page: '/' }, { name: '_ga', domain: '.acme.pl', page: '/' }, { name: '_ga', domain: '.acme.pl', page: '/en' }], requests: [], storage: [{ name: 'ipal-theme', page: '/', storage: 'localStorage' }], }, ) expect(observations).toEqual([ { name: 'sid', after: true, before: true, domain: 'acme.pl', pages: ['/'], storage: 'cookie' }, { name: '_ga', after: true, before: false, domain: 'acme.pl', pages: ['/', '/en'], storage: 'cookie' }, { name: 'ipal-theme', after: true, before: false, pages: ['/'], storage: 'localStorage' }, ]) expect(requests).toEqual([{ after: false, before: true, host: 'connect.facebook.net', pages: ['/'] }]) }) }) describe('crawler service — HTTP', () => { let close: (() => Promise) | undefined afterEach(async () => { await close?.() close = undefined }) async function start(crawl: (job: unknown) => Promise, extra: Record = {}) { const delivered: { auth: null | string; body: Record; url: string }[] = [] const fetchImpl = vi.fn(async (url: string, init: RequestInit) => { delivered.push({ auth: new Headers(init.headers).get('authorization'), body: JSON.parse(init.body as string), url }) return new Response('{}', { status: 200 }) }) const server = createCrawlerServer({ allowHttp: true, crawl, deliveryDelays: [0], fetchImpl: fetchImpl as unknown as typeof fetch, log: () => {}, sites, ...extra }) as { whenIdle: () => Promise } & ReturnType await new Promise((r) => server.listen(0, '127.0.0.1', r)) close = () => new Promise((r) => server.close(() => r())) const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}` const post = (body: unknown, token = TOKEN) => fetch(`${base}/crawl`, { body: JSON.stringify(body), headers: { Authorization: `Bearer ${token}` }, method: 'POST' }) return { base, delivered, post, server } } const job = { callbackUrl: 'https://acme.pl/api/ipal/cookie-crawl/results', jobId: JOB, siteUrl: 'https://acme.pl' } test('202, crawl in the background, result posted back with the site token', async () => { const crawl = vi.fn(async () => ({ accepted: true, observations: [], ok: true, pages: ['/'], requests: [] })) const { base, delivered, post, server } = await start(crawl) expect((await fetch(`${base}/health`)).status).toBe(200) const res = await post(job) expect(res.status).toBe(202) await server.whenIdle() expect(crawl).toHaveBeenCalledWith(expect.objectContaining({ maxPages: 20, siteUrl: 'https://acme.pl' })) expect(delivered).toEqual([{ auth: `Bearer ${TOKEN}`, body: expect.objectContaining({ jobId: JOB, ok: true }), url: job.callbackUrl }]) }) test('401 for a wrong token, 404 elsewhere, a crash or timeout is reported as ok:false', async () => { const { base, delivered, post, server } = await start(() => new Promise(() => {}), { jobTimeoutMs: 50 }) expect((await post(job, 'x'.repeat(32))).status).toBe(401) expect((await fetch(`${base}/nope`)).status).toBe(404) expect((await post(job)).status).toBe(202) await server.whenIdle() expect(delivered[0].body).toMatchObject({ error: expect.stringContaining('longer than 50 ms'), jobId: JOB, ok: false }) }) test('a full queue answers 429', async () => { const { post } = await start(() => new Promise(() => {}), { jobTimeoutMs: 60_000, queueMax: 1 }) expect((await post(job)).status).toBe(202) // running expect((await post(job)).status).toBe(202) // queued expect((await post(job)).status).toBe(429) }) }) describe('crawl — site side', () => { test('the wire format is validated, junk dropped', () => { expect(parseCrawlResult({ jobId: 'nope', ok: true })).toBeNull() expect(parseCrawlResult({ error: 'boom', jobId: JOB, ok: false })).toEqual({ error: 'boom', jobId: JOB, ok: false }) const r = parseCrawlResult({ jobId: JOB, observations: [ { name: '_ga', after: true, before: true, domain: '.Acme.pl', pages: ['/'], storage: 'cookie' }, { name: 'bad name', storage: 'cookie' }, { name: 'x', storage: 'indexedDB' }, ], ok: true, pages: ['/', 3], requests: [{ before: true, host: 'connect.facebook.net' }, { host: 'not a host' }], }) expect(r).toEqual({ accepted: true, jobId: JOB, observations: [{ name: '_ga', after: true, before: true, domain: 'acme.pl', pages: ['/'], storage: 'cookie' }], ok: true, pages: ['/'], requests: [{ after: false, before: true, host: 'connect.facebook.net', pages: [] }], }) }) test('violations: stored before consent and not necessary; tracker hosts; Google only in basic mode', () => { const o = (name: string, before: boolean) => ({ name, after: true, before, pages: ['/'], storage: 'cookie' as const }) const categories: Record = { _fbp: 'marketing', 'cookie-consent': 'necessary', mystery: null } const args = { categoryOf: (x: { name: string }) => categories[x.name], observations: [o('cookie-consent', true), o('_fbp', true), o('mystery', true), o('_ga', false)], requests: [ { after: true, before: true, host: 'connect.facebook.net', pages: ['/'] }, { after: true, before: true, host: 'www.googletagmanager.com', pages: ['/'] }, { after: true, before: false, host: 'px.ads.linkedin.com', pages: ['/'] }, ], } expect(findCrawlViolations(args).map((v) => v.name)).toEqual(['_fbp', 'mystery', 'connect.facebook.net']) expect(findCrawlViolations({ ...args, consentMode: 'basic' }).map((v) => v.name)).toContain('www.googletagmanager.com') expect(findCrawlViolations({ ...args, trackerHosts: [] }).map((v) => v.kind)).toEqual(['cookie', 'cookie']) }) test('bearer token: constant-time match, nothing without a token', () => { expect(bearerMatches(`Bearer ${TOKEN}`, TOKEN)).toBe(true) expect(bearerMatches(`Bearer ${TOKEN}x`, TOKEN)).toBe(false) expect(bearerMatches(TOKEN, TOKEN)).toBe(false) expect(bearerMatches(`Bearer ${TOKEN}`, null)).toBe(false) }) test('config: options, then env, then Payload serverURL; short tokens are not a token', () => { const payload = { config: { serverURL: 'https://acme.pl/' } } as unknown as BasePayload vi.stubEnv('IAPL_COOKIE_SCAN_URL', 'https://crawler.intecion.net/') vi.stubEnv('IAPL_COOKIE_SCAN_TOKEN', 'short') const c = resolveCrawlConfig({ maxPages: 500 }, payload) expect(c).toMatchObject({ maxPages: 100, serviceUrl: 'https://crawler.intecion.net', siteUrl: 'https://acme.pl', token: null }) expect(resolveCrawlConfig({ token: TOKEN, trackerHosts: (d) => [...d, 'chat.example'] }, payload).trackerHosts).toContain('chat.example') vi.unstubAllEnvs() }) })