Skip to content

Commit aa2bbed

Browse files
Merge pull request #56 from ShimonaR-MC/fix/support-encryption-of-string-fields
S3384399 : Support encryption of string fields
2 parents 437c338 + 39e72ce commit aa2bbed

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

lib/mcapi/utils/utils.js

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,8 +74,9 @@ module.exports.jsonToString = function (data) {
7474
if (typeof data === "undefined" || data === null) {
7575
throw new Error("Input not valid");
7676
}
77+
if (data === "") throw new Error("Json not valid");
7778
try {
78-
if (typeof data === "string" || data instanceof String) {
79+
if ((typeof data === "string" || data instanceof String) && isJson(data)) {
7980
return JSON.stringify(JSON.parse(data));
8081
} else {
8182
return JSON.stringify(data);
@@ -85,6 +86,15 @@ module.exports.jsonToString = function (data) {
8586
}
8687
};
8788

89+
function isJson(str) {
90+
try {
91+
JSON.parse(str);
92+
} catch (e) {
93+
return false;
94+
}
95+
return true;
96+
}
97+
8898
module.exports.mutateObjectProperty = function (
8999
path,
90100
value,
@@ -416,13 +426,13 @@ function hasEncryptionParam(encParams, bodyMap) {
416426
}
417427

418428
module.exports.addEncryptedDataToBody = function(encryptedData, path, encryptedValueFieldName, body) {
419-
body = this.mutateObjectProperty(path.obj, encryptedData, body);
420429
if (
421430
!isJsonRoot(path.obj) &&
422431
path.element !== path.obj + "." + encryptedValueFieldName
423432
) {
424433
this.deleteNode(path.element, body);
425434
}
435+
body = this.mutateObjectProperty(path.obj, encryptedData, body);
426436
return body;
427437
};
428438

test/field-level-encryption.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,22 @@ describe("Field Level Encryption", () => {
145145

146146
assert.ok(JSON.stringify(body) === JSON.stringify(decrypted));
147147
});
148+
149+
it("encrypt property of primitive type", () => {
150+
const res = encrypt.call(fle, "/resource", null, {
151+
elem1: {
152+
encryptedData: "plaintext",
153+
shouldBeThere: "shouldBeThere",
154+
},
155+
});
156+
assert.ok(res.header === null);
157+
assert.ok(res.body.elem1.shouldBeThere);
158+
assert.ok(res.body.elem1.encryptedData);
159+
assert.ok(res.body.elem1.encryptedKey);
160+
assert.ok(res.body.elem1.iv);
161+
assert.ok(res.body.elem1.oaepHashingAlgorithm);
162+
assert.ok(res.body.elem1.publicKeyFingerprint);
163+
});
148164
});
149165

150166
describe("#decrypt", () => {

0 commit comments

Comments
 (0)