spring-projects / spring-data-mongodb

Provides support to increase developer productivity in Java when using MongoDB. Uses familiar Spring concepts such as a template classes for core API usage and lightweight repository style data access.
https://spring.io/projects/spring-data-mongodb/
Apache License 2.0
1.61k stars 1.08k forks source link

Supply more useful variables to @Encrypted keyId SPEL expression #4304

Open hellproxy opened 1 year ago

hellproxy commented 1 year ago

The keyId SPEL expression for the @Encrypted annotation is great for avoiding hard-coding of encryption key ids. See docs here. Example:

@Document
@Encrypted(keyId = "#{mongocrypt.keyId(#target)}")
static class Patient {

    @Id String id;
    String name;

    @Encrypted(algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Random")
    String bloodType;

    @Encrypted(algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic")
    Integer ssn;
}

However the value bound to #target isn't particularly useful, it's just the simple class name (minus the package!) of the annotated class. See this line:

ctx.setVariable("target", getType().getSimpleName());

This limits the usefulness of the SPEL expression, especially in scenarios where users might want to use different encryption keys for different collections.

A simple but impactful enhancement would be to bind collection as a variable:

ctx.setVariable("collection", getCollection());

Curious to hear people's thoughts on this.

mp911de commented 1 year ago

Thanks for looking into this. If you want, feel free to submit a pull request to add the collection to the context.