Skip to content

Commit 2c80b79

Browse files
committed
Add type check on body when POSTing
Add a check on the typeof the body (e.g. when POSTing) to prevent the client from sending plaintext when `options.json === true`. This is added to avoid the situation where integrating code attempts to POST stringified json, which will likely be rejected by the endpoint (because the payload will appear as plaintext but the `Content-Type` header will declare 'application/json'. Also adds tests to confirm plaintext bodies throw errors (but null payloads are accepted).
1 parent f209a36 commit 2c80b79

3 files changed

Lines changed: 17 additions & 1 deletion

File tree

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ client.get('patrons/12345678').then((resp) => {
6767

6868
To POST a new "TestSchema" schema:
6969
```js
70-
client.post('schemas/TestSchema', '{ "name": "TestSchema", "type": "record", "fields": [ ... ] }')
70+
client.post('schemas/TestSchema', { name: "TestSchema", type: "record", fields: [ ... ] })
7171
.then((resp) => {
7272
if (JSON.parse(resp).data.stream !== 'TestSchema') throw Error('Error creating schema...')
7373
})

lib/client.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,11 @@ class Client {
192192
// Disallow caching anything but GET:
193193
if (method !== 'GET') options.cache = false
194194

195+
// Disallow non-object body if json enabled:
196+
if (options.json && options.body && (typeof options.body) !== 'object') {
197+
return Promise.reject(new Error(`Attempted to ${method} with options.json==true, but body is a ${typeof options.body}`))
198+
}
199+
195200
var uri = this._getFullUrl(path)
196201
var cacheKey = `${method} ${uri}`
197202

test/post-test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,17 @@ describe('Client POST method', function () {
2828
expect(resp).to.be.a('object')
2929
})
3030
})
31+
32+
it('should fail if supplied body is plaintext', function () {
33+
let call = client.post(`schemas/${testSchema.name}`, JSON.stringify(testSchema))
34+
return expect(call).to.be.rejected
35+
})
36+
37+
// A null/empty body should be accepted as valid if options.json===true
38+
it('should succeed if supplied body is empty', function () {
39+
let call = client.post(`schemas/${testSchema.name}`)
40+
return expect(call).to.be.fulfilled
41+
})
3142
})
3243

3344
describe('when config.json=false', function () {

0 commit comments

Comments
 (0)