Automattic / Automattic/mongoose

Mongoose Middleware and MongoDB CSFLE Explicit Encryption / Automatic Decryption

Open
#13,412 5 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
JavaScript
Stars
27.5k
Forks
4k
Avg merge
2d 7h
Merged PRs (30d)
35

Description

### Prerequisites

- [X] I have written a descriptive issue title

### Mongoose version

6.5.2

### Node.js version

18

### MongoDB version

5.0.17

### Operating system

macOS

### Operating system version (i.e. 20.04, 11.3, 10)

_No response_

### Issue

Using the MongoDB Community Edition, and its CSFLE Explicit Encryption and Automatic Decryption, I am trying to figure out the best way to insert the ClientEncryption.encrypt() in the Mongoose “save” process.

Let’s say we want to encrypt the `{ lastName: String }` field on save.

On one hand, the encrypted data must be saved on MongoDB as BinData (to benefit from automatic decryption for MongoDB), on the other: we would like to keep lastName defined as String in the Mongoose as schema.

Defining a field as String in the Mongoose schema forces the casting to String when saving the lastName (which would prevent the automatic decryption).
The `pre(‘save’)` doesn’t seem to allow to recast the String to BinData.

To get it to work, we had to change the lastName field’s SchemaType from String to Mixed.

Here is the question: is there a way to keep the SchemaType as String, and invoke the ClientEncryption.encrypt() and recast the String to BinData just before Mongoose makes the call to the MongoDB?
Maybe using a specific hook in the Mongoose middleware?

Thank you for your suggestion.

Contributor guide

Open the contributing guide

Research direction

Start with Mongoose's save process and the pre('save') middleware, then trace how String and Mixed SchemaTypes are cast before the MongoDB call. Compare that path with ClientEncryption.encrypt() and MongoDB CSFLE automatic decryption. Done means determining and documenting whether String can remain the schema type while encrypted values are stored as BinData.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, mongodb, node.js
Domain
backend, databases, security
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.