Skip to main content

StorageEncryption

Struct StorageEncryption 

Source
pub struct StorageEncryption { /* private fields */ }
Expand description

Storage encryption manager using AES-256-GCM, with per-record random nonces and associated data (AAD) binding each ciphertext to the storage key it was stored under – so a ciphertext copied from one record to another fails to decrypt instead of silently “succeeding” with the wrong value.

Known limitation (replay of an older value under the same key): AAD binds a ciphertext to which record it belongs to, not to when it was written. Someone who can both read an old ciphertext for a given key and write to that same key can replay the old value – AES-GCM’s authentication only proves “this is a genuine envelope for this record,” not “this is the most recent one.” Mitigating this needs a monotonic counter or timestamp bound into the AAD, not done here (most KV-layer values in this crate are replaced wholesale on every write, which bounds but does not eliminate the exposure).

Zeroization scope (accurate, not aspirational): this module zeroizes raw key material and intermediate plaintext it owns on every exit path it controls (success, a validation error, or an encryption failure partway through), as soon as it’s done with it – the [u8; 32] key bytes in LoadedKeys (after the AES-GCM ciphers are built, or before any validation error returns, including the “current key id not found” check), [decode_key]’s intermediate decoded Vec<u8>, every base64-encoded key string EnvKeyProvider reads (file contents and every per-key entry, even ones after a failure elsewhere in the same batch, and even when the file’s current id isn’t present in keys), and migrate_kv_to_encrypted’s intermediate plaintext/raw buffers, including when the subsequent re-encrypt or write-back fails. It does not zeroize: any copy the standard library or aes-gcm makes internally that this code doesn’t control (notably aes 0.8.4’s own key-schedule storage inside the Aes256Gcm cipher object, which has no zeroize support in the version this crate depends on; and HashMap growth can in principle leave a stale decoded-key copy in an old, freed backing allocation during a resize – mitigated, not eliminated, in EnvKeyProvider::load_from_file‘s multi-key decoding loop (the one production path that decodes a variable, potentially large number of keys into a map) by pre-sizing it with with_capacity; EnvKeyProvider::load_keys’ single-env-var path only ever inserts exactly one entry, so it can’t resize at all), or a plaintext value a public method (decrypt, decrypt_from_storage) hands back to its caller (that’s the actual return value the caller needs – it isn’t leftover residue this module can clean up on the caller’s behalf).

Implementations§

Source§

impl StorageEncryption

Source

pub fn new(provider: &dyn KeyProvider) -> Result<Self>

Create a new encryption manager, loading keys from the given provider. Fails closed: if the provider can’t load a usable key, this returns Err rather than any fallback.

Source

pub fn current_key_id(&self) -> &str

The id of the key new values are encrypted under.

Source

pub fn from_env() -> Result<Self>

Create a new encryption manager from the environment (see EnvKeyProvider). Convenience wrapper over new(&EnvKeyProvider).

Source

pub fn generate_key() -> String

Generate a new 256-bit encryption key (base64 encoded), suitable for AUTH_STORAGE_ENCRYPTION_KEY or a keys-file entry.

Source

pub fn encrypt(&self, plaintext: &[u8], aad: &[u8]) -> Result<EncryptedData>

Encrypt raw bytes. aad (associated data) is authenticated but not encrypted – callers should pass the storage key the resulting envelope will be stored under, binding the ciphertext to that specific record.

Source

pub fn decrypt(&self, encrypted: &EncryptedData, aad: &[u8]) -> Result<Vec<u8>>

Decrypt an envelope. aad must match exactly what was passed to Self::encrypt (the storage key the envelope is stored under) – a mismatch (e.g. a ciphertext copied to a different record) fails decryption rather than succeeding with the wrong plaintext.

A format-version-0 envelope (see EncryptedData) is decrypted with an empty AAD against every loaded key in turn, matching the original EncryptedStorage’s behavior (no AAD, no key id) – AES-GCM’s authentication tag makes trying the wrong key safe (it just fails), so this cannot silently produce the wrong plaintext.

Source

pub fn encrypt_for_storage(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>>

Encrypt raw bytes for storage, serialized as a self-describing envelope. aad should be the storage key this will be stored under. Accepts arbitrary bytes, not just UTF-8 text.

Source

pub fn decrypt_from_storage(&self, data: &[u8], aad: &[u8]) -> Result<Vec<u8>>

Decrypt a storage envelope produced by Self::encrypt_for_storage. aad must be the same storage key passed to that call.

Source

pub fn parse_envelope(data: &[u8]) -> Option<EncryptedData>

Parses data as one of this module’s own serialized envelopes – either the current format or the original format-version-0 shape (see EncryptedData) – without attempting to decrypt it. None if data isn’t valid UTF-8 JSON, doesn’t name the right algorithm, or claims a post-v0 format without a key_id.

This is a shape check only. A value that parses here but fails to decrypt (wrong key, corrupted, or tampered with) is a hard error from Self::decrypt_from_storage, never silently treated as plaintext.

Source

pub fn looks_like_envelope(data: &[u8]) -> bool

Returns true if data parses as one of this module’s own serialized envelopes. Used by migrate_kv_to_encrypted and EncryptedStorage::get_kv to decide whether a stored value should be decrypted at all.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more