diff --git a/lib/mcapi/utils/utils.js b/lib/mcapi/utils/utils.js index 4dd9462..66c626d 100644 --- a/lib/mcapi/utils/utils.js +++ b/lib/mcapi/utils/utils.js @@ -74,8 +74,9 @@ module.exports.jsonToString = function (data) { if (typeof data === "undefined" || data === null) { throw new Error("Input not valid"); } + if (data === "") throw new Error("Json not valid"); try { - if (typeof data === "string" || data instanceof String) { + if ((typeof data === "string" || data instanceof String) && isJson(data)) { return JSON.stringify(JSON.parse(data)); } else { return JSON.stringify(data); @@ -85,6 +86,15 @@ module.exports.jsonToString = function (data) { } }; +function isJson(str) { + try { + JSON.parse(str); + } catch (e) { + return false; + } + return true; +} + module.exports.mutateObjectProperty = function ( path, value, @@ -416,13 +426,13 @@ function hasEncryptionParam(encParams, bodyMap) { } module.exports.addEncryptedDataToBody = function(encryptedData, path, encryptedValueFieldName, body) { - body = this.mutateObjectProperty(path.obj, encryptedData, body); if ( !isJsonRoot(path.obj) && path.element !== path.obj + "." + encryptedValueFieldName ) { this.deleteNode(path.element, body); } + body = this.mutateObjectProperty(path.obj, encryptedData, body); return body; }; diff --git a/test/field-level-encryption.test.js b/test/field-level-encryption.test.js index c0d6b1e..57649f7 100644 --- a/test/field-level-encryption.test.js +++ b/test/field-level-encryption.test.js @@ -145,6 +145,22 @@ describe("Field Level Encryption", () => { assert.ok(JSON.stringify(body) === JSON.stringify(decrypted)); }); + + it("encrypt property of primitive type", () => { + const res = encrypt.call(fle, "/resource", null, { + elem1: { + encryptedData: "plaintext", + shouldBeThere: "shouldBeThere", + }, + }); + assert.ok(res.header === null); + assert.ok(res.body.elem1.shouldBeThere); + assert.ok(res.body.elem1.encryptedData); + assert.ok(res.body.elem1.encryptedKey); + assert.ok(res.body.elem1.iv); + assert.ok(res.body.elem1.oaepHashingAlgorithm); + assert.ok(res.body.elem1.publicKeyFingerprint); + }); }); describe("#decrypt", () => {