Skip to content

Instantly share code, notes, and snippets.

@sarjarapu
Created January 23, 2020 15:18
Show Gist options
  • Save sarjarapu/9933e1381fc0abd9f6a031be3d200816 to your computer and use it in GitHub Desktop.
Save sarjarapu/9933e1381fc0abd9f6a031be3d200816 to your computer and use it in GitHub Desktop.
A JavaScript to show how JSONSchema can be used to enforce clients to insert encrypted data than plain text data.
// So let's drop all the information in patients collection
plainDB.getCollection("patients").remove({"_id": 3});
// define server-side JSON and retry the insert
var patientsJSONSchema = {
"bsonType": "object",
"properties": {
"ssn": {
"encrypt": {
"bsonType": "string",
"algorithm": SSN_ENCRYPTION_ALGORITHM,
"keyId": [SSN_ENCRYPTION_KEY_UUID]
}
},
"mobile": {
"encrypt": {
"bsonType": "string",
"algorithm": MOBILE_ENCRYPTION_ALGORITHM,
"keyId": [MOBILE_ENCRYPTION_KEY_UUID]
}
},
"comment": {
"bsonType": "string"
}
}
};
// apply the jsonSchema validation for the patients and retry inserting document using plain text
plainDB.runCommand({ collMod: "patients", validator: { $jsonSchema: patientsJSONSchema } });
// Note that the insert is still using plain text on a plainDB object
// however because of the server side data validation the attempt to insert plain text fails
plainDB.getCollection("patients").insert({
"_id": 3,
"medRecNum": 3,
"firstName": "Jason",
"lastName": "Doe",
"ssn": "333-33-3333",
"mobile": "333-333-3333",
"comment": "Jason Doe SSN/Phone should have been encrypted, but the app/dev forgot to do so."
});
/*
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 121,
"errmsg" : "Document failed validation"
}
})
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment