This concept comes from a book I really enjoyed reading last year, Secure by Design. The authors suggest using a "read-once object" to represent sensitive values to avoid unintentional use or data leakage. A read-once objects has the following properties -
- Its main purpose is to facilitate detection of unintentional use
- It represents a sensitive value or concept
- It's often a domain primitive
- Its value can be read once, and once only
- It prevents serialization of sensitive data
- It prevents subclassing and extension
In the book, the authors start with the example of a
Password domain primitive as a read-once object. If you're one of the brave readers of this note, you've likely seen a few passwords stored as strings on user objects. While there are plenty of benefits to the use of a domain primitive over a string (validations, unit testing, encapsulation), once you've read the password to compare it during authentication, there's no need to keep it around. While there are other ways of removing from memory or scrubbing logs, why bother? There's enough to remember as it is.
The book provides additional examples and relies heavily on the value of DDD as a foundation for secure design throughout the book. There's a free chapter on the publisher's site on domain primitives.
I spotted this repo putting the concept to practice in TypeScript. Maybe one day will get around to putting together some examples in other languages (or better yet, using the idea on a project). In Ruby, for example, I'd think about overriding
to_json, maybe use object lifecycle callbacks to prevent subclassing, and clone and return a temporary value in the property getter. There's plenty more in the book, I'd highly recommend it.