Skip to content
Myr

index.test.ts

This file

Path

src/middleware/cors/index.test.ts

532 lines 路 16.4 KiB 路 TypeScript

Last changed by

fix(cors): append Origin to Vary header on OPTIONS preflight (#5235)Nanasibefore adoption8bf03c3

History of this file

Take it

1import { Hono } from '../../hono'2import { cors } from '../../middleware/cors'34describe('CORS by Middleware', () => {5  const app = new Hono()67  app.use('/api/*', cors())89  app.use(10    '/api2/*',11    cors({12      origin: 'http://example.com',13      allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],14      allowMethods: ['POST', 'GET', 'OPTIONS'],15      exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],16      maxAge: 600,17      credentials: true,18    })19  )2021  app.use(22    '/api3/*',23    cors({24      origin: ['http://example.com', 'http://example.org', 'http://example.dev'],25    })26  )2728  app.use(29    '/api4/*',30    cors({31      origin: (origin) => (origin.endsWith('.example.com') ? origin : 'http://example.com'),32    })33  )3435  app.use('/api5/*', cors())3637  app.use(38    '/api6/*',39    cors({40      origin: 'http://example.com',41    })42  )43  app.use(44    '/api6/*',45    cors({46      origin: 'http://example.com',47    })48  )4950  app.use(51    '/api7/*',52    cors({53      origin: (origin) => (origin === 'http://example.com' ? origin : '*'),54      allowMethods: (origin) =>55        origin === 'http://example.com'56          ? ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE']57          : ['GET', 'HEAD'],58    })59  )6061  app.use(62    '/api8/*',63    cors({64      origin: (origin) =>65        new Promise<string>((resolve) =>66          resolve(origin.endsWith('.example.com') ? origin : 'http://example.com')67        ),68    })69  )7071  app.use(72    '/api9/*',73    cors({74      origin: (origin) =>75        new Promise<string>((resolve) => resolve(origin === 'http://example.com' ? origin : '*')),76      allowMethods: (origin) =>77        new Promise<string[]>((resolve) =>78          resolve(79            origin === 'http://example.com'80              ? ['GET', 'HEAD', 'POST', 'PATCH', 'DELETE']81              : ['GET', 'HEAD']82          )83        ),84    })85  )8687  app.use(88    '/api10/*',89    cors({90      origin: '*',91      credentials: true,92    })93  )9495  app.get('/api/abc', (c) => {96    return c.json({ success: true })97  })9899  app.get('/api/vary-header', () => {100    return new Response(JSON.stringify({ success: true }), {101      headers: {102        Vary: 'X-Custom-Vary-Value',103      },104    })105  })106107  app.get('/api2/abc', (c) => {108    return c.json({ success: true })109  })110111  app.get('/api3/abc', (c) => {112    return c.json({ success: true })113  })114115  app.get('/api3/vary-header', () => {116    return new Response(JSON.stringify({ success: true }), {117      headers: {118        Vary: 'X-Custom-Vary-Value',119      },120    })121  })122123  app.get('/api4/abc', (c) => {124    return c.json({ success: true })125  })126127  app.get('/api5/abc', () => {128    return new Response(JSON.stringify({ success: true }))129  })130131  app.get('/api7/abc', () => {132    return new Response(JSON.stringify({ success: true }))133  })134135  app.get('/api10/abc', (c) => {136    return c.json({ success: true })137  })138139  it('GET default', async () => {140    const res = await app.request('http://localhost/api/abc')141142    expect(res.status).toBe(200)143    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')144    expect(res.headers.get('Vary')).toBeNull()145  })146147  it('Preflight default', async () => {148    const req = new Request('https://localhost/api/abc', {149      method: 'OPTIONS',150      headers: {151        'Access-Control-Request-Method': 'QUERY',152        'Access-Control-Request-Headers': 'X-PINGOTHER, Content-Type',153      },154    })155    const res = await app.request(req)156157    expect(res.status).toBe(204)158    expect(res.statusText).toBe('No Content')159    expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')).toEqual([160      'GET',161      'HEAD',162      'PUT',163      'POST',164      'DELETE',165      'PATCH',166      'QUERY',167    ])168    expect(res.headers.get('Access-Control-Allow-Headers')?.split(',')).toEqual([169      'X-PINGOTHER',170      'Content-Type',171    ])172  })173174  it('Preflight handles a large Access-Control-Request-Headers value', async () => {175    const req = new Request('https://localhost/api/abc', { method: 'OPTIONS' })176    req.headers.append('Access-Control-Request-Headers', 'x' + ' '.repeat(200000) + 'x')177    const res = await app.request(req)178    expect(res.status).toBe(204)179  })180181  it('Preflight with options', async () => {182    const req = new Request('https://localhost/api2/abc', {183      method: 'OPTIONS',184      headers: { origin: 'http://example.com' },185    })186    const res = await app.request(req)187188    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')189    expect(res.headers.get('Vary')?.split(/\s*,\s*/)).toEqual(expect.arrayContaining(['Origin']))190    expect(res.headers.get('Access-Control-Allow-Headers')?.split(/\s*,\s*/)).toEqual([191      'X-Custom-Header',192      'Upgrade-Insecure-Requests',193    ])194    expect(res.headers.get('Access-Control-Allow-Methods')?.split(/\s*,\s*/)).toEqual([195      'POST',196      'GET',197      'OPTIONS',198    ])199    expect(res.headers.get('Access-Control-Expose-Headers')?.split(/\s*,\s*/)).toEqual([200      'Content-Length',201      'X-Kuma-Revision',202    ])203    expect(res.headers.get('Access-Control-Max-Age')).toBe('600')204    expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')205  })206207  it('Disallow an unmatched origin', async () => {208    const req = new Request('https://localhost/api2/abc', {209      method: 'OPTIONS',210      headers: { origin: 'http://example.net' },211    })212    const res = await app.request(req)213    expect(res.headers.has('Access-Control-Allow-Origin')).toBeFalsy()214  })215216  it('Allow multiple origins', async () => {217    let req = new Request('http://localhost/api3/abc', {218      headers: {219        Origin: 'http://example.org',220      },221    })222    let res = await app.request(req)223    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.org')224225    req = new Request('http://localhost/api3/abc')226    res = await app.request(req)227    expect(228      res.headers.has('Access-Control-Allow-Origin'),229      'An unmatched origin should be disallowed'230    ).toBeFalsy()231232    req = new Request('http://localhost/api3/abc', {233      headers: {234        Referer: 'http://example.net/',235      },236    })237    res = await app.request(req)238    expect(239      res.headers.has('Access-Control-Allow-Origin'),240      'An unmatched origin should be disallowed'241    ).toBeFalsy()242  })243244  it('Set "Origin" to Vary header', async () => {245    const res = await app.request('http://localhost/api3/abc', {246      headers: {247        Origin: 'http://example.com',248      },249    })250251    expect(res.status).toBe(200)252    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')253    expect(res.headers.get('Vary')).toBe('Origin')254  })255256  it('Keep original Vary header', async () => {257    const res = await app.request('http://localhost/api/vary-header', {258      headers: {259        Origin: 'http://example.com',260      },261    })262263    expect(res.status).toBe(200)264    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')265    expect(res.headers.get('Vary')).toBe('X-Custom-Vary-Value')266  })267268  it('Append "Origin" to Vary header, if response has some Vary header', async () => {269    const res = await app.request('http://localhost/api3/vary-header', {270      headers: {271        Origin: 'http://example.com',272      },273    })274275    expect(res.status).toBe(200)276    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')277    expect(res.headers.get('Vary')).toBe('X-Custom-Vary-Value, Origin')278  })279280  it('Append "Origin" to Vary header on OPTIONS preflight, if response has some Vary header', async () => {281    const testApp = new Hono()282    testApp.use('/api/*', async (c, next) => {283      c.header('Vary', 'Accept-Encoding', { append: true })284      await next()285    })286    testApp.use(287      '/api/*',288      cors({289        origin: 'http://example.com',290        allowHeaders: ['X-Custom-Header'],291      })292    )293    testApp.all('/api/test', (c) => c.text('ok'))294295    const res = await testApp.request('http://localhost/api/test', {296      method: 'OPTIONS',297      headers: {298        Origin: 'http://example.com',299        'Access-Control-Request-Headers': 'X-Custom-Header',300      },301    })302303    expect(res.status).toBe(204)304    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')305    expect(res.headers.get('Vary')).toBe('Accept-Encoding, Origin, Access-Control-Request-Headers')306  })307308  it('Allow origins by function', async () => {309    let req = new Request('http://localhost/api4/abc', {310      headers: {311        Origin: 'http://subdomain.example.com',312      },313    })314    let res = await app.request(req)315    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://subdomain.example.com')316317    req = new Request('http://localhost/api4/abc')318    res = await app.request(req)319    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')320321    req = new Request('http://localhost/api4/abc', {322      headers: {323        Referer: 'http://evil-example.com/',324      },325    })326    res = await app.request(req)327    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')328  })329330  it('Allow origins by promise returning function', async () => {331    let req = new Request('http://localhost/api8/abc', {332      headers: {333        Origin: 'http://subdomain.example.com',334      },335    })336    let res = await app.request(req)337    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://subdomain.example.com')338339    req = new Request('http://localhost/api8/abc')340    res = await app.request(req)341    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')342343    req = new Request('http://localhost/api8/abc', {344      headers: {345        Referer: 'http://evil-example.com/',346      },347    })348    res = await app.request(req)349    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')350  })351352  it('With raw Response object', async () => {353    const res = await app.request('http://localhost/api5/abc')354355    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')356    expect(res.headers.get('Vary')).toBeNull()357  })358359  it('Should not return duplicate header values', async () => {360    const res = await app.request('http://localhost/api6/abc', {361      headers: {362        origin: 'http://example.com',363      },364    })365366    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')367  })368369  it('Allow methods by function', async () => {370    const req = new Request('http://localhost/api7/abc', {371      headers: {372        Origin: 'http://example.com',373      },374      method: 'OPTIONS',375    })376    const res = await app.request(req)377    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')378    expect(res.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD,POST,PATCH,DELETE')379380    const req2 = new Request('http://localhost/api7/abc', {381      headers: {382        Origin: 'http://example.org',383      },384      method: 'OPTIONS',385    })386    const res2 = await app.request(req2)387    expect(res2.headers.get('Access-Control-Allow-Origin')).toBe('*')388    expect(res2.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD')389  })390391  it('Allow methods by promise returning function', async () => {392    const req = new Request('http://localhost/api9/abc', {393      headers: {394        Origin: 'http://example.com',395      },396      method: 'OPTIONS',397    })398    const res = await app.request(req)399    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')400    expect(res.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD,POST,PATCH,DELETE')401402    const req2 = new Request('http://localhost/api9/abc', {403      headers: {404        Origin: 'http://example.org',405      },406      method: 'OPTIONS',407    })408    const res2 = await app.request(req2)409    expect(res2.headers.get('Access-Control-Allow-Origin')).toBe('*')410    expect(res2.headers.get('Access-Control-Allow-Methods')).toBe('GET,HEAD')411  })412413  it('Does not set allow methods when function returns an empty array', async () => {414    for (const allowMethods of [() => [], async () => []]) {415      const app = new Hono()416      app.use(cors({ allowMethods }))417418      const res = await app.request('http://localhost/', { method: 'OPTIONS' })419420      expect(res.headers.get('Access-Control-Allow-Methods')).toBeNull()421    }422  })423424  it('Emits the wildcard, not the reflected origin, when credentials is true with wildcard origin', async () => {425    const res = await app.request('http://localhost/api10/abc', {426      headers: {427        Origin: 'http://example.com',428      },429    })430431    expect(res.status).toBe(200)432    // Must not reflect the request origin; the wildcard + credentials combination433    // is rejected by the browser (fail closed). A wildcard response does not vary434    // by Origin, so no Vary header is set.435    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')436    expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')437    expect(res.headers.get('Vary')).toBeNull()438  })439440  it('Preflight emits the wildcard, not the reflected origin, when credentials is true with wildcard origin', async () => {441    const req = new Request('http://localhost/api10/abc', {442      method: 'OPTIONS',443      headers: {444        Origin: 'http://example.com',445      },446    })447    const res = await app.request(req)448449    expect(res.status).toBe(204)450    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')451    expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')452  })453454  it('Emits the wildcard with no Origin header when credentials is true with wildcard origin', async () => {455    const res = await app.request('http://localhost/api10/abc')456457    expect(res.status).toBe(200)458    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')459    expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')460  })461462  it('Emits the wildcard for every origin (never reflects) when credentials is true with wildcard origin', async () => {463    const res1 = await app.request('http://localhost/api10/abc', {464      headers: { Origin: 'http://example.com' },465    })466    const res2 = await app.request('http://localhost/api10/abc', {467      headers: { Origin: 'http://other.com' },468    })469470    expect(res1.headers.get('Access-Control-Allow-Origin')).toBe('*')471    expect(res2.headers.get('Access-Control-Allow-Origin')).toBe('*')472  })473474  it('Origin: null gets the wildcard, not a reflected null origin, with credentials', async () => {475    const res = await app.request('http://localhost/api10/abc', {476      headers: { Origin: 'null' },477    })478479    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')480    expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')481  })482483  it('Should not reflect an arbitrary Origin when credentials is true with default origin', async () => {484    const app = new Hono()485    app.use('*', cors({ credentials: true }))486    app.get('/api/me', (c) => c.json({ secret: 'private user data' }))487488    // A wildcard/default origin must not be turned into a reflect-any-origin489    // credentialed policy; the browser must keep rejecting it (fail closed).490    for (const origin of ['https://attacker.example', 'http://evil.test', 'null']) {491      const res = await app.request('http://localhost/api/me', { headers: { Origin: origin } })492      expect(res.headers.get('Access-Control-Allow-Origin')).not.toBe(origin)493    }494  })495496  it('Preflight should not approve an arbitrary Origin when credentials is true with default origin', async () => {497    const app = new Hono()498    app.use('*', cors({ credentials: true }))499    app.delete('/api/account', (c) => c.json({ deleted: true }))500501    const res = await app.request(502      new Request('http://localhost/api/account', {503        method: 'OPTIONS',504        headers: {505          Origin: 'https://attacker.example',506          'Access-Control-Request-Method': 'DELETE',507          'Access-Control-Request-Headers': 'X-CSRF',508        },509      })510    )511512    expect(res.headers.get('Access-Control-Allow-Origin')).not.toBe('https://attacker.example')513  })514515  it('Options without origin fall back to wildcard default', async () => {516    const subApp = new Hono()517    subApp.use('/api/*', cors({ allowMethods: ['GET', 'POST'] }))518    subApp.get('/api/abc', (c) => c.json({ ok: true }))519520    const res = await subApp.request('http://localhost/api/abc')521    expect(res.status).toBe(200)522    expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')523524    const preflight = await subApp.request(525      new Request('http://localhost/api/abc', { method: 'OPTIONS' })526    )527    expect(preflight.headers.get('Access-Control-Allow-Methods')?.split(/\s*,\s*/)).toEqual([528      'GET',529      'POST',530    ])531  })532})