Skip to content
Myr

index.test.ts

This file

Path

src/middleware/csrf/index.test.ts

534 lines 路 15.9 KiB 路 TypeScript

Last changed by

fix(csrf): exempt OPTIONS request from CSRF validation (#5250)John Emerson Requizobefore adoptioneea9735

History of this file

Take it

1import type { Context } from '../../context'2import { Hono } from '../../hono'3import { csrf } from '../../middleware/csrf'45const simplePostHandler = vi.fn(async (c: Context) => {6  if (c.req.header('content-type') === 'application/json') {7    return c.text((await c.req.json<{ name: string }>())['name'])8  } else {9    const body = await c.req.parseBody<{ name: string }>()10    return c.text(body['name'])11  }12})1314const buildSimplePostRequestData = (options: { origin?: string; secFetchSite?: string } = {}) => ({15  method: 'POST',16  headers: Object.assign(17    {18      'content-type': 'application/x-www-form-urlencoded',19    },20    options?.origin ? { origin: options.origin } : {},21    options?.secFetchSite ? { 'sec-fetch-site': options.secFetchSite } : {}22  ) as Record<string, string>,23  body: 'name=hono',24})2526describe('CSRF by Middleware', () => {27  beforeEach(() => {28    simplePostHandler.mockClear()29  })3031  describe('simple usage', () => {32    const app = new Hono()3334    app.use('*', csrf())35    app.get('/form', (c) => c.html('<form></form>'))36    app.options('/form', (c) => c.text('OK'))37    app.post('/form', simplePostHandler)38    app.put('/form', (c) => c.text('OK'))39    app.delete('/form', (c) => c.text('OK'))40    app.patch('/form', (c) => c.text('OK'))4142    describe('GET /form', async () => {43      it('should be 200 for any request', async () => {44        const res = await app.request('http://localhost/form')4546        expect(res.status).toBe(200)47        expect(await res.text()).toBe('<form></form>')48      })49    })5051    describe('HEAD /form', async () => {52      it('should be 200 for any request', async () => {53        const res = await app.request('http://localhost/form', { method: 'HEAD' })5455        expect(res.status).toBe(200)56      })57    })5859    describe('OPTIONS /form', async () => {60      it('should be 200 for any request', async () => {61        const res = await app.request('http://localhost/form', { method: 'OPTIONS' })6263        expect(res.status).toBe(200)64        expect(await res.text()).toBe('OK')65      })66    })6768    describe('POST /form', async () => {69      it('should be 200 for local request', async () => {70        /*71         * <form action="/form" method="POST"><input name="name" value="hono" /></form>72         * or73         * <script>74         * fetch('/form', {75         *   method: 'POST',76         *   headers: {77         *     'content-type': 'application/x-www-form-urlencoded',78         *   },79         *   body: 'name=hono',80         * });81         * </script>82         */83        const res = await app.request(84          'http://localhost/form',85          buildSimplePostRequestData({ origin: 'http://localhost' })86        )8788        expect(res.status).toBe(200)89        expect(await res.text()).toBe('hono')90      })9192      it('should be 403 for "application/x-www-form-urlencoded" cross origin', async () => {93        /*94         * via http://example.com95         *96         * <form action="http://localhost/form" method="POST">97         *   <input name="name" value="hono" />98         * </form>99         * or100         * <script>101         * fetch('http://localhost/form', {102         *   method: 'POST',103         *   headers: {104         *     'content-type': 'application/x-www-form-urlencoded',105         *   },106         *   body: 'name=hono',107         * });108         * </script>109         */110        const res = await app.request(111          'http://localhost/form',112          buildSimplePostRequestData({ origin: 'http://example.com' })113        )114115        expect(res.status).toBe(403)116        expect(simplePostHandler).not.toHaveBeenCalled()117      })118    })119120    it('should be 403 for "multipart/form-data" cross origin', async () => {121      /*122       * via http://example.com123       *124       * <form action="http://localhost/form" method="POST" enctype="multipart/form-data">125       *   <input name="name" value="hono" />126       * </form>127       * or128       * <script>129       * fetch('http://localhost/form', {130       *   method: 'POST',131       *   headers: {132       *     'content-type': 'multipart/form-data',133       *   },134       *   body: 'name=hono',135       * });136       * </script>137       */138      const res = await app.request(139        'http://localhost/form',140        buildSimplePostRequestData({ origin: 'http://example.com' })141      )142143      expect(res.status).toBe(403)144      expect(simplePostHandler).not.toHaveBeenCalled()145    })146147    it('should be 403 for "text/plain" cross origin', async () => {148      /*149       * via http://example.com150       *151       * <form action="http://localhost/form" method="POST" enctype="text/plain">152       *   <input name="name" value="hono" />153       * </form>154       * or155       * <script>156       * fetch('http://localhost/form', {157       *   method: 'POST',158       *   headers: {159       *     'content-type': 'text/plain',160       *   },161       *   body: 'name=hono',162       * });163       * </script>164       */165      const res = await app.request(166        'http://localhost/form',167        buildSimplePostRequestData({ origin: 'http://example.com' })168      )169170      expect(res.status).toBe(403)171      expect(simplePostHandler).not.toHaveBeenCalled()172    })173174    it('should be 403 if request has no origin header', async () => {175      const res = await app.request('http://localhost/form', buildSimplePostRequestData())176177      expect(res.status).toBe(403)178      expect(simplePostHandler).not.toHaveBeenCalled()179    })180181    it('should be 200 for application/json', async () => {182      /*183       * via http://example.com184       * Assume localhost allows cross origin POST185       *186       * <script>187       * fetch('http://localhost/form', {188       *   method: 'POST',189       *   headers: {190       *     'content-type': 'application/json',191       *   },192       *   body: JSON.stringify({ name: 'hono' }),193       * });194       * </script>195       */196      const res = await app.request('http://localhost/form', {197        method: 'POST',198        headers: {199          'content-type': 'application/json',200          origin: 'http://example.com',201        },202        body: JSON.stringify({ name: 'hono' }),203      })204205      expect(res.status).toBe(200)206      expect(await res.text()).toBe('hono')207    })208209    it('should be 403 for "Application/x-www-form-urlencoded" cross origin', async () => {210      const res = await app.request('http://localhost/form', {211        method: 'POST',212        headers: Object.assign({213          'content-type': 'Application/x-www-form-urlencoded',214        }),215        body: 'name=hono',216      })217      expect(res.status).toBe(403)218      expect(simplePostHandler).not.toHaveBeenCalled()219    })220221    it('should be 403 if the content-type is not set', async () => {222      const res = await app.request('/form', {223        method: 'POST',224        body: new Blob(['test'], {}),225      })226      expect(res.status).toBe(403)227      expect(simplePostHandler).not.toHaveBeenCalled()228    })229  })230231  describe('with origin option', () => {232    describe('string', () => {233      const app = new Hono()234235      app.use(236        '*',237        csrf({238          origin: 'https://example.com',239        })240      )241      app.post('/form', simplePostHandler)242243      it('should be 200 for allowed origin', async () => {244        const res = await app.request(245          'https://example.com/form',246          buildSimplePostRequestData({ origin: 'https://example.com' })247        )248        expect(res.status).toBe(200)249      })250251      it('should be 403 for not allowed origin', async () => {252        const res = await app.request(253          'https://example.jp/form',254          buildSimplePostRequestData({ origin: 'https://example.jp' })255        )256        expect(res.status).toBe(403)257        expect(simplePostHandler).not.toHaveBeenCalled()258      })259    })260261    describe('string[]', () => {262      const app = new Hono()263264      app.use(265        '*',266        csrf({267          origin: ['https://example.com', 'https://hono.example.com'],268        })269      )270      app.post('/form', simplePostHandler)271272      it('should be 200 for allowed origin', async () => {273        let res = await app.request(274          'https://hono.example.com/form',275          buildSimplePostRequestData({ origin: 'https://hono.example.com' })276        )277        expect(res.status).toBe(200)278279        res = await app.request(280          'https://example.com/form',281          buildSimplePostRequestData({ origin: 'https://example.com' })282        )283        expect(res.status).toBe(200)284      })285286      it('should be 403 for not allowed origin', async () => {287        const res = await app.request(288          'http://example.jp/form',289          buildSimplePostRequestData({ origin: 'http://example.jp' })290        )291        expect(res.status).toBe(403)292        expect(simplePostHandler).not.toHaveBeenCalled()293      })294    })295296    describe('IsAllowedOriginHandler', () => {297      const app = new Hono()298299      app.use(300        '*',301        csrf({302          origin: (origin) => /https:\/\/(\w+\.)?example\.com$/.test(origin),303        })304      )305      app.post('/form', simplePostHandler)306307      it('should be 200 for allowed origin', async () => {308        let res = await app.request(309          'https://hono.example.com/form',310          buildSimplePostRequestData({ origin: 'https://hono.example.com' })311        )312        expect(res.status).toBe(200)313314        res = await app.request(315          'https://example.com/form',316          buildSimplePostRequestData({ origin: 'https://example.com' })317        )318        expect(res.status).toBe(200)319      })320321      it('should be 403 for not allowed origin', async () => {322        let res = await app.request(323          'http://honojs.hono.example.jp/form',324          buildSimplePostRequestData({ origin: 'http://example.jp' })325        )326        expect(res.status).toBe(403)327        expect(simplePostHandler).not.toHaveBeenCalled()328329        res = await app.request(330          'http://example.jp/form',331          buildSimplePostRequestData({ origin: 'http://example.jp' })332        )333        expect(res.status).toBe(403)334        expect(simplePostHandler).not.toHaveBeenCalled()335      })336    })337338    describe('async IsAllowedOriginHandler', () => {339      const app = new Hono()340341      app.use(342        '*',343        csrf({344          origin: async (origin) => {345            await new Promise((r) => setTimeout(r, 10))346            return /https:\/\/(\w+\.)?example\.com$/.test(origin)347          },348        })349      )350      app.post('/form', simplePostHandler)351352      it('should be 200 for allowed origin with async handler', async () => {353        let res = await app.request(354          'https://hono.example.com/form',355          buildSimplePostRequestData({ origin: 'https://hono.example.com' })356        )357        expect(res.status).toBe(200)358359        res = await app.request(360          'https://example.com/form',361          buildSimplePostRequestData({ origin: 'https://example.com' })362        )363        expect(res.status).toBe(200)364      })365366      it('should be 403 for not allowed origin with async handler', async () => {367        let res = await app.request(368          'http://honojs.hono.example.jp/form',369          buildSimplePostRequestData({ origin: 'http://example.jp' })370        )371        expect(res.status).toBe(403)372        expect(simplePostHandler).not.toHaveBeenCalled()373374        res = await app.request(375          'http://example.jp/form',376          buildSimplePostRequestData({ origin: 'http://example.jp' })377        )378        expect(res.status).toBe(403)379        expect(simplePostHandler).not.toHaveBeenCalled()380      })381    })382  })383384  describe('with secFetchSite option', () => {385    describe('string', () => {386      const app = new Hono()387      app.use('*', csrf({ secFetchSite: 'same-origin' }))388      app.post('/form', simplePostHandler)389390      it('should allow matching value', async () => {391        const res = await app.request(392          'http://localhost/form',393          buildSimplePostRequestData({ secFetchSite: 'same-origin' })394        )395        expect(res.status).toBe(200)396      })397398      it('should block non-matching value', async () => {399        const res = await app.request(400          'http://localhost/form',401          buildSimplePostRequestData({ secFetchSite: 'cross-site' })402        )403        expect(res.status).toBe(403)404      })405406      it('should block unknown values', async () => {407        const res = await app.request(408          'http://localhost/form',409          buildSimplePostRequestData({ secFetchSite: 'any' })410        )411        expect(res.status).toBe(403)412      })413    })414415    describe('string[]', () => {416      const app = new Hono()417      app.use('*', csrf({ secFetchSite: ['same-origin', 'none'] }))418      app.post('/form', simplePostHandler)419420      it('should allow "same-origin" value', async () => {421        const res = await app.request(422          'http://localhost/form',423          buildSimplePostRequestData({ secFetchSite: 'same-origin' })424        )425        expect(res.status).toBe(200)426      })427428      it('should allow "none" value', async () => {429        const res = await app.request(430          'http://localhost/form',431          buildSimplePostRequestData({ secFetchSite: 'none' })432        )433        expect(res.status).toBe(200)434      })435436      it('should block not included values', async () => {437        const res = await app.request(438          'http://localhost/form',439          buildSimplePostRequestData({ secFetchSite: 'cross-site' })440        )441        expect(res.status).toBe(403)442      })443    })444445    describe('IsAllowedSecFetchSiteHandler', () => {446      const app = new Hono()447      app.use(448        '*',449        csrf({450          secFetchSite: (secFetchSite, c) => {451            if (secFetchSite === 'same-origin') {452              return true453            }454            if (c.req.path.startsWith('/webhook/')) {455              return true456            }457            return false458          },459        })460      )461      app.post('/form', simplePostHandler)462      app.post('/webhook/test', simplePostHandler)463464      it('should use custom logic for allowed values', async () => {465        const res = await app.request(466          'http://localhost/form',467          buildSimplePostRequestData({ secFetchSite: 'same-origin' })468        )469        expect(res.status).toBe(200)470      })471472      it('should use custom logic for path-based bypass', async () => {473        const res = await app.request(474          'http://localhost/webhook/test',475          buildSimplePostRequestData({ secFetchSite: 'cross-site' })476        )477        expect(res.status).toBe(200)478      })479480      it('should block when custom logic returns false', async () => {481        const res = await app.request(482          'http://localhost/form',483          buildSimplePostRequestData({ secFetchSite: 'cross-site' })484        )485        expect(res.status).toBe(403)486      })487    })488489    describe('async IsAllowedSecFetchSiteHandler', () => {490      const app = new Hono()491      app.use(492        '*',493        csrf({494          secFetchSite: async (secFetchSite, c) => {495            await new Promise((r) => setTimeout(r, 10))496            if (secFetchSite === 'same-origin') {497              return true498            }499            if (c.req.path.startsWith('/webhook/')) {500              return true501            }502            return false503          },504        })505      )506      app.post('/form', simplePostHandler)507      app.post('/webhook/test', simplePostHandler)508509      it('should use async custom logic for allowed values', async () => {510        const res = await app.request(511          'http://localhost/form',512          buildSimplePostRequestData({ secFetchSite: 'same-origin' })513        )514        expect(res.status).toBe(200)515      })516517      it('should use async custom logic for path-based bypass', async () => {518        const res = await app.request(519          'http://localhost/webhook/test',520          buildSimplePostRequestData({ secFetchSite: 'cross-site' })521        )522        expect(res.status).toBe(200)523      })524525      it('should block when async custom logic returns false', async () => {526        const res = await app.request(527          'http://localhost/form',528          buildSimplePostRequestData({ secFetchSite: 'cross-site' })529        )530        expect(res.status).toBe(403)531      })532    })533  })534})