app

Local-first trade for farms and co-ops
git clone https://radroots.dev/git/app.git
Log | Files | Refs | README | LICENSE

security-headers.spec.ts (12578B)


      1 import { expect, test } from '@playwright/test';
      2 import { fileURLToPath } from 'node:url';
      3 import { prepareSecurityHeaders } from '../../tools/security-headers.mjs';
      4 import { encodeProductReference } from '../../src/lib/nostr/references.ts';
      5 import { createStaticHarness } from '../integration/harness/static.ts';
      6 
      7 const web = fileURLToPath(new URL('../../', import.meta.url));
      8 const coordinate = encodeProductReference({
      9   kind: 30402,
     10   pubkey: '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
     11   identifier: 'HCP127_TEST_ONLY'
     12 });
     13 if (!coordinate) throw new Error('Missing qualified coordinate');
     14 const handle = '12345678-1234-4234-8234-123456789abc';
     15 const routes = [
     16   '/',
     17   '/search',
     18   '/products/' + coordinate,
     19   '/sell',
     20   '/selling',
     21   '/selling/drafts/' + handle,
     22   '/products/' + coordinate + '/edit',
     23   '/messages',
     24   '/messages/' + handle,
     25   '/about',
     26   '/privacy'
     27 ];
     28 
     29 test('actual hashed HTTP CSP hydrates all eleven direct routes, refresh and client navigation', async ({
     30   browser
     31 }) => {
     32   const prepared = await prepareSecurityHeaders(web);
     33   const server = await createStaticHarness({ headers: prepared.headers });
     34   const context = await browser.newContext();
     35   const external: string[] = [];
     36   const errors: string[] = [];
     37   try {
     38     await context.route('**/*', (route) => {
     39       if (new URL(route.request().url()).origin === server.url)
     40         return route.continue();
     41       external.push(route.request().url());
     42       return route.abort();
     43     });
     44     await context.addInitScript(() => {
     45       Reflect.set(window, 'hcp127Violations', []);
     46       document.addEventListener('securitypolicyviolation', (event) => {
     47         const rows = Reflect.get(window, 'hcp127Violations') as string[];
     48         rows.push(event.effectiveDirective);
     49       });
     50     });
     51     const page = await context.newPage();
     52     page.on('pageerror', (error) => errors.push(error.message));
     53     for (const pathname of routes) {
     54       for (const navigate of [
     55         () => page.goto(server.url + pathname),
     56         () => page.reload()
     57       ]) {
     58         const response = await navigate();
     59         expect(response?.status()).toBe(200);
     60         expect(response?.headers()['content-security-policy']).toBe(
     61           prepared.headers['Content-Security-Policy']
     62         );
     63         await expect(
     64           page.getByRole('link', { name: 'HarvestCircle', exact: true })
     65         ).toBeVisible();
     66         await expect(
     67           page
     68             .getByRole('navigation', { name: 'Primary' })
     69             .getByRole('button', { name: 'Connect extension', exact: true })
     70         ).toBeEnabled();
     71         const marker =
     72           pathname + ':' + (await page.evaluate(() => history.length));
     73         await page.evaluate(
     74           (value) => Reflect.set(window, 'hcp127NavigationMarker', value),
     75           marker
     76         );
     77         console.log(
     78           JSON.stringify({
     79             fixture: 'HCP127_SAME_DOCUMENT_NAVIGATION',
     80             phase: 'ready',
     81             pathname,
     82             url: page.url(),
     83             marker
     84           })
     85         );
     86         await page
     87           .getByRole('link', {
     88             name: pathname === '/search' ? 'HarvestCircle' : 'Search',
     89             exact: true
     90           })
     91           .click();
     92         await expect(page).toHaveURL(
     93           server.url + (pathname === '/search' ? '/' : '/search')
     94         );
     95         await expect(
     96           page.getByRole('textbox', { name: 'What are you looking for?' })
     97         ).toBeEnabled();
     98         expect(
     99           await page.evaluate(
    100             () => Reflect.get(window, 'hcp127NavigationMarker') as unknown
    101           )
    102         ).toBe(marker);
    103         console.log(
    104           JSON.stringify({
    105             fixture: 'HCP127_SAME_DOCUMENT_NAVIGATION',
    106             phase: 'client-target',
    107             pathname,
    108             url: page.url(),
    109             marker
    110           })
    111         );
    112         await page.goBack();
    113         await expect(page).toHaveURL(server.url + pathname);
    114         await expect(page.getByRole('main')).toBeVisible();
    115         expect(
    116           await page.evaluate(
    117             () => Reflect.get(window, 'hcp127NavigationMarker') as unknown
    118           )
    119         ).toBe(marker);
    120         console.log(
    121           JSON.stringify({
    122             fixture: 'HCP127_SAME_DOCUMENT_NAVIGATION',
    123             phase: 'back',
    124             pathname,
    125             url: page.url(),
    126             marker
    127           })
    128         );
    129         expect(new URL(page.url()).pathname).toBe(pathname);
    130         const announcer = page.locator('#svelte-announcer');
    131         await expect(announcer).toHaveCount(1);
    132         const style = await announcer.evaluate(async (element) => {
    133           const bytes = new TextEncoder().encode(
    134             element.getAttribute('style') ?? ''
    135           );
    136           const hash = await crypto.subtle.digest('SHA-256', bytes);
    137           const computed = getComputedStyle(element);
    138           return {
    139             sha256: [...new Uint8Array(hash)]
    140               .map((value) => value.toString(16).padStart(2, '0'))
    141               .join(''),
    142             position: computed.position,
    143             width: computed.width,
    144             height: computed.height,
    145             clipPath: computed.clipPath
    146           };
    147         });
    148         expect(style).toEqual({
    149           sha256: prepared.framework_style_attributes[0].style_sha256,
    150           position: 'absolute',
    151           width: '1px',
    152           height: '1px',
    153           clipPath: 'inset(50%)'
    154         });
    155         expect(
    156           await page.evaluate(
    157             () => Reflect.get(window, 'hcp127Violations') as string[]
    158           )
    159         ).toEqual([]);
    160       }
    161     }
    162     for (const asset of ['/missing.js', '/missing.css', '/missing.png']) {
    163       const response = await context.request.get(server.url + asset, {
    164         headers: { accept: 'text/html' }
    165       });
    166       expect(response.status()).toBe(404);
    167       expect(await response.text()).toBe('');
    168     }
    169     expect(external).toEqual([]);
    170     expect(errors).toEqual([]);
    171   } finally {
    172     await context.close();
    173     await server.close();
    174   }
    175   expect(context.pages()).toHaveLength(0);
    176   expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
    177 });
    178 
    179 test('real browser CSP denies arbitrary script, eval, hinted egress, resources, base and forms', async ({
    180   browser
    181 }) => {
    182   const prepared = await prepareSecurityHeaders(web);
    183   const server = await createStaticHarness({ headers: prepared.headers });
    184   const context = await browser.newContext();
    185   const external: string[] = [];
    186   try {
    187     await context.route('**/*', (route) => {
    188       if (new URL(route.request().url()).origin === server.url)
    189         return route.continue();
    190       external.push(route.request().url());
    191       return route.abort();
    192     });
    193     const page = await context.newPage();
    194     await page.goto(server.url);
    195     await expect(
    196       page.getByRole('textbox', { name: 'What are you looking for?' })
    197     ).toBeEnabled();
    198     const permissions = await page.evaluate(() => {
    199       const policy = Reflect.get(document, 'featurePolicy') as {
    200         allowsFeature(feature: string): boolean;
    201       };
    202       return ['camera', 'microphone', 'geolocation', 'payment', 'usb'].map(
    203         (feature) => ({
    204           feature,
    205           allowed: policy.allowsFeature(feature)
    206         })
    207       );
    208     });
    209     expect(permissions).toEqual(
    210       ['camera', 'microphone', 'geolocation', 'payment', 'usb'].map(
    211         (feature) => ({ feature, allowed: false })
    212       )
    213     );
    214     const result = await page.evaluate(async () => {
    215       const violations: string[] = [];
    216       Reflect.set(window, 'hcp127Violations', violations);
    217       document.addEventListener('securitypolicyviolation', (event) =>
    218         violations.push(event.effectiveDirective)
    219       );
    220       const script = document.createElement('script');
    221       const styled = document.createElement('div');
    222       styled.setAttribute('style', 'position: fixed');
    223       document.body.append(styled);
    224       script.textContent = 'window.hcp127Injected = true';
    225       document.body.append(script);
    226       let connectDenied = false;
    227       try {
    228         await fetch('https://hinted.invalid/private');
    229       } catch {
    230         connectDenied = true;
    231       }
    232       const image = document.createElement('img');
    233       image.src = 'https://hinted.invalid/image.png';
    234       document.body.append(image);
    235       const frame = document.createElement('iframe');
    236       frame.src = 'https://hinted.invalid/embed';
    237       document.body.append(frame);
    238       try {
    239         await new FontFace(
    240           'HC127Denied',
    241           'url(https://hinted.invalid/font.woff2)'
    242         ).load();
    243       } catch {
    244         /* Required policy refusal is asserted below. */
    245       }
    246       const base = document.createElement('base');
    247       base.href = 'https://hinted.invalid/';
    248       document.head.append(base);
    249       const form = document.createElement('form');
    250       form.action = 'https://hinted.invalid/submit';
    251       document.body.append(form);
    252       form.submit();
    253       return {
    254         inline: Reflect.get(window, 'hcp127Injected') as unknown,
    255         hostileStyle: getComputedStyle(styled).position,
    256         connectDenied
    257       };
    258     });
    259     expect(result).toEqual({
    260       inline: undefined,
    261       hostileStyle: 'static',
    262       connectDenied: true
    263     });
    264     // Runtime.evaluate defaults to bypassing unsafe-eval CSP. Disable that
    265     // DevTools privilege explicitly; page.evaluate cannot qualify this check.
    266     // https://chromedevtools.github.io/devtools-protocol/tot/Runtime/#method-evaluate
    267     const session = await context.newCDPSession(page);
    268     try {
    269       const evaluated = await session.send('Runtime.evaluate', {
    270         expression: "window.eval('window.hcp127Evaluated = true')",
    271         allowUnsafeEvalBlockedByCSP: false,
    272         returnByValue: true
    273       });
    274       expect(evaluated.exceptionDetails?.exception?.className).toBe(
    275         'EvalError'
    276       );
    277       expect(evaluated.exceptionDetails?.exception?.description).toContain(
    278         'Content Security Policy'
    279       );
    280       expect(
    281         await page.evaluate(
    282           () => Reflect.get(window, 'hcp127Evaluated') as unknown
    283         )
    284       ).toBeUndefined();
    285       console.log(
    286         JSON.stringify({
    287           fixture: 'HCP127_CSP_EVAL_NO_DEVTOOLS_BYPASS',
    288           allowUnsafeEvalBlockedByCSP: false,
    289           exception: evaluated.exceptionDetails?.exception
    290         })
    291       );
    292     } finally {
    293       await session.detach();
    294     }
    295     for (const directive of [
    296       'script-src-elem',
    297       'style-src-attr',
    298       'script-src',
    299       'connect-src',
    300       'img-src',
    301       'font-src',
    302       'frame-src',
    303       'base-uri',
    304       'form-action'
    305     ])
    306       await expect
    307         .poll(() =>
    308           page.evaluate(
    309             () => Reflect.get(window, 'hcp127Violations') as string[]
    310           )
    311         )
    312         .toContain(directive);
    313     expect(page.url()).toBe(server.url + '/');
    314     expect(external).toEqual([]);
    315   } finally {
    316     await context.close();
    317     await server.close();
    318   }
    319   expect(context.pages()).toHaveLength(0);
    320   expect(server.state()).toEqual({ listening: false, childProcesses: 0 });
    321 });
    322 
    323 test('actual frame-ancestors header refuses embedding by another controlled origin', async ({
    324   browser
    325 }) => {
    326   const prepared = await prepareSecurityHeaders(web);
    327   const child = await createStaticHarness({ headers: prepared.headers });
    328   const parent = await createStaticHarness();
    329   const context = await browser.newContext();
    330   const denied: string[] = [];
    331   try {
    332     await context.route('**/*', (route) =>
    333       [parent.url, child.url].includes(new URL(route.request().url()).origin)
    334         ? route.continue()
    335         : route.abort()
    336     );
    337     const page = await context.newPage();
    338     page.on('console', (message) => {
    339       if (message.text().includes('frame-ancestors'))
    340         denied.push(message.text());
    341     });
    342     await page.goto(parent.url);
    343     await expect(
    344       page.getByRole('textbox', { name: 'What are you looking for?' })
    345     ).toBeEnabled();
    346     await page.evaluate((url) => {
    347       const frame = document.createElement('iframe');
    348       frame.src = url;
    349       document.body.append(frame);
    350     }, child.url);
    351     await expect.poll(() => denied.length).toBeGreaterThan(0);
    352     expect(
    353       page.frames().filter((frame) => frame.url().startsWith(child.url))
    354     ).toHaveLength(0);
    355   } finally {
    356     await context.close();
    357     await parent.close();
    358     await child.close();
    359   }
    360   expect(context.pages()).toHaveLength(0);
    361   expect(parent.state()).toEqual({ listening: false, childProcesses: 0 });
    362   expect(child.state()).toEqual({ listening: false, childProcesses: 0 });
    363 });