Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Parse JSON fields when content-type is set. Fixes #278. #288

Merged
merged 4 commits into from Nov 1, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Expand Up @@ -340,6 +340,25 @@ hello: {
}
```

#### JSON non-file fields

If a non file field sent has `Content-Type` header starting with `application/json`, it will be parsed using `JSON.parse`.

The schema for validation for JSON fields should look like this:
ShogunPanda marked this conversation as resolved.
Show resolved Hide resolved

```js
hello: {
ShogunPanda marked this conversation as resolved.
Show resolved Hide resolved
properties: {
value: {
type: 'object',
properties: {
/* ... */
}
}
}
}
```

## Access all errors

We export all custom errors via a server decorator `fastify.multipartErrors`. This is useful if you want to react to specific errors. They are derived from [fastify-error](https://github.com/fastify/fastify-error) and include the correct `statusCode` property.
Expand Down
24 changes: 23 additions & 1 deletion index.js
Expand Up @@ -160,6 +160,7 @@ function fastifyMultipart (fastify, options, done) {
const RequestFileTooLargeError = createError('FST_REQ_FILE_TOO_LARGE', 'request file too large, please check multipart config', 413)
const PrototypeViolationError = createError('FST_PROTO_VIOLATION', 'prototype property is not allowed as field name', 400)
const InvalidMultipartContentTypeError = createError('FST_INVALID_MULTIPART_CONTENT_TYPE', 'the request is not multipart', 406)
const InvalidJSONFieldError = createError('FST_INVALID_JSON_FIELD_ERROR', 'a request field is not a valid JSON as declared by its Content-Type', 406)

fastify.decorate('multipartErrors', {
PartsLimitError,
Expand Down Expand Up @@ -353,15 +354,36 @@ function fastifyMultipart (fastify, options, done) {

request.pipe(bb)

function onField (name, fieldValue, fieldnameTruncated, valueTruncated) {
function onField (name, fieldValue, fieldnameTruncated, valueTruncated, encoding, contentType) {
let mimetype

// don't overwrite prototypes
if (getDescriptor(Object.prototype, name)) {
onError(new PrototypeViolationError())
return
}

// If it is a JSON field, parse it
if (contentType.startsWith('application/json')) {
// If the value was truncated, it can never be a valid JSON. Don't even try to parse
if (valueTruncated) {
onError(new InvalidJSONFieldError())
return
}

try {
fieldValue = JSON.parse(fieldValue)
ShogunPanda marked this conversation as resolved.
Show resolved Hide resolved
mimetype = 'application/json'
} catch (e) {
onError(new InvalidJSONFieldError())
return
}
}

const value = {
fieldname: name,
mimetype,
encoding,
value: fieldValue,
fieldnameTruncated,
valueTruncated,
Expand Down
208 changes: 208 additions & 0 deletions test/multipart.json.test.js
@@ -0,0 +1,208 @@
'use strict'

const util = require('util')
const test = require('tap').test
const FormData = require('form-data')
const Fastify = require('fastify')
const multipart = require('..')
const http = require('http')
const stream = require('stream')
const pump = util.promisify(stream.pipeline)

test('should parse JSON fields forms if content-type is set', function (t) {
t.plan(5)

const fastify = Fastify()
t.teardown(fastify.close.bind(fastify))

fastify.register(multipart)

fastify.post('/', async function (req, reply) {
for await (const part of req.parts()) {
t.notOk(part.filename)
t.equal(part.mimetype, 'application/json')
t.type(part.value, 'object')
ShogunPanda marked this conversation as resolved.
Show resolved Hide resolved
}

reply.code(200).send()
})

fastify.listen(0, async function () {
// request
const form = new FormData()
const opts = {
protocol: 'http:',
hostname: 'localhost',
port: fastify.server.address().port,
path: '/',
headers: form.getHeaders(),
method: 'POST'
}

const req = http.request(opts, res => {
t.equal(res.statusCode, 200)
res.resume()
res.on('end', () => {
t.pass('res ended successfully')
})
})

form.append('json', JSON.stringify({ a: 'b' }), { contentType: 'application/json' })

try {
await pump(form, req)
} catch (error) {
t.error(error, 'formData request pump: no err')
}
})
})

test('should not parse JSON fields forms if no content-type is set', function (t) {
t.plan(5)

const fastify = Fastify()
t.teardown(fastify.close.bind(fastify))

fastify.register(multipart)

fastify.post('/', async function (req, reply) {
for await (const part of req.parts()) {
t.notOk(part.filename)
t.notOk(part.mimetype)
t.type(part.value, 'string')
}

reply.code(200).send()
})

fastify.listen(0, async function () {
// request
const form = new FormData()
const opts = {
protocol: 'http:',
hostname: 'localhost',
port: fastify.server.address().port,
path: '/',
headers: form.getHeaders(),
method: 'POST'
}

const req = http.request(opts, res => {
t.equal(res.statusCode, 200)
res.resume()
res.on('end', () => {
t.pass('res ended successfully')
})
})

form.append('json', JSON.stringify({ a: 'b' }))

try {
await pump(form, req)
} catch (error) {
t.error(error, 'formData request pump: no err')
}
})
})

test('should throw error when parsing JSON fields failed', function (t) {
t.plan(2)

const fastify = Fastify()
t.teardown(fastify.close.bind(fastify))

fastify.register(multipart)

fastify.post('/', async function (req, reply) {
try {
for await (const part of req.parts()) {
t.type(part.value, 'string')
}

reply.code(200).send()
} catch (error) {
t.ok(error instanceof fastify.multipartErrors.InvalidJSONFieldError)
reply.code(500).send()
}
})

fastify.listen(0, async function () {
// request
const form = new FormData()
const opts = {
protocol: 'http:',
hostname: 'localhost',
port: fastify.server.address().port,
path: '/',
headers: form.getHeaders(),
method: 'POST'
}

const req = http.request(opts, res => {
t.equal(res.statusCode, 500)
res.resume()
res.on('end', () => {
t.pass('res ended successfully')
})
})

form.append('object', 'INVALID', { contentType: 'application/json' })

try {
await pump(form, req)
} catch (error) {
t.error(error, 'formData request pump: no err')
}
})
})

test('should always reject JSON parsing if the value was truncated', function (t) {
t.plan(2)

const fastify = Fastify()
t.teardown(fastify.close.bind(fastify))

fastify.register(multipart, { limits: { fieldSize: 2 } })

fastify.post('/', async function (req, reply) {
try {
for await (const part of req.parts()) {
t.type(part.value, 'string')
}

reply.code(200).send()
} catch (error) {
t.ok(error instanceof fastify.multipartErrors.InvalidJSONFieldError)
reply.code(500).send()
}
})

fastify.listen(0, async function () {
// request
const form = new FormData()
const opts = {
protocol: 'http:',
hostname: 'localhost',
port: fastify.server.address().port,
path: '/',
headers: form.getHeaders(),
method: 'POST'
}

const req = http.request(opts, res => {
t.equal(res.statusCode, 500)
res.resume()
res.on('end', () => {
t.pass('res ended successfully')
})
})

form.append('object', JSON.stringify({ a: 'b' }), { contentType: 'application/json' })

try {
await pump(form, req)
} catch (error) {
t.error(error, 'formData request pump: no err')
}
})
})