fix(validator): allow content-type mismatches (#3165)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent 7389b4c · Browse files · 2 files·+161 added−69 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+161 added−69 removed
- tests:+151 added−65 removed
- other:+10 added−4 removed
Provenance
- Commit
4171896- Tree
5774828- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
7389b4c
2 files changed+161 added−69 removed
modified:src/validator/validator.test.ts+151 added-65 removed
4 unmodified lines5 import { HTTPException } from '../http-exception'6 import type {7 ErrorHandler,8 ExtractSchema,9- FormValue,9 MiddlewareHandler,10 ParsedFormValue,11 ValidationTargets,12 } from '../types'24 unmodified lines37 const data = result.data as z.output<T>38 return data39 })40 42-describe('Validator middleware', () => {41+describe('Basic', () => {42 const app = new Hono()43 44 const route = app.get(45 '/search',45 unmodified lines91 }92 return c.json({ message: e.message }, 500)93 }94 96-describe('Malformed JSON', () => {95+describe('JSON', () => {96 const app = new Hono()97 app.post(98 '/post',100- validator('json', (value, c) => {}),99+ validator('json', (value) => value),100 (c) => {102- return c.text('Valid!')101+ return c.json(c.req.valid('json'))102 }103 )105- app.onError(onErrorHandler)104 107- it('Should return 400 response', async () => {105+ it('Should return 200 response with a valid JSON data', async () => {106 const res = await app.request('http://localhost/post', {107 method: 'POST',108+ body: JSON.stringify({ foo: 'bar' }),109+ headers: {110+ 'Content-Type': 'application/json',111+ },112 })111- expect(res.status).toBe(400)113+ expect(res.status).toBe(200)114+ const data = await res.json()115+ expect(data).toEqual({ foo: 'bar' })116 })117 114- it('Should return 400 response, for request with wrong Content-Type header', async () => {118+ it('Should not validate if Content-Type is not set', async () => {119 const res = await app.request('http://localhost/post', {120 method: 'POST',121+ body: JSON.stringify({ foo: 'bar' }),122+ })123+ expect(res.status).toBe(200)124+ const data = await res.json()125+ expect(data.foo).toBeUndefined()126+ })127+128+ it('Should not validate if Content-Type is wrong', async () => {129+ const res = await app.request('http://localhost/post', {130+ method: 'POST',131 headers: {132 'Content-Type': 'text/plain;charset=utf-8',133 },120- body: JSON.stringify({121- any: 'thing',122- }),134+ body: JSON.stringify({ foo: 'bar' }),135 })124- expect(res.status).toBe(400)136+ expect(res.status).toBe(200)137 })138 127- it('Should return 200 response, for request with Content-Type which is a subtype like application/merge-patch+json', async () => {139+ it('Should validate if Content-Type is a subtype like application/merge-patch+json', async () => {140 const res = await app.request('http://localhost/post', {141 method: 'POST',142 headers: {143 'Content-Type': 'application/merge-patch+json',144 },133- body: JSON.stringify({134- any: 'thing',135- }),145+ body: JSON.stringify({ foo: 'bar' }),146 })147 expect(res.status).toBe(200)148+ expect(await res.json()).toEqual({ foo: 'bar' })149 })150 140- it('Should return 200 response, for request with JSON:API Content-Type application/vnd.api+json', async () => {151+ it('Should validate if Content-Type is application/vnd.api+json', async () => {152 const res = await app.request('http://localhost/post', {153 method: 'POST',154 headers: {155 'Content-Type': 'application/vnd.api+json',156 },146- body: JSON.stringify({147- any: 'thing',148- }),157+ body: JSON.stringify({ foo: 'bar' }),158 })159 expect(res.status).toBe(200)160+ expect(await res.json()).toEqual({ foo: 'bar' })161 })162 153- it('Should return 400 response, if Content-Type header does not start with application/json', async () => {163+ it('Should not validate if Content-Type does not start with application/json', async () => {164 const res = await app.request('http://localhost/post', {165 method: 'POST',166 headers: {167 'Content-Type': 'Xapplication/json',168 },159- body: JSON.stringify({160- any: 'thing',161- }),169+ body: JSON.stringify({ foo: 'bar' }),170 })171+ expect(res.status).toBe(200)172+ const data = await res.json()173+ expect(data.foo).toBeUndefined()174+ })175+})176+177+describe('Malformed JSON', () => {178+ const app = new Hono()179+ app.post(180+ '/post',181+ validator('json', (value) => value),182+ (c) => {183+ return c.json(c.req.valid('json'))184+ }185+ )186+187+ it('Should return 400 response if the body data is not a valid JSON', async () => {188+ const formData = new FormData()189+ formData.append('foo', 'bar')190+ const res = await app.request('http://localhost/post', {191+ method: 'POST',192+ headers: {193+ 'Content-Type': 'application/json',194+ },195+ body: formData,196+ })197 expect(res.status).toBe(400)198+ })199+})200+201+describe('FormData', () => {202+ const app = new Hono()203+ app.post(204+ '/post',205+ validator('form', (value) => value),206+ (c) => {207+ return c.json(c.req.valid('form'))208+ }209+ )210+211+ it('Should return 200 response with a valid form data', async () => {212+ const formData = new FormData()213+ formData.append('message', 'hi')214+ const res = await app.request('http://localhost/post', {215+ method: 'POST',216+ body: formData,217+ })218+ expect(res.status).toBe(200)219+ expect(await res.json()).toEqual({ message: 'hi' })220+ })221+222+ it('Should validate a URL Encoded Data', async () => {223+ const params = new URLSearchParams()224+ params.append('foo', 'bar')225+ const res = await app.request('/post', {226+ method: 'POST',227+ body: params,228+ headers: {229+ 'content-type': 'application/x-www-form-urlencoded',230+ },231+ })232+ expect(res.status).toBe(200)233 expect(await res.json()).toEqual({165- success: false,166- message: 'Invalid HTTP header: Content-Type=Xapplication/json',234+ foo: 'bar',235 })236 })237+238+ it('Should return `foo[]` as an array', async () => {239+ const form = new FormData()240+ form.append('foo[]', 'bar1')241+ form.append('foo[]', 'bar2')242+ const res = await app.request('/post', {243+ method: 'POST',244+ body: form,245+ })246+ expect(res.status).toBe(200)247+ expect(await res.json()).toEqual({248+ 'foo[]': ['bar1', 'bar2'],249+ })250+ })251 })252 253 describe('Malformed FormData request', () => {254 const app = new Hono()255 app.post(256 '/post',175- validator('form', (value, c) => ({})),257+ validator('form', (value) => value),258 (c) => {177- return c.text('Valid!')259+ return c.json(c.req.valid('form'))260 }261 )262 app.onError(onErrorHandler)263 182- it('Should return 400 response, for unsupported content type header', async () => {264+ it('Should return 400 response, for malformed content type header', async () => {265 const res = await app.request('http://localhost/post', {266 method: 'POST',267 body: 'hi',268+ headers: {269+ 'content-type': 'multipart/form-data',270+ },271 })272 expect(res.status).toBe(400)273 const data = await res.json()274 expect(data['success']).toBe(false)275 expect(data['message']).toMatch(/^Malformed FormData request./)276 })277+})278 193- it('Should return 400 response, for malformed content type header', async () => {194- const res = await app.request('http://localhost/post', {279+describe('JSON and FormData', () => {280+ const app = new Hono()281+ app.post(282+ '/',283+ validator('json', (value) => value),284+ validator('form', (value) => value),285+ async (c) => {286+ const jsonData = c.req.valid('json')287+ const formData = c.req.valid('form')288+ return c.json({289+ json: jsonData,290+ form: formData,291+ })292+ }293+ )294+295+ it('Should validate a JSON request', async () => {296+ const res = await app.request('/', {297 method: 'POST',196- body: 'hi',298+ body: JSON.stringify({ foo: 'bar' }),299 headers: {198- 'content-type': 'multipart/form-data',300+ 'Content-Type': 'application/json',301 },302 })201- expect(res.status).toBe(400)303+ expect(res.status).toBe(200)304 const data = await res.json()203- expect(data['success']).toBe(false)204- expect(data['message']).toMatch(/^Malformed FormData request./)305+ expect(data.json).toEqual({ foo: 'bar' })306 })307+308+ it('Should validate a FormData request', async () => {309+ const form = new FormData()310+ form.append('foo', 'bar')311+ const res = await app.request('/', {312+ method: 'POST',313+ body: form,314+ })315+ expect(res.status).toBe(200)316+ const data = await res.json()317+ expect(data.form).toEqual({ foo: 'bar' })318+ })319 })320 321 describe('Cached contents', () => {322 describe('json', () => {36 unmodified lines359 })360 }361 })362 250- describe('form', () => {363+ describe('Cached content', () => {364 const app = new Hono()365 const bodyTypes = ['formData', 'text', 'arrayBuffer', 'blob']366 367 for (const type of bodyTypes) {31 unmodified lines399 }400 })401 })402 290-describe('Form with multiple values', () => {291- const app = new Hono()292-293- app.post(294- '/',295- validator('form', (value) => value),296- async (c) => {297- const data = c.req.valid('form')298- return c.json(data)299- }300- )301-302- it('Should return `foo[]` as an array', async () => {303- const form = new FormData()304- form.append('foo[]', 'bar1')305- form.append('foo[]', 'bar2')306- const res = await app.request('/', {307- method: 'POST',308- body: form,309- })310- expect(res.status).toBe(200)311- expect(await res.json()).toEqual({312- 'foo[]': ['bar1', 'bar2'],313- })314- })315-})316-403 describe('Validator middleware with a custom validation function', () => {404 const app = new Hono()405 406 const validationFunction: ValidationFunction<{ id: string }, { id: number }> = (v) => {755 unmodified linesmodified:src/validator/validator.ts+10 added-4 removed
21 unmodified lines22232425262728293031323336 unmodified lines70717273707172747576777879808182838482858687888990919259 unmodified lines21 unmodified lines
// eslint-disable-next-line @typescript-eslint/no-explicit-anytype ExcludeResponseType<T> = T extends Response & TypedResponse<any> ? never : T
const jsonRegex = /^application\/([a-z-\.]+\+)?json$/const multipartRegex = /^multipart\/form-data(; boundary=[A-Za-z0-9'()+_,\-./:=?]+)?$/const urlencodedRegex = /^application\/x-www-form-urlencoded$/
export const validator = < InputType, P extends string, M extends string,36 unmodified lines const contentType = c.req.header('Content-Type')
switch (target) { case 'json': if (!contentType || !/^application\/([a-z-\.]+\+)?json/.test(contentType)) { const message = `Invalid HTTP header: Content-Type=${contentType}` throw new HTTPException(400, { message }) if (!contentType || !jsonRegex.test(contentType)) { break } try { value = await c.req.json() } catch { const message = 'Malformed JSON in request body' throw new HTTPException(400, { message }) } break case 'form': { if (!contentType) { if ( !contentType || !(multipartRegex.test(contentType) || urlencodedRegex.test(contentType)) ) { break }
let formData: FormData59 unmodified lines