Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

KMS envelope encryption for Rust

The library provides envelope encryption with a key encryption key held by a KMS, and AEAD encryption without a KMS. It covers:

To start using the library, see Getting started.

Envelope encryption

A value is encrypted with an AEAD algorithm under a data encryption key (DEK). The DEK is then encrypted by a key encryption key (KEK) that never leaves the KMS, and the encrypted DEK is stored next to the cipher text. KMS documentation, and Azure Key Vault’s wrapKey and unwrapKey operations, call this wrapping the DEK. To read the value, the KMS decrypts the DEK, and the DEK decrypts the value locally.

So the KMS sees only DEKs, never the data, and a KMS call is needed only to encrypt or decrypt a DEK. Access to the data is controlled by access to the KEK: revoke the KMS permission, or destroy the key, and the stored values cannot be decrypted.

The additional authenticated data (AAD) is authenticated but not encrypted: a value decrypts only with the AAD it was encrypted with. Use it to tie a value to where it is stored, such as a table and a row id, so that a value copied to another row fails to decrypt.

Choosing a mode

The ways to use a KMS differ in how many DEKs exist, how often the KMS is called and what a stored value holds. The table below sets the four modes side by side. Pick one by what the data needs:

  • Per-call envelope, the default of KmsAeadEnvelope. Use it when values are written rarely, such as secrets and configuration, or when one DEK per value is a requirement. See Envelope encryption;
  • Store-less DEK reuse, a KmsAeadEnvelope with a DekReusePolicy. Use it for high write rates where a KMS call per value costs too much. See DEK caching and reuse and Cut KMS calls with a DEK cache and DEK reuse;
  • One fixed key, encrypt of AeadCipher or DeterministicCipher. Use it for a column that BigQuery reads, with no key rotation. See One fixed key;
  • Keyring, the kms-aead-keyring crate. Use it when keys need central rotation and retirement, or when BigQuery and Tink read values across rotations. See Keyring and field encryption.
Per-call envelopeStore-less DEK reuseOne fixed keyKeyring
Cratekms-aeadkms-aeadkms-aeadkms-aead-keyring
DEKsone per valueone per process at a time, renewed by age or countone, encrypted once by an administrative jobone per key version of a scope
KMS calls on writeone encryption per valueone encryption per renewed DEKno encryption, and one decryption per DEK cache TTLno encryption, and one decryption per key version per DEK cache TTL
KMS calls on readone decryption per value, or per DEK cache missone decryption per DEK per cache TTLone decryption per cache TTLone decryption per key version per cache TTL
A value carriesits encrypted DEKits encrypted DEKa 4-byte key ida 4-byte key id
Infrastructurea KMSa KMSa KMS, and the encrypted DEK in the application’s settingsa KMS and a keyring store
Rotationthe KEK in the KMSthe KEK in the KMS, and DEK renewal per processthe KEK in the KMS; the DEK is not rotatedcentral: staged rotate and promote, retire, destroy, and a compromised flag every process sees
Deterministic fieldswith keys the application stores, see Deterministic encryptionnoyes, with DeterministicCipheryes, with queries across rotations
BigQuery readersnonoyes, with a keyset of the key encrypted by a Cloud KMS KEKyes, with a Cloud KMS KEK
Tink readersyes, with KmsEnvelopeAead for GCP and AWS keysyes, with KmsEnvelopeAead for GCP and AWS keysyes, with a keyset of the keyyes, with a KEK in Cloud KMS, AWS KMS by key ARN or Vault Transit
Crypto-shreddingKEK destructionKEK destructionKEK destructionKEK destruction, or dangerously_shred() and the deletion of the record’s backups

No mode needs another. Values of the envelope modes move to a keyring with a sweep, see Move envelope values to a keyring.

Streamed values come in the same modes: under a keyring, under an envelope, or with a DEK the application holds, see Streaming encryption.

Both envelope modes encrypt a value of a Rust type, such as an application newtype, into an Encrypted<T, Envelope> that carries its encrypted DEK, and serde, tokio-postgres and sqlx store it as bytes, so a column of secrets needs no store of its own. See Stored values.

AeadCipher and DeterministicCipher work without a KMS at all, with keys the application holds.

Where to start

The setup is under Getting started: Choose a provider and a backend, FIPS included, and Develop and test without a cloud.

Use cases are in five groups, each a situation and the way through it:

ToRead
Encrypt columns, make fewer KMS calls, give each customer its own keys, look a row up by an encrypted value or erase a customerProtect data in your database
Let BigQuery or Tink read encrypted columns, or let partners and devices encrypt without being able to decryptShare encrypted data with other systems
Encrypt uploads and exports of any size, and read byte ranges of themFiles and streams
Publish a file anyone can verify, or detect tampering between your own servicesProve where data came from
Log a payload that fails to parse, with no encryptionKeep sensitive data out of logs

Running in production, one page per task:

ToRead
Give the applications and the administration their own rightsPermissions: applications and administration
Alert on bothMonitoring and alerts
Rotate the DEKs and the KEK without downtimeRotate keys and re-encrypt values
Respond to a leaked key or a damaged keyring recordIncident runbook
Stop a writer of the keyring store from changing which keys are usedProtect the keyring record
Move envelope values to a keyringMove envelope values to a keyring

Moving to a newer version is covered by the guides in the Upgrading section at the end of the book: Migrating from 0.30 and Migrating from 0.29. Apply them in order, newest first.

Licence

Apache Software License (ASL)

Getting started

This page adds the crate, encrypts a value with an envelope and with a keyring, and links the choices a build makes. To decide which provider and backend fit, read Choose a provider and a backend.

Cargo.toml:

[dependencies]
kms-aead = { version = "0.34", features = ["gcp-kms-encryption", "aws-lc"] }

The crate has no default features. A build makes three choices, and they do not constrain each other:

  1. the KMS providers, any number of them, or none for AEAD without a KMS;
  2. the TLS root store and the TLS crypto provider of each provider that has a choice;
  3. the crypto backends that run the AEAD algorithms, one or more.

Features

Every feature of both crates is in Cargo features.

Choosing a backend

There is no default backend: each backend feature adds a type to kms_aead::backends, Ring, AwsLc or RustCrypto, and every type that encrypts takes one as its backend type parameter. Which one fits a build, FIPS and the C toolchain included, is in Choose a provider and a backend.

With an envelope

The local KMS needs no cloud account, so it is the quickest way to try the library. An ephemeral KEK lives as long as the process:

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, KmsAeadEnvelope};
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

let aad = b"orders/1042";
let secret = SecretValue::from("4111 1111 1111 1111");

let encrypted: Encrypted<SecretValue, Envelope> = envelope.encrypt(aad, &secret).await?;
let decrypted: SecretValue = envelope.decrypt(aad, &encrypted).await?;

assert_eq!(decrypted, secret);
Ok(())
}

To move to a cloud KMS, replace the provider, see KMS providers. The rest of the code stays the same.

With a keyring

Field encryption under a keyring is the kms-aead-keyring crate, see Keyring and field encryption. Its features are in Cargo features.

Cargo.toml:

[dependencies]
kms-aead = { version = "0.34", features = ["gcp-kms-encryption", "ring"] }
kms-aead-keyring = { version = "0.34", features = ["ring", "admin", "firestore-tls-roots"] }
secret-vault-value = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

A keyring on the memory store with a local KEK, for an application type Email. It needs no cloud credentials, and needs the admin feature for create, rotate and promote.

  • KeyringAdmin creates and rotates the keyring, and Keyring is the application’s handle that encrypts and decrypts;
  • a rotation is staged: rotate adds a version, and a later promotion makes it the one that encrypts, so every process can load the new version before it is used;
  • FieldAad is the AAD of one field of one record, built from the entity kind, the field name and the entity id.
use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::KmsAeadResult;
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldAad, FieldName, FieldSpec, KeyId, Keyring, KeyringAdmin,
    KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions, Plaintext, Purpose,
    Encryptor,
};
use secret_vault_value::SecretValue;

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

const TENANT: KeyringId = KeyringId::from_static("tenant-42");
const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(provider, TENANT, KeyringAlgorithms::new())
    .await?;
// The application's handle on the same keyring
let keyring: &Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = admin.keyring();

// The AAD ties the value to user 42's email: `user/42/email`
let aad: FieldAad = EMAIL.aad(&EntityId::try_from("42")?);
let alice = Email("alice@example.com".to_string());
// One encryptor per write of a record, for every encrypted field it holds
let encryptor: Encryptor<'_, MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = keyring.encryptor().await;
let value: Encrypted<Email, Randomized> = encryptor.encrypt(&aad, &alice).await?;
assert_eq!(value.key_id(), KeyId::new(1));

// A staged rotation keeps the previous version decrypting. One process has nothing to wait for,
// so it promotes at once
let staged: KeyId = admin.rotate(Purpose::Randomized).await?;
admin.promote_now(staged).await?;
assert_eq!(keyring.decrypt(&aad, &value).await?, alice);
registry.shutdown(None).await;
Ok(())
}

The registry, its handles and the encryptor are in The registry and its handles.

Full example available here, run it with cargo run -p kms-aead-keyring --example local_kms --features ring,admin.

MSRV

The minimum supported Rust version is 1.99, for every feature.

Choose a provider and a backend

A build makes two choices that do not constrain each other: the KMS that holds the KEK, and the crypto backend that runs the AEAD algorithms. Both are Cargo features, see Cargo features.

KMS providers

The KMS decides who else reads the values, what a rotation takes and how a scope is crypto-shredded:

Google Cloud KMSAWS KMSAzure Key VaultVault TransitLocal KMS
Tink reads envelope valuesyesyesnonono
Tink reads keyring keysetsyesyes, with a key named by its ARNnoTink for Go onlyno
BigQuery readsyesnononono
KMS random generatoryes, at the HSM protection levelyesnonono
KEK version on each encrypted DEKyesno, Noneyesyesyes
Disabling an old KEK versionyes, eventually consistentno, for key material AWS KMS generatedyesyes, with min_decryption_versionyes, by dropping it from the list
Crypto-shredding a scopedestroying its KEK versionsdeleting the keydeleting the key, with all its versionsdeleting its key versionsdestroying every copy of the KEK

Notes on the table:

The TLS root store and the TLS crypto provider are a feature choice for Google Cloud KMS, Azure and Vault Transit, with the rules in Feature rules.

Crypto backends

ringaws-lcaws-lc-fipsrustcrypto
AES-256-GCM-SIVnoyesyesyes
RSA-OAEP encryption, for a producer under an asymmetric KEKnoyesyesyes
FIPS modulenonoyesno
Needs a C toolchainyesyesyes, with CMake and Gono
A second crypto library beside a cloud provideryesnonoyes
Key schedules zeroisednoyes, by AWS-LC’s allocatoryes, by AWS-LC’s allocatoryes

Every backend has ChaCha20-Poly1305, AES-128-GCM and AES-256-GCM, writes the same bytes, and decrypts the values of any other, so a move from one backend to another needs no migration of the data, see Cross-backend compatibility.

  • Producers under an asymmetric KEK: a producer needs a backend with RSA encryption, so it cannot run on ring. Readers need nothing of RSA on any backend, see Accept data from partners and devices that cannot read it back;
  • No second crypto library: the default features of the cloud providers already build aws-lc-rs for TLS, so aws-lc adds nothing to a provider build, see aws-lc-rs and FIPS;
  • FIPS: aws-lc-fips runs the backend on the AWS-LC FIPS module and moves every user of aws-lc-rs in the build to it, the rustls provider included. AES-256-GCM is the algorithm for a FIPS deployment. AES-SIV, the deterministic algorithm, is not FIPS-approved and runs on RustCrypto whatever the backend, so deterministic fields stay outside the validated boundary, see aws-lc-rs and FIPS;
  • No C toolchain: rustcrypto is pure Rust;
  • Zeroisation: what each backend leaves in freed memory is in Crypto backends.

A build may enable several backends at once, and code generic over the backend bounds it with B: AeadBackend and nothing else, see Code generic over the backend.

Develop and test without a cloud

The local KMS, the memory store and local servers for the other stores run the same code paths as production, with no cloud account. What each one keeps, and for how long, decides where it fits.

PieceForKeeps its keys
LocalKmsProvider::ephemeraltestsfor the life of the provider
LocalKmsProvider::new with LocalKek::from_env or from_filea development databaseas long as the variable or the file
MemoryKeyringStoretestsfor the life of the process
a Firestore emulator, a local PostgreSQL or an S3-compatible servera development keyring storeas long as the server’s data

The KMS

  • Tests: LocalKmsProvider::ephemeral has one random KEK that lives as long as the provider. Every DEK it encrypts, and so every value, is unreadable once the process exits, see Tests and development;
  • a development environment whose data outlives a run keeps a KEK in a variable or a file, with LocalKek::from_env or LocalKek::from_file, see the same section. A value written with the local KMS never decrypts under a cloud KMS, so a development database starts again empty on the move to one.

The provider is in every build, with no feature, and logs its KEK id and where each version came from at INFO when it is created.

The keyring store

  • Tests: MemoryKeyringStore, in kms_aead_keyring::testing, loses its records, and with them every DEK, when the process exits. A test that creates keyrings in it enables admin in [dev-dependencies] only, see Permissions: applications and administration;

  • Firestore: the emulator of the Google Cloud CLI, gcloud emulators firestore start, and FIRESTORE_EMULATOR_HOST set to its address. FirestoreDb::new connects to the emulator while the variable is set, so the store needs no change. The sweep_firestore example runs on it:

    docker run --rm -d --name kms-aead-firestore -p 8687:8687 \
      gcr.io/google.com/cloudsdktool/google-cloud-cli:emulators \
      gcloud emulators firestore start --host-port=0.0.0.0:8687
    FIRESTORE_EMULATOR_HOST=127.0.0.1:8687 PROJECT_ID=kms-aead-emulator \
      cargo run -p kms-aead-keyring --example sweep_firestore --features ring,admin,firestore-tls-roots
    
  • PostgreSQL: a local server, the table of PostgreSQL, and a connection with NoTls. The sweep_postgres example reads its connection string from KMS_AEAD_KEYRING_POSTGRES_URL;

  • S3: an S3-compatible server such as MinIO, once it passes the store conformance suite, see S3-compatible servers.

Cloud Storage has no local server in the store’s tests.

A first run

The local_kms example creates a keyring on the memory store with a local KEK, rotates it and reads a value written before the rotation: cargo run -p kms-aead-keyring --example local_kms --features ring,admin. The same with kms-aead alone is in With an envelope.

Limits

  • The local KMS has no IAM and no audit log, and the KEK in a variable stays in the process environment, see Local KMS;
  • values encrypted under a local KEK are not exported to BigQuery, which decrypts with Cloud KMS only.

Protect data in your database

The values live in your own tables and the application reads them back. These use cases cover encrypting the columns, the cost in KMS calls, a set of keys for each customer, lookups by an encrypted value, and erasing a customer.

Pick this whenUse case
Customers’ emails, phone numbers or API tokens sit in your own tablesEncrypt personal data and secrets in your database
Reads or writes make too many KMS callsCut KMS calls with a DEK cache and DEK reuse
One customer needs its keys rotated or destroyed without touching the othersGive each customer of a SaaS its own keys
A row has to be found by an encrypted value, such as an emailFind a user by an encrypted email
A customer’s data has to become unreadable, backups includedErase one customer’s data for good

Encrypt personal data and secrets in your database

An application stores customers’ emails and phone numbers, or the API tokens of their integrations, in its own tables. A copy of the database, a backup or a read-only replica leaks them, and so does anyone with a SQL console. Each field is encrypted under a DEK that a cloud KMS encrypts, with no keyring store. Every value carries its encrypted DEK, so nothing is stored apart from the values. For central rotation, deterministic fields across rotations or BigQuery reads across rotations, see Choosing a mode and the keyring.

Which mode

Values areModeSee
written rarely, such as secrets and configurationper-call envelopeEnvelope encryption
written at a high rate, or read repeatedlystore-less DEK reuse for writes, and a DEK cache for readsCut KMS calls with a DEK cache and DEK reuse
grouped, such as a file in chunks or a tenant’s rows, with one DEK the application keepsthe *_with_dek and *_with_encrypted_dek callsWorking with DEKs yourself
encrypted with a key the application holds, with no KMSAeadCipherAEAD without a KMS

The modes are compared in Choosing a mode.

The path

  1. A provider for the KMS, such as GcpKmsProvider::new(&key_ref), see KMS providers, with the rights of With kms-aead alone: decrypt for a reader, and encrypt too for a writer;
  2. KmsAeadEnvelope::new(provider), or with_options with a DekReusePolicy for store-less DEK reuse and a DekCache for repeated reads, see DEK caching and reuse;
  3. a newtype per field, such as Email, that implements Plaintext, and normalises the value if it is ever looked up, see Plaintext;
  4. the AAD that ties the value to its place, <table>/<row id>/<column>, so a value copied into another row fails to decrypt, see AAD;
  5. envelope.encrypt(aad, &value) into an Encrypted<Email, Envelope>, stored as a serde field, a BYTEA column through tokio-postgres or sqlx, or hex in a TEXT column, see Storing;
  6. envelope.decrypt(aad, &encrypted) with the same AAD, rebuilt from the row.

A first example, with the local KMS, is in With an envelope.

What to watch for

Cut KMS calls with a DEK cache and DEK reuse

A service decrypts the same stored values on every request: a profile page that shows an email, a payment screen that shows a card’s last digits. With a per-call envelope each decryption is one KMS call, so latency, quota and the KMS bill grow with the traffic. An event or audit stream has the opposite problem: it writes thousands of values a second, and one KMS call to encrypt a DEK for each value is far too many. A DekCache makes reads call the KMS once per DEK and TTL, and a DekReusePolicy makes writes call it once per renewed DEK. Both keep the stored format of a per-call envelope: every value still carries its encrypted DEK.

Reads: a DEK cache

A per-call envelope has no cache unless its options give it one. Pass a DekCache to KmsAeadEnvelopeOptions, and every decrypt of a value whose DEK the cache holds skips the KMS:

use kms_aead::backends::Ring;
use kms_aead::cache::{DekCache, DekCacheOptions};
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, KmsAeadEnvelope, KmsAeadEnvelopeOptions};
use secret_vault_value::SecretValue;
use std::num::NonZeroUsize;
use std::time::Duration;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let cache = DekCache::new(
    DekCacheOptions::new()
        .with_ttl(Duration::from_secs(5 * 60))
        .with_max_entries(NonZeroUsize::new(10_000).expect("not zero")),
)?;

let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::with_options(
    provider,
    KmsAeadEnvelopeOptions::new().with_dek_cache(cache),
)?;

let stored: Encrypted<SecretValue, Envelope> = envelope
    .encrypt(b"users/1/email", &SecretValue::from("ada@example.com"))
    .await?;

// The first read decrypts the DEK with the KMS, the next ones within the TTL do not
let first: SecretValue = envelope.decrypt(b"users/1/email", &stored).await?;
let second: SecretValue = envelope.decrypt(b"users/1/email", &stored).await?;
assert_eq!(first, second);
Ok(())
}

Clone shares the cache, so one cache may serve every envelope of the process, over several KEKs as well.

Choosing the TTL and the size

  • A cache serves an entry for its TTL after it was inserted. A longer TTL saves more KMS calls, keeps DEKs in memory for longer and delays the effect of a revoked KMS permission;
  • past max_entries the cache evicts the oldest entry. Set it above the number of distinct DEKs read per TTL, otherwise reads evict each other’s keys and the KMS is called again;
  • with per-call envelopes every value has its own DEK, so the cache helps only values read more than once within the TTL. A value read once is one KMS call with or without it.

The defaults of the TTL and of max_entries are in DEK cache.

As an example, a service reads 100 values a second, drawn from 2,000 distinct values, each with its own DEK. Without a cache that is 100 × 3,600 = 360,000 KMS decryptions an hour. With a cache of max_entries 4,096 and the default TTL of 15 minutes, each DEK is decrypted at most once per TTL, so at most 2,000 × 4 = 8,000 an hour, and concurrent misses of one DEK share a single call. The figures follow from the number of distinct DEKs and the TTL, and fewer distinct values need fewer calls.

Writes: DEK reuse

A DekReusePolicy makes the envelope encrypt many values under one DEK and renew it by age, by count of values or by bytes, whichever comes first. A write calls the KMS only to renew the DEK:

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{DekReusePolicy, Encrypted, KmsAeadEnvelope, KmsAeadEnvelopeOptions};
use secret_vault_value::SecretValue;
use std::num::NonZeroU64;
use std::time::Duration;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::with_options(
    provider,
    KmsAeadEnvelopeOptions::new().with_dek_reuse(
        DekReusePolicy::new()
            // The envelope's DEK cache drops the DEK after its TTL, 15 minutes by default, and the
            // next write renews it, so `max_age` decides only when the cache's TTL is longer
            .with_max_age(Duration::from_secs(60 * 60))
            .with_max_uses(NonZeroU64::new(1_000_000).expect("not zero")),
    ),
)?;

// One KMS encryption for both values
let first: Encrypted<SecretValue, Envelope> =
    envelope.encrypt(b"events/1", &SecretValue::from("first")).await?;
let second: Encrypted<SecretValue, Envelope> =
    envelope.encrypt(b"events/2", &SecretValue::from("second")).await?;

// Read with any envelope over the same KEK and algorithm
let decrypted_first: SecretValue = envelope.decrypt(b"events/1", &first).await?;
let decrypted_second: SecretValue = envelope.decrypt(b"events/2", &second).await?;
assert_eq!(decrypted_first, SecretValue::from("first"));
assert_eq!(decrypted_second, SecretValue::from("second"));
Ok(())
}

Each value carries its encrypted DEK, so nothing is stored apart from the values, and values under earlier DEKs stay readable. Readers need no policy: any envelope over the same KEK decrypts them, and a reader with a DekCache calls the KMS once per DEK and TTL, as in the previous section.

As an example, a writer encrypts 1,000 values a second. With one DEK per value that is 3,600,000 KMS encryptions an hour. A store-less envelope keeps its DEK in a cache and renews the DEK when the cache drops it. With the default TTL of 15 minutes this writer renews it every 15 minutes, before max_uses of 1,000,000 values or max_age of an hour is reached: 4 KMS encryptions an hour for the process. To renew by max_age instead, give the envelope a DekCache whose TTL is longer than it.

With a keyring

A keyring needs no policy: its values carry a 4-byte key id instead of an encrypted DEK, so a write calls no KMS, and a read decrypts each key version’s DEK once per DEK cache TTL. KeyringRegistryOptions::with_dek_cache sets the cache and its TTL, see Record cache.

What to watch for

  • A disabled KMS key or a revoked IAM grant reaches cached keys only when their entries expire, see Invalidation for dropping them at once;
  • the cache runs no thread of its own, so a process that can sit idle while it holds keys purges expired ones on a timer, see Key lifetime;
  • a store-less writer that shares a cache with readers needs max_entries above the distinct DEKs read per TTL, or a cache of its own, see The DEK lives in the cache;
  • the bytes a DEK encrypts are bounded, see Volume limit.

The full behaviour of the cache and the policy is in DEK caching and reuse.

Give each customer of a SaaS its own keys

A SaaS product stores the data of many customers. One of them asks for its keys to be rotated, or leaves and wants its data gone, and with one set of keys for everybody that cannot be done without touching the others. A multi-tenant application gives each tenant a keyring of its own: its own key versions, rotated, flagged and destroyed apart from the others, in one keyring store such as Firestore or PostgreSQL. The keyring id names the tenant, see The record for the ids it takes.

One KEK per tenant or one shared KEK

A KEK per tenantOne shared KEK
A DEK copied into another tenant’s recordfails at the KMS, which decrypts with the tenant’s own KEKdecrypts, since the KMS decrypts it for any principal allowed to decrypt with the KEK
KMS rightsper tenant, so a principal can be limited to some tenantsone grant covers every tenant
Crypto-shredding a tenantdestroying its KEK, backups of the record and exported keysets includeddangerously_shred(), and then deleting the record’s backups, the store’s other copies and the exported keysets, or a KEK rotation for every other keyring
KMS keys to manageone per tenantone

The first row is the store-writer threat of Keyring deployment, and the third the two routes of Crypto-shredding. A deployment that needs either guarantee uses a KEK per tenant.

Creating the keyrings

An application opens only keyrings that exist, so each tenant’s keyring is created first:

  • by the administrative job, as part of onboarding a tenant, with create or open_or_create;
  • or by the application on the tenant’s first request, with open_or_create, see What to watch for.

The path through the API

  1. One KeyringRegistry per process and store, with the store and the backend, see The registry and its handles;
  2. registry.open(provider, keyring_id) for each tenant the process serves. A second open of an open keyring reads nothing from the store and shares the first one’s record and watch. The call takes the provider by value: one provider serves every keyring of its KEK as an Arc<P>, which implements the provider traits for every provider, or as a clone of a provider that is Clone, such as GcpKmsProvider, AwsKmsProvider and HcVaultTransitProvider;
  3. a FieldSpec constant per encrypted field, the same for every tenant, since each keyring has DEKs of its own, see Encrypted fields and AAD;
  4. on every write, keyring.encryptor() and its encrypt, and the encryption marker it gives, see The encryption marker; on every read, keyring.decrypt;
  5. registry.shutdown(None) before the process exits, see The registry and its handles.

Rotations and sweeps run per keyring: the administrative job loops over the tenants, see Rotate keys and re-encrypt values.

What to watch for

An application that creates a keyring on a tenant’s first request builds with the admin feature and runs with the administrative rights, so it is trusted as the administration is, see Permissions: applications and administration and Keyring limits. Under RecordSignaturePolicy::Required it holds the record signer too and calls open_or_create_signed: open_or_create fails with RECORD_SIGNER_MISSING where it would create the record.

What many keyrings cost

A keyring stays open until the registry shuts down, so a process holds every keyring it opened:

  • store reads: one at the first open, and one revalidation per keyring per record_ttl, or per change signal, see How the record is refreshed;
  • connections: a store holds a fixed number of listen streams or connections, however many keyrings it serves, see Keyring stores;
  • the DEK cache: one per registry, shared by its keyrings, with an entry per version in use per keyring. An entry evicted for capacity is decrypted through the KMS again on its next use, so size it above the tenants a process serves times the versions each uses, see Sizing;
  • KMS calls: one decryption per version per DEK cache TTL in every process, and two per version in each reencrypt_deks. A KEK rotation re-encrypts every keyring under the KEK, see The KMS decrypt burst;
  • metrics: the plaintext size histogram has a series per keyring and version, see Metrics for its cardinality limit.

Find a user by an encrypted email

A login form asks for an email, and the users table stores it encrypted. A randomised value is different every time it is encrypted, so a data store cannot find a row by it. Two ways make a field searchable by equality: a deterministic field, whose stored value is equal for equal plaintexts, and a beacon, a truncated HMAC stored beside a field that stays randomised.

Beacon or deterministic field

BeaconDeterministic field
Stored valueRandomised, so its AAD can name the row, and a value copied into another row fails to decryptEqual for equal values, so its AAD names the field and never the row, and a value copied into another row decrypts there
MatchThe truncated HMAC, with deliberate collisionsAlways the exact value
KeyA beacon key, rotated separately from the data keysThe field’s own key
CostAn extra column, and a decryption and filter of the candidates on every lookupNothing beyond the field
BigQuerySQL cannot calculate a beacon; it matches beacons the application calculatedSQL decrypts the field and searches it by equality
FIPSHMAC-SHA256 on the configured backendAES-SIV, which is not FIPS-approved

With the default of 16 bits, there are 65,536 possible beacons. A column of 1,000,000 distinct emails gives about 1,000,000 / 65,536, or 15, emails per beacon, so a lookup of one email returns about 15 rows. The application decrypts them and keeps the one equal to the email it looks for. How the bits trade rows to filter against what the column leaks is in Bits.

With kms-aead alone

The application keeps the key itself, as a key id and the key encrypted by the KMS, such as in its settings, and rotates it by hand:

  • a deterministic field: DeterministicCipher with a key the KMS encrypts once, see Deterministic encryption;
  • a beacon: KmsAeadEnvelope::beacon or BeaconMac, see Beacons. A rotation keeps both keys and queries with a beacon under each until a re-index, see Rotating a beacon key.

With a keyring

Each purpose has its own key versions, rotated centrally, and a lookup matches every version that still decrypts:

  • a deterministic field: an encryptor’s encrypt_deterministic on every write, and Keyring::deterministic_probes for a lookup, under the deterministic feature, see Deterministic fields;
  • a beacon: an encryptor’s encrypt and beacon in the same write, and Keyring::beacon_probes for a lookup, see Beacons.

A lookup

  1. Normalise the value in its newtype, such as a lowercased email, so that the write and the lookup encode the same bytes, see Normalisation;
  2. compute the probes of the value looked for, one per key that still decrypts: with kms-aead alone one, or two during a rotation by hand until the re-index; with a keyring one per version;
  3. query by them: WHERE email_beacon = ANY($1) on PostgreSQL with the probes bound as a BYTEA[], an in filter on Firestore, which limits its number of values, see Queries across rotations;
  4. for a beacon, decrypt every row found and keep the ones whose plaintext equals the value: an equal beacon never proves an equal value.

A deterministic field in BigQuery is queried in SQL, with one DETERMINISTIC_ENCRYPT per version, see Query keyring values in BigQuery.

What to watch for

  • Both ways leak which rows hold the same value, see What it leaks and What a beacon leaks. Neither suits a field with few distinct values, such as a status or a country;
  • each rotation of a deterministic or beacon version adds a probe to every lookup until a sweep, see Rotation cadence.

Erase one customer’s data for good

A customer closes its account and asks for its data to be erased, or a retention rule requires it. Deleting its rows leaves the values in backups, exports and every other copy of the store, and those cannot all be found and rewritten. Destroying the keys that decrypt the values makes every copy unreadable at once.

Crypto-shredding

A scope’s values become unreadable once nothing can decrypt their DEKs. With kms-aead alone, the DEKs are encrypted by the KEK, so shredding is the destruction of the KEK’s versions that encrypted them, backups included. Per KMS:

  • Google Cloud KMS: destroy the key versions. Cloud KMS schedules the destruction, and until then a version can be restored, see Google Cloud KMS;
  • AWS KMS: delete the key. Rotated key material is never destroyed on its own, see AWS KMS;
  • Azure Key Vault: delete the key, which deletes it with all its versions: Key Vault never deletes one version alone, see Azure Key Vault. Soft delete and purge protection delay the shredding, see What survives a shred;
  • Vault Transit: min_available_version and a trim of the key delete the versions below it, see Vault Transit, and a deletion of the key, once its configuration sets deletion_allowed, deletes every version;
  • local KMS: destroy every copy of the KEK version, backups included, see Local KMS.

Under a keyring, the KEK encrypts the record’s DEKs and every keyset exported from the keyring, so destroying the KEK’s versions makes the backups of the record and the exported keysets unrecoverable too.

Since a deletion of the key takes every version, shredding one scope under AWS KMS or Azure Key Vault needs a key per scope. With a keyring, a shared KEK has a second route, dangerously_shred(). It destroys every version of the keyring and deletes its record from the store, with the earlier versions the store keeps. The keys stay in every copy the store keeps beyond its API, such as a backup, and in every keyset exported from the keyring, see What survives a shred. A deployment that needs shredding guarantees uses a KEK per scope, see Give each customer of a SaaS its own keys.

Shredding a tenant with dangerously_shred()

Under a shared KEK, KeyringAdmin::dangerously_shred() ends the tenant’s keyring in one call: it destroys every version of the keyring in one write, as dangerously_destroy_all_versions does, then deletes the record from the store with every earlier version of it the store keeps. The keyring encrypts and decrypts nothing from then on, except through a stream encryptor or decryptor already made, see below, and the id is free for a new keyring.

  • the write is signed as every lifecycle write is: an administration without a record signer is refused with RecordSignerMissing over a signed record, and a signing one with RecordUnsigned over an unsigned record, both before any store write;
  • a conflict of the write or of the delete starts again from a new read, up to cas_retries, then RecordConflict;
  • a shred that fails is run again. A record whose every version is destroyed already, as a failure between the write and the delete leaves it, is deleted without a write, and a record already gone returns Ok. The record left between the two steps holds no encrypted DEK, and every process that reads it destroys its versions;
  • KeyringRegistry::admin on a keyring already gone fails with RecordMissing, which an erasure treats as done;
  • a copy of the record from before the shred is refused by a process that took the deletion, with RecordRegressed and an ERROR, because it revives versions the process holds destroyed. A store writer who restores an old record gains nothing against that process;
  • after a deliberate restore, such as one that undoes an accidental deletion, restart every process that took the deletion. A process that starts after the restore takes the record.

Every process that holds the keyring takes the shred as a deleted record, see The keyring record was deleted or corrupted. Its handles fail with NoActiveVersion for a write and KeyVersionDestroyed for a read. How late:

  • with push, within reload_min_interval of the store’s signal;
  • without push, on Cloud Storage and S3 or with watch off, once the cached record is older than record_ttl, at the next call.

The plaintext DEK leaves the process’s memory at that revalidation. A process that makes no call keeps it until the DEK cache drops it: its TTL, with purge_expired on a timer, see DEK eviction. A stream decryptor or encryptor already made keeps the key derived for its value, and goes on decrypting or encrypting with it, until it is dropped. Build a decryptor per request and do not cache it across requests, so that a shred takes effect for new requests, see Streaming encryption.

What to watch for

  • dangerously_shred() never calls the KMS and leaves every KMS key version as it was. Values encrypted under the keyring stay where they are and decrypt under nothing;
  • the store’s backups, its history and every exported keyset stay where they are too, and still decrypt while a KEK version that encrypted their DEKs exists, see What survives a shred.

What survives a shred

Every copy of the record outside the store’s API still holds the encrypted DEKs, which the KMS decrypts as long as a KEK version that encrypted them exists. The operator deletes them or ends the KEK versions:

  • Firestore: serves a deleted document to reads at an earlier time for one hour, and for seven days with point-in-time recovery on, which keeps the versions of every document for that window. Backups and exports hold the record until they are deleted;
  • PostgreSQL: the row’s earlier versions until a vacuum reclaims them, and backups, WAL archives and replicas. The WAL is the write-ahead log, which holds every committed change;
  • Cloud Storage: dangerously_shred() deletes every generation of the object, noncurrent ones included. Soft delete keeps every deleted generation restorable for the bucket’s retention, 7 days by default, so a bucket of keyring records turns soft delete off, or counts the retention into the time a shred takes;
  • S3: dangerously_shred() deletes every version and delete marker of the object. Replication to another bucket and backups hold copies it does not reach;
  • exported keysets: every BigQuery and Tink keyset exported from the keyring holds the keys of the versions it was exported with, under the same KEK, see Keyring limits.

Per store, what dangerously_shred() deletes is in Keyring stores.

So after a shred, either delete the record’s backups and every copy of the keysets exported from the keyring, or destroy every KEK version that encrypted them. On GCP, Vault Transit and the local KMS, rotate the KEK, re-encrypt every other keyring under it as in Re-encrypt DEKs after a KEK rotation, then destroy every previous KEK version, the ones an earlier rotation left disabled included. On AWS rotated key material is never destroyed, so only the deletion of the KMS key itself shreds. Azure Key Vault deletes a key with all its versions and never one version alone, so there too only the deletion of the key shreds. A vault with soft delete keeps a deleted key recoverable until it is purged, and with purge protection on, no purge is possible until the vault’s retention period of 7 to 90 days has passed, see Azure Key Vault soft-delete.

Full example available here.

Share encrypted data with other systems

The reader is not the application that wrote the value: an analyst in BigQuery, a service in another language, or a producer that must never read its own data back.

Pick this whenUse case
BigQuery SQL or a Tink reader in Java or Python needs an encrypted columnDecrypt columns in BigQuery SQL or with Tink
Partners, devices or upload clients encrypt data and must not be able to decrypt itAccept data from partners and devices that cannot read it back

Decrypt columns in BigQuery SQL or with Tink

An analyst needs a column that the application encrypted, in a BigQuery query, or a service in Java or Python needs to read values a Rust service wrote. Values the library writes are in the formats of Tink, Google’s cryptography library, so Tink in another language and BigQuery’s SQL read them, given the keys. Three routes lead there, and they differ in what the reader needs and in whether the key rotates:

Envelope valuesOne fixed keyKeyring
Written byKmsAeadEnvelope::encrypt, per call or store-lessAeadCipher::encrypt or DeterministicCipher::encrypt, with a key the KMS encrypts oncean encryptor’s encrypt or encrypt_deterministic
A value carriesits encrypted DEKa 4-byte key ida 4-byte key id
Tink reads withKmsEnvelopeAead, on a Cloud KMS or AWS KMS keya keyset of the key, as TinkKeyset builds itexport_tink_keyset, on a Cloud KMS key, an AWS KMS key named by its ARN, or a Vault Transit key for Tink for Go
BigQuery reads withnothing: SQL has no KMS envelopeKEYS.KEYSET_CHAIN over the keyset encrypted by a Cloud KMS keyKEYS.KEYSET_CHAIN over export_bigquery_keyset, on a Cloud KMS key
Algorithms BigQuery readsnoneAES-256-GCM and AES-SIVAES-256-GCM and AES-SIV
Rotationthe KEK in the KMSnone: a second key needs a second key id and a keyset of bothcentral, with a new export after each rotation
SeeTink’s KMS envelopeOne fixed keyBigQuery and Tink interop

The AAD

The reader decrypts a value only with the AAD it was encrypted with, so the AAD is one the reader can build:

  • envelope values and one fixed key: the application’s own bytes, which a Tink reader passes as they are, and SQL builds from the row when they are text, see AAD;
  • a keyring: the field’s default AAD, <kind>/<id>/<field> for a randomised field, which SQL rebuilds from the row as UTF-8 text, see AAD in SQL. A custom AAD fails on a field declared for BigQuery.

With a keyring

  1. Declare each field the reader decrypts with FieldSpec::with_interop(Interop::BigQuery) or Interop::Tink: the keyring then refuses to encrypt it under an algorithm or a KEK the reader does not read, see Fields BigQuery reads and Fields Tink reads;

  2. the administrative job exports the keyset, with export_bigquery_keyset under the bigquery-export feature or export_tink_keyset under admin, and writes its bytes where the query or the reader takes them;

  3. the job exports again. A Readable keyset holds every version of a purpose that decrypts and is not compromised, and a Single keyset one version, as its primary key:

    • the Readable keysets after every rotate, before the promotion, and after every retire, every mark_compromised and every KEK rotation;
    • the Single keyset of a new deterministic version after its promotion, since a pending version has none. Until then, an equality lookup in SQL computes no probe under the new version and misses the rows encrypted under it, with no error.

    See Rotation cadence, Retiring the old version and Encrypted keysets.

Full example of a Tink export available here, and of a BigQuery sweep in SQL here.

Query keyring values in BigQuery

Every value reaches the query as a parameter: @kms_key is the export’s key_uri(), each keyset parameter its value(), and @email the address an equality query looks for. The requirements of a query are in Queries:

-- Randomised values, with a Readable(Randomized) keyset
SELECT AEAD.DECRYPT_STRING(
  KEYS.KEYSET_CHAIN(@kms_key, @keyset), u.email_enc, CONCAT('user/', u.id, '/email'))
FROM users u;

-- Deterministic values, with a Readable(Deterministic) or Single keyset
SELECT DETERMINISTIC_DECRYPT_STRING(KEYS.KEYSET_CHAIN(@kms_key, @keyset), u.email_det, 'user/email')
FROM users u;

-- An equality query: one probe per deterministic version, each with its Single keyset
SELECT u.id
FROM users u
WHERE u.email_det IN (
  DETERMINISTIC_ENCRYPT(KEYS.KEYSET_CHAIN(@kms_key, @keyset_d2), @email, 'user/email'),
  DETERMINISTIC_ENCRYPT(KEYS.KEYSET_CHAIN(@kms_key, @keyset_d1), @email, 'user/email')
);

Read a keyring export with Tink for Python

Tink for Python reads the keyset that export_tink_keyset wrote, such as tenant-42.keyset of Exporting a keyset to Tink, with the KMS client of the key URI the export returned, and decrypts a randomised value with the value’s default AAD as UTF-8:

import tink
from tink import aead
from tink.integration import gcpkms

aead.register()
key_uri = 'gcp-kms://projects/my-project/locations/europe-north1/keyRings/my-key-ring/cryptoKeys/my-key'
with open('tenant-42.keyset', 'rb') as keyset_file:
  keyset_handle = tink.read_keyset_handle(
      tink.BinaryKeysetReader(keyset_file.read()),
      gcpkms.GcpKmsClient(key_uri).get_aead(key_uri),
  )
email_aead = keyset_handle.primitive(aead.Aead)


def decrypt_email(value: bytes, user_id: str) -> str:
  return email_aead.decrypt(value, f'user/{user_id}/email'.encode()).decode()

What to watch for

  • An exported keyset holds the keys of the versions it selects, so treat it as a copy of the record’s readable versions, see Keyring limits;
  • BigQuery cannot calculate a beacon: a beacon lookup in BigQuery matches beacons the application calculated, see BigQuery.

Accept data from partners and devices that cannot read it back

A partner posts documents, a device reports readings, an upload client sends files. Each encrypts what it sends and has no way to decrypt it again, whatever its credentials leak. An asymmetric KEK is a KMS key pair: the public half encrypts the DEKs and is not a secret, the private half stays in the KMS and decrypts them for the readers. See Asymmetric KEKs.

The three sides

SideHoldsDoes
Producerthe public key and its fingerprint, in its configurationencrypts values; no KMS client, no KMS right
Readera KMS provider, with decrypt on the keydecrypts values, as for any KEK
Administrationthe public key’s source, read right on the keyhands the public key to the producers
  1. Create an RSA key for asymmetric decryption in the KMS, with the algorithm and the key size of Asymmetric KEKs;
  2. grant the readers the decrypt right and the administration the right to read the public key, see Under an asymmetric KEK;
  3. the administration fetches the public key on its provider, writes to_json() and the key’s fingerprint to the producers’ configuration;
  4. each producer builds a PublicKeyKekProvider from them and an envelope over it.

The producer

The fingerprint comes from a channel other than the one that delivered the key. pinned refuses a key with another fingerprint with ASYMMETRIC_KEK_MISMATCH, so a key taken from a wrong place does not become a key that encrypts for whoever supplied it:

use kms_aead::backends::AwsLc;
use kms_aead::formats::Envelope;
use kms_aead::providers::PublicKeyKekProvider;
use kms_aead::{AsymmetricKekPublicKey, Encrypted, KmsAeadEnvelope, AsymmetricKekFingerprint};
use secret_vault_value::SecretValue;
use kms_aead::providers::{LocalAsymmetricKmsProvider, LocalKekId};
use kms_aead::AsymmetricKekAlgorithm;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let reader_provider = LocalAsymmetricKmsProvider::<AwsLc>::ephemeral(
    LocalKekId::try_from("submissions".to_string())?,
    AsymmetricKekAlgorithm::RsaOaepSha256,
)?;
let public_key = reader_provider.public_key(None)?;
let public_key_json = public_key.to_json()?;
let fingerprint_from_config = public_key.fingerprint().to_string();
let public_key = AsymmetricKekPublicKey::try_from_json(&public_key_json)?;
let fingerprint = AsymmetricKekFingerprint::try_from(fingerprint_from_config)?;
let producer = KmsAeadEnvelope::<_, AwsLc>::new(PublicKeyKekProvider::<AwsLc>::pinned(
    public_key,
    fingerprint,
)?)?;

let encrypted: Encrypted<SecretValue, Envelope> = producer
    .encrypt(b"submissions/1042", &SecretValue::from("account 1234"))
    .await?;

// The reader's side: the provider it already uses
let reader =
    KmsAeadEnvelope::<LocalAsymmetricKmsProvider<AwsLc>, AwsLc>::new(reader_provider)?;
let decrypted: SecretValue = reader.decrypt(b"submissions/1042", &encrypted).await?;
assert_eq!(decrypted, SecretValue::from("account 1234"));
Ok(())
}

Encrypt one test value and decrypt it with a reader before a new producer writes anything that matters. The provider logs the fingerprint at INFO when it is built, which an operator compares with the administration’s.

What the compiler guarantees

PublicKeyKekProvider encrypts and does not decrypt. Every call that decrypts a value or a DEK, decrypt, beacon, the stream decryptors and the *_with_encrypted_dek calls, requires a decrypting provider, so over a producer none of them compiles. A producer streams as well: an envelope over it encrypts a large file with stream_encryptor and decrypts none, see Store customer uploads and serve byte ranges.

The guarantee covers the producer’s calls into the library. A producer process holds the plaintext DEKs of its cached writes, and its own code can read what it wrote in memory. A service that writes and reads holds a KMS provider and is a reader.

With a keyring

The administration opens its registry with an AsymmetricKekProvider, which encrypts each new version’s DEK with the public key, and the applications open theirs with the plain KMS provider. Whoever holds the public key can also encrypt a DEK of their own and file it in a record they can write, and every application then decrypts it. Run every keyring under an asymmetric KEK with signed records, and RecordSignaturePolicy::Required on every application, before the first DEK a public key encrypts, see Protect the keyring record.

What to watch for

  • The producer encrypts randomised values only. A beacon or a deterministic value needs a key’s plaintext, which only a reader holds;
  • Ring has no RSA encryption, so a producer needs AwsLc or RustCrypto, see Crypto backends;
  • the encryption is local, so the KMS audit log does not show who encrypted a DEK. The decrypt log stays;
  • anyone holding the public key makes a reader pay for an asymmetric KMS decryption by sending a made-up value. Rate-limit what readers decrypt;
  • a rotation of the KEK is a new public key for every producer;
  • RSA is not quantum-safe, so data that must stay confidential for decades stays under a symmetric KEK.

Full example available here.

Files and streams

The data is too large to hold in memory. It is encrypted in chunks, as it is written or sent, and read in chunks.

Pick this whenUse case
Uploads of any size are stored encrypted, and readers need byte ranges of themStore customer uploads and serve byte ranges
A handler sends a large export over HTTP, and the body has to leave the server encryptedSend a large export over HTTP, encrypted

Store customer uploads and serve byte ranges

Customers upload videos and archives of any size, and the object store must not hold them in plaintext. Uploads are encrypted as they arrive, with one chunk of 16 KiB in memory, and a reader fetches only the chunks that cover the bytes it needs: one entry of a zip archive, or the range a video player asks for. The object store holds the encrypted object and serves Range requests as it does for any object. Feature stream, see Streaming encryption.

Keyring or envelope

KeyringEnvelope
Keythe keyring’s active version, named by a 4-byte key id in the object’s headera DEK of the object’s own, or a reused one under a DekReusePolicy
Stored beside the objectthe encryption marker, see The encryption markerthe encrypted DEK, in the object’s metadata or in the row that names the object
KMS callsone decryption per key version per DEK cache TTLone encryption per new DEK, one decryption per object per DEK cache TTL
Rotationthe keyring’sthe KEK’s, by re-encrypting the stored DEKs

Both give the same StreamEncryptor and StreamDecryptor. There is no size cap: the encryptor does not need the length in advance.

Upload

An EncryptingWriter wraps the sink that writes the object. Copy the request body into it and call shutdown, which writes the final chunk; a writer dropped before its shutdown leaves an object that no reader decrypts whole. The object’s AAD names where it belongs, such as upload/<id>/file. A handler that holds the body as a Stream of Bytes uses an EncryptingStream instead, see Encrypting and decrypting.

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    EntityId, EntityKind, FieldName, FieldSpec, KeyringAlgorithms, KeyringId, KeyringRegistry,
    KeyringRegistryOptions,
};
use kms_aead_keyring::stream::EncryptingWriter;
use tokio::io::AsyncWriteExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("uploads".to_string())?)?;
let admin = registry
    .open_or_create(provider, KeyringId::from_static("tenant-42"), KeyringAlgorithms::new())
    .await?;
let keyring = admin.keyring();
let mut body = &vec![7_u8; 1_200_000][..];
let mut sink = Vec::new();

const UPLOAD_FILE: FieldSpec = FieldSpec::new(
    EntityKind::from_static("upload"),
    FieldName::from_static("file"),
);
let aad = UPLOAD_FILE.aad(&EntityId::try_from("upload-7")?);

let encryptor = keyring.encryptor().await.stream_encryptor(&aad).await?;
let mut writer = EncryptingWriter::new(encryptor, &mut sink);
tokio::io::copy(&mut body, &mut writer).await?;
writer.shutdown().await?;
let stored_len = writer.stored_len_written();
assert_eq!(sink.len() as u64, stored_len);
registry.shutdown(None).await;
Ok(())
}

Serve byte ranges

A reader plans each range from the size the object store reports, and fetches and decrypts only the chunks the plan names. This example uses StreamFormat::Prefixed, whose header starts with the key id of the version that encrypted the object, as every keyring object does. The envelope example below uses StreamFormat::Bare, which has no key reference, since the encrypted DEK is stored beside the object.

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    EntityId, EntityKind, FieldName, FieldSpec, KeyringAlgorithms, KeyringId, KeyringRegistry,
    KeyringRegistryOptions,
};
use kms_aead_keyring::stream::EncryptingWriter;
use kms_aead_keyring::stream::{ChunkReadPlan, PrefixedStreamHeader, StreamFormat};
use tokio::io::AsyncWriteExt;
/// An object store that serves `Range` requests, held in memory.
struct Store(Vec<u8>);
impl Store {
    fn get(&self, range: std::ops::Range<u64>) -> &[u8] {
        &self.0[range.start as usize..range.end as usize]
    }
    fn size(&self) -> u64 {
        self.0.len() as u64
    }
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("uploads".to_string())?)?;
let admin = registry
    .open_or_create(provider, KeyringId::from_static("tenant-42"), KeyringAlgorithms::new())
    .await?;
let keyring = admin.keyring();
let mut body = &vec![7_u8; 1_200_000][..];
let mut sink = Vec::new();
const UPLOAD_FILE: FieldSpec = FieldSpec::new(
    EntityKind::from_static("upload"),
    FieldName::from_static("file"),
);
let aad = UPLOAD_FILE.aad(&EntityId::try_from("upload-7")?);
let encryptor = keyring.encryptor().await.stream_encryptor(&aad).await?;
let mut writer = EncryptingWriter::new(encryptor, &mut sink);
tokio::io::copy(&mut body, &mut writer).await?;
writer.shutdown().await?;
let stored_len = writer.stored_len_written();
let store = Store(sink);
assert_eq!(store.size(), stored_len);

// Plan from the size the store reports first, so that a length the rules refuse reaches neither
// the store nor the KMS. One zip entry, or the range of a video request
let last: ChunkReadPlan = StreamFormat::Prefixed.plan_final_chunk_read(store.size())?;
let plan = StreamFormat::Prefixed.plan_chunk_read(store.size(), 1_000_000..1_064_512)?;

// The header once per request, then the decryptor
let header = PrefixedStreamHeader::try_from(store.get(0..StreamFormat::Prefixed.header_len() as u64))?;
let decryptor = keyring.stream_decryptor(&aad, &header).await?;

// The final chunk authenticates the length the store reports before any range is served
decryptor.decrypt_chunk_read::<Vec<u8>>(&last, store.get(last.ciphertext()))?;
let entry: Vec<u8> = decryptor.decrypt_chunk_read(&plan, store.get(plan.ciphertext()))?;
assert_eq!(entry.len(), 64_512);
registry.shutdown(None).await;
Ok(())
}

A download that serves the whole object takes it from its first byte to its last with decrypting_stream or decrypting_reader of the keyring or the envelope, and needs no stored length, see Encrypting and decrypting.

The DEK beside the object

An envelope takes the place of the keyring. stream_encryptor_bare returns the encrypted DEK with the encryptor, and stream_decryptor_bare takes it back; the application stores it beside the object and hands it to the reader. The rest is as above:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::stream::{EncryptingWriter, StreamFormat};
use kms_aead::KmsAeadEnvelope;
use tokio::io::AsyncWriteExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("uploads".to_string())?)?;
let mut body = &vec![7_u8; 1_200_000][..];
let mut object = Vec::new();
let envelope = KmsAeadEnvelope::<_, Ring>::new(provider)?;
let aad = b"upload/7/file";

let (encryptor, encrypted_dek) = envelope.stream_encryptor_bare(aad).await?;
let mut writer = EncryptingWriter::new(encryptor, &mut object);
tokio::io::copy(&mut body, &mut writer).await?;
writer.shutdown().await?;
let stored_len = writer.stored_len_written();

let header = &object[..StreamFormat::Bare.header_len()];
let decryptor = envelope.stream_decryptor_bare(aad, header, &encrypted_dek).await?;
let last = StreamFormat::Bare.plan_final_chunk_read(stored_len)?;
assert_eq!(last.plaintext().end, 1_200_000);
Ok(())
}

The envelope’s stream_encryptor, without the _bare suffix, writes the encrypted DEK inside the object instead, so that nothing is stored beside it, and decrypting_stream or decrypting_reader reads the whole object back, see Streaming encryption. A store-less envelope, one with a DekReusePolicy, encrypts many objects under one DEK in either form.

What to watch for

  • The stored length a range is planned with is the object store’s word until the final chunk has been decrypted. A store that cuts an object inside a chunk and reports the shorter size passes every range that stays clear of the cut. Read the final chunk through plan_final_chunk_read once per object before the first range. A zip reader that counts from the end of the archive needs it first;
  • make one decryptor per request, in an Arc: its methods take &self. Do not cache it across requests: a decryptor, like an encryptor, keeps decrypting after a shred, a destroy or a compromised flag of its version until it is dropped, see Streaming encryption;
  • a response written chunk by chunk goes to a place you can discard, since a chunk is yielded as soon as it is authentic, see Streaming encryption;
  • the object carries no signature. A party without the DEK that must check it gets a Signature<T> over a document that lists the object’s SHA-256 digest, see Publish a rate sheet or a release anyone can verify.

The other limits, such as STREAM_IO and the sweep of a streamed object, are in Streaming encryption.

Full examples available here for a keyring, here for reading a range from an envelope, and here for a request body as a Stream.

Send a large export over HTTP, encrypted

A handler streams a large export, one record at a time, and the body leaves the server encrypted. The client decrypts it as it arrives and decodes the records one by one. Neither side holds the export in memory, and the encrypted DEK travels inside the body. Feature stream, see Streaming encryption.

The encryption sits on the bytes of the body, between the format and the socket:

  • the server turns its items into bytes with a streaming format, such as JSON lines (one JSON document per line) of axum-streams, and passes the bytes through an EncryptingStream, which yields the header and then one encrypted chunk at a time;
  • the client passes the bytes of the response to decrypting_stream of the envelope, and hands the plaintext to the decoder of reqwest-streams;
  • the format knows nothing about encryption, and the envelope knows nothing about items. The body is one Cobblestone stream in the envelope form, the chunked encryption format of the C2SP specification, see Format, so the KMS is called as for any streamed value: one encryption per new DEK, one decryption per response per DEK cache TTL, see DEK caching and reuse.

The server

The handler takes the body of the StreamBodyAs response, the encoded bytes, and sends it with an opaque content type, since the body is ciphertext. The format is part of the endpoint’s contract, so the response does not name it. The AAD names the export, so that a body of another export does not decrypt under it:

use std::sync::Arc;

use axum::body::Body;
use axum::extract::State;
use axum::http::header::CONTENT_TYPE;
use axum::http::{HeaderValue, StatusCode};
use axum::response::IntoResponse;
use axum_streams::StreamBodyAs;
use futures::stream;
use kms_aead::stream::EncryptingStream;
use kms_aead::backends::Ring;
use kms_aead::providers::LocalKmsProvider;
use kms_aead::KmsAeadEnvelope;
use serde::Serialize;

type Envelope = KmsAeadEnvelope<LocalKmsProvider<Ring>, Ring>;
#[derive(Serialize)]
struct Order {
    id: u64,
}

const EXPORT_AAD: &[u8] = b"exports/orders/2026-10";

async fn export_orders(
    State(envelope): State<Arc<Envelope>>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let orders = stream::iter((0..50_000).map(|id| Order { id }));
    let encoded = StreamBodyAs::json_nl(orders).into_response().into_body();

    let encryptor = envelope
        .stream_encryptor(EXPORT_AAD)
        .await
        .map_err(|error| (StatusCode::INTERNAL_SERVER_ERROR, error.code().to_string()))?;
    let ciphertext = EncryptingStream::new(encryptor, encoded.into_data_stream());

    Ok((
        [(CONTENT_TYPE, HeaderValue::from_static("application/octet-stream"))],
        Body::from_stream(ciphertext),
    ))
}

The route is get(export_orders), with the envelope in an Arc as the router’s state. EncryptingStream takes its source as a Stream of Result<Bytes, _> whose error converts into a boxed error, and Body::from_stream takes the encrypted chunks the same way, so no error is mapped by hand. An error in the items ends the body with an error, never with a clean end.

The client

reqwest-streams decodes a reqwest::Response, so the decrypted bytes are wrapped in one. The decoder reads the body only, in the format the client asks for. The source of decrypting_stream is Unpin, so the byte stream of the response goes through Box::pin. The decoder takes the longest record it accepts, which bounds what a server can make the client buffer:

use axum::http::Response;
use futures::TryStreamExt;
use kms_aead::backends::Ring;
use kms_aead::providers::LocalKmsProvider;
use kms_aead::KmsAeadEnvelope;
use reqwest_streams::JsonStreamResponse;
use serde::Deserialize;

#[derive(Deserialize)]
struct Order {
    amount_cents: u64,
}
const EXPORT_AAD: &[u8] = b"exports/orders/2026-10";
const MAX_ORDER_LEN: usize = 64 * 1024;

async fn download_orders(
    envelope: &KmsAeadEnvelope<LocalKmsProvider<Ring>, Ring>,
    url: &str,
) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
    let response = reqwest::get(url).await?.error_for_status()?;

    let plaintext = envelope
        .decrypting_stream(EXPORT_AAD, Box::pin(response.bytes_stream()))
        .await?
        .map_err(std::io::Error::other);
    let decrypted = Response::new(reqwest::Body::wrap_stream(plaintext));

    let mut orders = reqwest::Response::from(decrypted).json_nl_stream::<Order>(MAX_ORDER_LEN);
    let mut total_cents = 0;
    while let Some(order) = orders.try_next().await? {
        total_cents += order.amount_cents;
    }
    Ok(total_cents)
}

The example runs both sides in one process, on a loopback port, with the local KMS and no credentials. It decodes 50,000 orders from a body of about 3.8 MB and compares each one with the order that was sent. Run it with cargo run --example axum_encrypted_stream --features stream,ring.

What to watch for

  • Cobblestone releases a chunk only when 16 KiB of plaintext has gathered or the stream ends, and EncryptingStream has no flush. This fits exports, reports and bulk downloads. A feed that sends a small record every few seconds delivers nothing until 16 KiB of records have gathered, so server-sent events and notifications do not fit;
  • the client’s decoder receives records in groups of one chunk, and only once the chunk is authentic. A body that is cut, modified or extended ends in an error item, STREAM_LENGTH or DECRYPT, after the records of the earlier chunks were already decoded. The retry is the whole download again, so write what the client decodes to a place it can discard;
  • the status and the headers are sent before the first record. A failure while the items stream ends the body with an error and cannot change the status;
  • the content type convention belongs to the two sides. The name of the header is not a standard, and the client should check its value against the formats it decodes;
  • ciphertext does not compress, so a compression layer on the route gains nothing;
  • the AAD must be the same on both sides. A value that names the export, the tenant or the user keeps a body from decrypting under another route, see AAD.

Full example available here.

Prove where data came from

The bytes stay readable, and the reader checks who produced them and that nobody changed them on the way. A signature answers it for anyone with a public key, and a MAC (a keyed hash) answers it between services that share a key.

Pick this whenUse case
A file, an export or a release is published, and anyone has to be able to verify itPublish a rate sheet or a release anyone can verify
Your own services pass jobs, cache entries or rows to each other, and the reader checks that nobody changed themDetect tampering with jobs and rows between your services

Publish a rate sheet or a release anyone can verify

A rate sheet, a data export or a release goes out with a signature, and whoever downloads it checks that it came from the publisher and was not changed on the way, with no KMS and no secret. The private key stays in a KMS. Verifiers need the public key, which the publisher serves as a JWK Set, a JSON document that lists public keys. See Signatures and MACs.

Sign a document

A bank publishes its exchange rates as a JSON document. The type that holds the document implements SignableType, which names its payload type, and is signed as JsonEncoded::new(rates), which stands for the compact JSON of the value. The payload type is signed with the bytes, so a signature over the rates never verifies as another kind of document. If anything serialises the JSON again, canonicalise it before it is signed: write it in one fixed form, so that every serialiser produces the same bytes. To publish large files, sign one document that lists their SHA-256 digests instead of each file, and compare the digest of each downloaded file with its entry once the document verifies.

The signing key is a KMS key version that signs, such as a Cloud KMS EC_SIGN_P256_SHA256 version. Every signing provider is built from a key reference that names one version, see “Signing” on the page of Google Cloud KMS, AWS KMS, Azure Key Vault and Vault Transit:

use std::collections::BTreeMap;
use std::num::NonZeroU32;

use kms_aead::backends::Ring;
use kms_aead::providers::{GcpKmsSigningKeyRef, GcpKmsSigningProvider};
use kms_aead::signing::{Signer, SigningAlgorithm, VerifyingKeySet};
use kms_aead::{JsonEncoded, KmsAeadResult, SignedPayloadType, SignableType};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct ExchangeRates {
    base: String,
    date: String,
    rates: BTreeMap<String, f64>,
}

impl SignableType for ExchangeRates {
    const PAYLOAD_TYPE: SignedPayloadType =
        SignedPayloadType::from_static("application/vnd.example.exchange-rates+json");
}

#[tokio::main]
async fn main() -> KmsAeadResult<()> {
let key_ref = GcpKmsSigningKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "rates".to_string(),
    "rates-signing".to_string(),
    NonZeroU32::MIN,
    SigningAlgorithm::EcdsaP256Sha256,
);
let signer = Signer::<_, Ring>::new(GcpKmsSigningProvider::new(&key_ref).await?).await?;

// Once per key: the JWK Set to serve at a stable URL, such as /.well-known/rate-keys.json
let jwks: String = VerifyingKeySet::new([signer.verifying_key().clone()])?.to_jwks()?;

// Per publication: the signature to publish beside the document
let rates = JsonEncoded::new(ExchangeRates {
    base: "EUR".to_string(),
    date: "2026-10-26".to_string(),
    rates: BTreeMap::from([("GBP".to_string(), 0.8412), ("USD".to_string(), 1.0873)]),
});
let signature: Vec<u8> = signer.sign(&rates).await?.into_value();
let _ = (jwks, signature);
Ok(())
}

Verify in Rust

A verifier is built from the JWK Set alone and needs no KMS client, so it runs in a CLI, a CI job or another service on any crypto backend:

use kms_aead::backends::Ring;
use kms_aead::signing::{Signature, Verifier, VerifyingKeySet};
use kms_aead::{JsonEncoded, KmsAeadResult, SignedPayloadType, SignableType};
use std::collections::BTreeMap;
use kms_aead::providers::{LocalSigningKeyName, LocalSigningProvider};
use kms_aead::signing::{Signer, SigningAlgorithm};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct ExchangeRates {
    base: String,
    date: String,
    rates: BTreeMap<String, f64>,
}
impl SignableType for ExchangeRates {
    const PAYLOAD_TYPE: SignedPayloadType =
        SignedPayloadType::from_static("application/vnd.example.exchange-rates+json");
}
#[tokio::main]
async fn main() -> KmsAeadResult<()> {
let provider = LocalSigningProvider::<Ring>::ephemeral(
    LocalSigningKeyName::try_from("rates".to_string())?,
    SigningAlgorithm::EcdsaP256Sha256,
)?;
let signer = Signer::<_, Ring>::new(provider).await?;
let downloaded_jwks = VerifyingKeySet::new([signer.verifying_key().clone()])?.to_jwks()?;
let rates = JsonEncoded::new(ExchangeRates {
    base: "EUR".to_string(),
    date: "2026-10-26".to_string(),
    rates: BTreeMap::from([("GBP".to_string(), 0.8412), ("USD".to_string(), 1.0873)]),
});
let downloaded_signature = signer.sign(&rates).await?.into_value();
let verifier = Verifier::<Ring>::new(VerifyingKeySet::from_jwks(&downloaded_jwks)?)?;
let signature = Signature::<JsonEncoded<ExchangeRates>>::try_from(downloaded_signature)?;
verifier.verify(&rates, &signature)?;
Ok(())
}

A verification that fails returns SIGNATURE_INVALID, and a signature with a key id the set lacks SIGNING_KEY_UNKNOWN.

Verify in the browser

A page or a service worker verifies the same signature with WebCrypto: import the keys of the JWK Set, hash the payload and call verify. The code is in In a browser, with the browsers that support Ed25519 and P-256, and the test vectors that run against it in CI. Use P-256 where every engine must verify.

Rotate signing keys

A signing key rotates by publishing before signing:

  1. create the new key version in the KMS;
  2. add its public key to the served JWK Set beside the current one;
  3. switch the signers to the new version once verifiers have fetched the set;
  4. keep the old key in the set for as long as its signatures are verified.

A signature carries the id of its key, the first four bytes of the key’s JWK thumbprint, so verifiers pick the key with no coordination. Removing a key from the set revokes every signature under it, which is the response to a compromised key. See Key ids and rotation.

What to watch for

  • The JWK Set is the trust root. Serve it over HTTPS from a domain the publisher controls, and let a verifier that needs more pin it in its own configuration. The library does not sign the set;
  • a signature has no expiry and the set has no revocation list. Put a version or a date in the document, such as the date of the rates, so that a verifier can refuse an old document that is still validly signed;
  • ECDSA signatures are malleable, which means a third party can turn a valid signature into another valid one for the same document: never use signature bytes as an identifier;
  • the signature does not hide the document, see Store customer uploads and serve byte ranges for the content.

Full example available here.

Detect tampering with jobs and rows between your services

One service puts a job on a queue, an entry in a cache or a row in a table, and another reads it. The reader needs to know that nobody who can write the queue, the cache or the table changed the bytes. A MAC, a keyed hash, answers that with a key only the application’s services hold, and costs an HMAC in process. The MAC does not hide the bytes, see Envelope encryption for that. See Signatures and MACs.

Keyring MACs

A keyring holds MAC key versions beside its other versions, encrypted by the KEK and rotated, flagged and retired as the others are. Create the keyring with a MAC algorithm, see MACs in a keyring. A service that writes calls mac_attached on its Encryptor, and a service that reads calls verify_with_mac. The type that is authenticated implements SignableType, whose payload type separates one kind of message from another: a MAC over a job never verifies as a cache entry. The calls take it as JsonEncoded::new(job), which stands for the compact JSON of the value.

use kms_aead_keyring::{JsonEncoded, SignableType, SignedPayloadType, WithMac};
use serde::{Deserialize, Serialize};
use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions, MacAlgorithm,
};

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Job {
    task: String,
    image_id: u64,
}

impl SignableType for Job {
    const PAYLOAD_TYPE: SignedPayloadType = SignedPayloadType::from_static("example.com/jobs/v1");
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("jobs".to_string())?)?;
let admin = registry
    .open_or_create(
        provider,
        KeyringId::from_static("backend"),
        KeyringAlgorithms::new().with_mac(MacAlgorithm::HmacSha256),
    )
    .await?;
let keyring = admin.keyring();
// The service that enqueues: the payload and its tag in one value
let message: Vec<u8> = keyring
    .encryptor()
    .await
    .mac_attached(&JsonEncoded::new(Job { task: "resize".to_string(), image_id: 7 }))
    .await?
    .into_value();

// The service that works: the tag is checked before the payload is decoded
let with_mac = WithMac::<JsonEncoded<Job>>::try_from(message)?;
let job = keyring.verify_with_mac(&with_mac).await?.0;
assert_eq!(job, Job { task: "resize".to_string(), image_id: 7 });
registry.shutdown(None).await;
Ok(())
}

A value whose bytes changed fails with MAC_INVALID. Where the payload already has a place of its own, such as the columns of a row, Encryptor::mac computes a detached Mac<T> to store beside it, and Keyring::verify_mac checks it against the payload as read.

Both services build a Keyring for the same keyring id, with decrypt on the keyring’s KEK and read access to its record, see Permissions: applications and administration. Every service that holds the key can compute a valid tag, so a MAC protects the bytes from whoever writes the store, and says nothing about which service wrote them.

Rotation

A MAC version rotates and retires like the others, see Rotate keys and re-encrypt values. A sweep re-encrypts Encrypted fields and does not touch MACs, and a value under a retired version fails with KEY_VERSION_RETIRED. Authenticate the payloads that still matter again under the active version before retiring the old one. Messages that are consumed within minutes, such as a queue’s, need no such pass: wait for them to drain.

A signature instead

Use a signature when the party that checks should not be able to forge, or is not one of your services:

MACSignature
Who can checkholders of the keyring’s key: your servicesanyone with the public key: a partner, a browser, an offline tool
Who can forgeevery checkerthe holder of the private key only
Costan HMAC in processone KMS call to sign, none to verify

A webhook your customers verify, a release, and a record whose writer must be told apart from its readers are signatures. See Publish a rate sheet or a release anyone can verify, and Protect the keyring record for the keyring’s own record.

What to watch for

  • Nothing outside the payload type and the payload is authenticated. A message that must not be replayed carries a timestamp or a nonce, and a message for one recipient names it;
  • a process on a version that predates MACs refuses a record that holds a MAC version, so upgrade every process that reads the keyring before it gets its first MAC version, see Readers before producers.

Full example available here.

Keep sensitive data out of logs

A log line that explains a failure often needs the data that failed, and the data is the thing a log must not keep. This use case needs no KMS and no keys.

Pick this whenUse case
A payload that fails to parse has to be logged, and it holds emails, phone numbers or amountsLog a webhook payload that failed to parse

Log a webhook payload that failed to parse

A webhook handler or a queue consumer receives JSON from outside, and some of it does not parse: a sender cut the body short, a proxy answered with an HTML page, a field changed its type. The log line that explains the failure needs the payload, and the payload holds emails, phone numbers and amounts that a log must not keep. RedactedJson writes an outline of the bytes instead: the shape of the JSON, with every value hidden unless the application opts into showing it. It does no encryption and needs no KMS, so it works for any bytes and any logger. It needs no Cargo feature.

Outline instead of the payload

RedactedJson::new::<P>(bytes) takes the bytes and a policy P, a type that says what the outline shows. ShapeOnly shows nothing but the shape. Display and Debug both write the outline and never the bytes, so the value goes to format!, to tracing as a field, to log or to a logger of the application’s own.

use kms_aead::redaction::{RedactedJson, ShapeOnly};

fn reject(body: &[u8]) {
    if let Err(error) = serde_json::from_slice::<serde_json::Value>(body) {
        eprintln!(
            "WARN webhook payload rejected ({:?}): {}",
            error.classify(),
            RedactedJson::new::<ShapeOnly>(body)
        );
    }
}
let body = br#"{"event":"order.paid","customer":{"email":"ann@example.com"},"paid":true,"total_cents":117"#;
reject(body);
assert_eq!(
    RedactedJson::new::<ShapeOnly>(body).to_string(),
    "{<key>: <string>, <key>: {<key>: <string>}, <key>: <bool>, <key>: <number>, <error: EOF while parsing an object>"
);

A body that stops inside total_cents logs this line:

WARN webhook payload rejected (Eof): {<key>: <string>, <key>: {<key>: <string>}, <key>: <bool>, <key>: <number>, <error: EOF while parsing an object>

The log shows the type of every value, <key> for every key, the nesting, and where serde_json stopped reading. error.classify() gives the category of the failure, Eof, Syntax, Data or Io.

Choose what the outline shows

A policy is a type of the application’s own that implements JsonRedaction and sets the constants it needs, each of them off by default: FIELD_NAMES shows the keys, SIZES the lengths, and REVEALED_FIELDS the values of the fields it lists, such as items[].sku for the sku of every item of items. Every constant and the grammar of a path are in Redaction policies.

use kms_aead::redaction::{FieldPaths, JsonRedaction, RedactedJson};

struct WebhookLog;

impl JsonRedaction for WebhookLog {
    const FIELD_NAMES: bool = true;
    const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["event", "items[].sku"]);
}
let body = br#"{"event":"order.paid","customer":{"email":"ann@example.com"},"items":[{"sku":"desk","qty":2},{"sku":"lamp","qty":1}],"total_cents":117"#;
let outline = RedactedJson::new::<WebhookLog>(body);
assert_eq!(
    outline.to_string(),
    r#"{"event": "order.paid", "customer": {"email": <string>}, "items": [{"sku": "desk", "qty": <number>}, {"sku": "lamp", "qty": <number>}], "total_cents": <number>, <error: EOF while parsing an object>"#
);

The outline of the same kind of body:

{"event": "order.paid", "customer": {"email": <string>}, "items": [{"sku": "desk", "qty": <number>}, {"sku": "lamp", "qty": <number>}], "total_cents": <number>, <error: EOF while parsing an object>

Input that is not JSON

Broken, truncated and non-JSON input is outlined as far as it goes, and the outline never panics. An HTML error page from a proxy and a base64 string print as their class only, and a syntax error in the middle ends the outline there, with serde_json’s fixed message:

not JSON: text
not JSON: base64-like text
{"event": "order.paid", "a": <error: expected value>

What to watch for

  • Log the category from error.classify(), and not the message of serde_json::Error, which for a value of the wrong type can quote the input;
  • revealed values go to the log whenever the JSON fails to parse. Reveal codes and identifiers, never personal data;
  • SIZES has a cost: a length gives away a hidden boolean, since true and false differ in length, and it narrows a short string down. Leave it off for any payload where that matters;
  • an outline is bounded in length and depth, see the limits in Redaction policies.

JsonEncoded<T, P> applies the same policies to the JSON that fails to decode after an encrypted value is opened, see JSON that does not decode. The event it logs is in Spans and events.

Permissions: applications and administration

Without a keyring, the principals that write values and the ones that only read them differ in their KMS rights, see With kms-aead alone. A keyring adds an administration side that builds with another feature, calls another handle and writes the keyring store, and the sections below give each side its checklist and its rights.

Two sides of a keyring

A keyring has two sides, each with its own handle and its own rights:

  • the application decrypts and runs sweeps on a Keyring, which KeyringRegistry::open returns in every build, and encrypts, computes beacons and re-encrypts on the Encryptor the Keyring hands out for each write;
  • the administration creates keyrings, rotates, promotes, retires and destroys versions, flags compromised ones, re-encrypts DEKs, exports keysets and shreds keyrings, on a KeyringAdmin, which KeyringRegistry::create, open_or_create and admin return with the admin feature.

The application builds without the admin feature and runs under a principal with the rights of its row only:

SideHandleKMSKeyring store
ApplicationKeyringdecryptread, and listen or watch
AdministrationKeyringAdminencrypt and decrypt, or under an asymmetric KEK decrypt and read of the public keyread, write and delete

Sweeps run on the application’s side: re-encrypting a value encrypts it under a DEK the record already holds, and never asks the KMS to encrypt a DEK. Every call that encrypts a DEK, writes or deletes the record is a KeyringAdmin call. The exact roles per KMS are in KMS rights, and the permissions per store in Store rights.

The admin feature keeps the administrative calls out of the application’s build, and the rights keep them out of its reach: without the KMS encrypt right and write access to the store, those calls fail in any build.

An application opens only keyrings that exist: open on a keyring the store holds no record of fails with KeyringError::RecordMissing. So the administration creates each keyring before an application opens it:

  • from infrastructure: a job, a CLI or a deployment step, built with the admin feature and run with the administrative rights, calls create or open_or_create;
  • or from an application that provisions lazily, such as one keyring per tenant on the tenant’s first request. Such an application enables admin and is given the administrative rights deliberately, and is then trusted as the administration is, see Keyring limits and Creating the keyrings.

An application’s own tests that create keyrings in MemoryKeyringStore enable admin for the tests only:

[dependencies]
kms-aead-keyring = { version = "0.34", features = ["ring", "firestore-tls-roots"] }

[dev-dependencies]
kms-aead-keyring = { version = "0.34", features = ["ring", "firestore-tls-roots", "admin"] }

The application

  • builds without the admin feature, with cargo build -p <application>: Cargo unifies the features of the packages one command builds, so a cargo build of a workspace with both the application and an administrative job gives the application admin too;
  • calls KeyringRegistry::open, and on the Keyring it returns encryptor, decrypt, the beacons and the probes, and runs the sweeps. None of its calls asks the KMS to encrypt;
  • runs as a principal with KMS decrypt on the KEK and read access to the keyring store, listen included, see KMS rights and Store rights;
  • where records are signed, opens its registry with RecordSignaturePolicy::Required and the public key of the record signer, from its configuration and never from the store, see Protect the keyring record;
  • awaits registry.shutdown(None) before it exits.

The administration

  • builds with the admin feature, and bigquery-export where it exports BigQuery keysets;
  • calls the registry’s create or open_or_create for each new keyring, and admin, and on the KeyringAdmin they return the lifecycle calls (rotate, promote, change_algorithm, mark_compromised, retire, reinstate, destroy and dangerously_destroy_all_versions), dangerously_shred, reencrypt_deks and the keyset exports export_bigquery_keyset and export_tink_keyset, see Key versions and lifecycle;
  • runs in a job or in infrastructure automation, never in a request handler, as the only principal with KMS encrypt and decrypt on the KEK, or under an asymmetric KEK decrypt and the read of the public key and no encrypt right, and with write access to the keyring store;
  • holds the record signer where records are signed: a Signer on a KMS signing key, with the right to sign and no other principal holding it, passed to create_signed, open_or_create_signed or with_record_signer, see Protect the keyring record;
  • logs every call it makes, since a version its log does not show is the start of A version the administrative job did not create;
  • opens its registry with the longest record_ttl in the fleet, which the promotion guard waits.

KMS rights

A keyring record is signed only where the administration holds a record signer, see Signing the keyring record and Keyring deployment, so a deployment splits the two sides above into two principals.

With kms-aead alone

An envelope that writes needs KMS encrypt on the KEK: one encryption per value with a per-call envelope, and one per renewed DEK with store-less DEK reuse. An envelope that reads needs KMS decrypt, on every DEK cache miss. A principal that does both needs both, and so does a re-encryption of stored DEKs, see Re-encrypt DEKs after a KEK rotation. The local KMS has no rights to grant.

KMSWriter: encryptReader: decrypt
GCPcloudkms.cryptoKeyVersions.useToEncryptcloudkms.cryptoKeyVersions.useToDecrypt, as in roles/cloudkms.cryptoKeyDecrypter
AWSkms:Encrypt on the keykms:Decrypt on the key
Azure Key Vaultkeys/wrap/action on the keykeys/unwrap/action on the key
Vault Transitupdate on <mount>/encrypt/<key>update on <mount>/decrypt/<key>

roles/cloudkms.cryptoKeyEncrypterDecrypter carries both GCP permissions. With the KMS random generator on, the writer also needs cloudkms.locations.generateRandomBytes on the location under GCP, and kms:GenerateRandom under AWS. See the page of each provider in KMS providers.

With a keyring

The rights of the two sides, per KMS:

KMSApplicationAdministration
GCProles/cloudkms.cryptoKeyDecrypterroles/cloudkms.cryptoKeyEncrypterDecrypter
AWSkms:Decrypt on the keykms:Encrypt and kms:Decrypt on the key, plus kms:GenerateRandom with the KMS random generator
Azure Key Vaulta role with keys/unwrap/action on the keya role with keys/wrap/action and keys/unwrap/action on the key
Vault Transitupdate on transit/decrypt/<key>update on transit/encrypt/<key> and transit/decrypt/<key>

Under an asymmetric KEK

Under an asymmetric KEK the public key encrypts new DEKs in the administration’s own process, so no side has the KMS encrypt right: Cloud KMS useToEncrypt, AWS kms:Encrypt, Key Vault keys/wrap/action and Transit transit/encrypt leave the administration’s grant. The administration needs the read of the public key beside the applications’ decrypt:

KMSApplicationAdministration
GCPcloudkms.cryptoKeyVersions.useToDecrypt, as in roles/cloudkms.cryptoKeyDecrypterdecrypt, and cloudkms.cryptoKeyVersions.viewPublicKey, as in roles/cloudkms.publicKeyViewer
AWSkms:Decrypt on the keykms:Decrypt and kms:GetPublicKey on the key
Azure Key Vaultkeys/unwrap/actionkeys/unwrap/action and keys/get
Vault Transitupdate on transit/decrypt/<key>update on transit/decrypt/<key>, and read on transit/keys/<key> or transit/export/public-key/<key>

Two built-in roles fall short of what the administration needs:

  • roles/cloudkms.cryptoKeyDecrypter does not carry viewPublicKey;
  • Azure’s “Key Vault Crypto Service Encryption User” carries read, wrap and unwrap and no decrypt.

The KMS audit log does not show who encrypted a DEK, since the encryption is local, and anyone holding the public key can encrypt one: a keyring under an asymmetric KEK runs with RecordSignaturePolicy::Required on every application, see Keyrings under an asymmetric KEK. The public_key call of each provider is in KMS providers.

The permissions of each store are below.

Store rights

The store’s access control is what the record’s integrity rests on, unless the record is signed: only the administration writes the record, and the applications read it and listen to its changes, see above:

StoreApplicationAdministration
Firestoreread of the keyring documents, which the listener uses too, such as roles/datastore.viewerread, write and delete of the keyring documents, such as roles/datastore.user
PostgreSQLSELECT on the table, and LISTEN, which needs no grantSELECT, INSERT, UPDATE and DELETE on the table; each write and delete also sends the NOTIFY
Cloud Storagestorage.objects.getstorage.objects.get, storage.objects.create and storage.objects.delete, since a write replaces the object
S3s3:GetObjects3:GetObject and s3:PutObject

dangerously_shred() needs more of the administration on the object stores:

StoreAlso needed
Cloud Storagestorage.objects.list, to find the object’s generations
S3s3:ListBucketVersions, s3:DeleteObject and s3:DeleteObjectVersion

What to alert on

Each side logs events an operator acts on, such as a refused record, a failed revalidation or a re-encryption that failed, and records metrics with the opentelemetry feature. The list, with the next step for each, is in Monitoring and alerts.

Monitoring and alerts

The catalogue of what to alert on in production, then the alerts for the volume of values under a key version and for the two rotations.

What to alert on

The events are logged through tracing, see Keyring events and Events, and the metrics need the opentelemetry feature, see Metrics.

The keyring record

SignalWhat it meansNext step
ERROR: a refreshed record refused because it moves a version backwardssomething other than the administrative job rewrote or restored the recordA version the administrative job did not create
ERROR: a refreshed record refused by record verification, with RECORD_UNSIGNED, RECORD_SIGNATURE_INVALID or RECORD_SIGNATURE_REMOVEDsomething other than the record signer wrote or restored the record; the process keeps the record it holdsA version the administrative job did not create, and the signer’s KMS audit log
WARN: “The keyring record could not be revalidated; the cached record stays in use”the process misses every change, a promotion or a compromised flag included, until the store answersfix the process’s access to the store before the next promotion
WARN: “The keyring store no longer holds the keyring record; every version is destroyed in this process”the record was deleted or shredded, and this process destroyed every version in memoryThe keyring record was deleted or corrupted
WARN: the store’s listener disconnected or did not start, or a keyring opened with no tokio runtimechanges reach the process within record_ttl instead of secondscheck the listener’s connection and the runtime

After the WARN about a deleted record, the process’s handles fail with NoActiveVersion and KeyVersionDestroyed, and new opens fail with RecordMissing until a record is created. A process that read the shred’s first write logs an INFO instead.

Versions and sweeps

SignalWhat it meansNext step
WARN: a compromised flag written without a rotationthe KMS could not encrypt a new DEK, so encrypt fails with NoActiveVersionrotate and promote_now once the KMS answers, see Compromised versions
WARN: a read of a compromised version under the Allow policyvalues under a leaked DEK are being readthe sweep of A plaintext DEK leaked
WARN: a read refused because its version is retired or destroyeda value the sweep missedreinstate a retired version, and sweep again
WARN: a record a sweep could not re-encrypt, or SweepReport::failed above zeroa record left under an old versionthe cause in the event’s error, see Running a sweep

The process and the KMS

SignalWhat it meansNext step
WARN: a KeyringRegistry dropped with its tasks running, or a shutdown that aborted themthe process exits without shutdownawait registry.shutdown(None) before the exit
WARN, inside the KMS span: a Cloud KMS or Vault Transit response without a key versionthe KMS reported no version, so kek_versions_in_use lists a None and the check before a KEK disable never passesA KEK version the KMS did not report

Metrics

SignalWhat it meansNext step
error.type on kms_aead.operation.durationcalls that fail, by code, such as DECRYPT for a value that is not authentic under its key and AAD, or KEY_VERSION_UNKNOWNthe code, see Error handling
error.type on kms_aead.kms.durationKMS requests that fail: a denied permission, a disabled key version, a quotaRetries for the codes of each KMS
error.type on kms_aead.store.durationkeyring store reads that failthe store’s own monitoring
values and bytes per keyring versiona version near the limits of its algorithmAlerting on volume

The KMS audit log

SignalWhat it meansNext step
an Encrypt by a principal other than the administrationan IAM over-grant, or a version the job did not createA KMS IAM over-grant
a Decrypt by a principal other than the application, the administration and the keyset readersan IAM over-grant, or an encrypted DEK or a keyset decrypted outside the deploymentA KMS IAM over-grant

Cloud KMS logs Encrypt and Decrypt as DATA_READ in its Data Access audit logs, which are off by default and must be turned on, see Cloud KMS audit logging and Enable Data Access audit logs. Every KEYS.KEYSET_CHAIN query decrypts its keyset as the principal that runs it, and so does a Tink reader through its own KMS client, see Queries and Exporting a keyset to Tink.

Without a keyring, the rows of kms-aead apply: error.type on kms_aead.operation.duration and kms_aead.kms.duration, the KMS audit log, and the WARN of old layouts.

Alerting on volume

With the opentelemetry feature, the keyring records the plaintext size of each value it encrypts under each version, see Metrics: the histogram’s count is the values, and its sum their bytes. Each process records its own, and the alert sums them across the fleet. Here at half of the bounds of a version, 2^32 values (Nonces) and 2^38 bytes (Data volume), in PromQL over the Prometheus export, with the range covering the version’s life:

sum by (kms_aead_keyring, kms_aead_key_id) (
  increase(kms_aead_plaintext_size_bytes_count{
    kms_aead_mode="keyring", kms_aead_operation="encrypt", kms_aead_purpose="randomized"
  }[90d])
) > 0.5 * 2^32

sum by (kms_aead_keyring, kms_aead_key_id) (
  increase(kms_aead_plaintext_size_bytes_sum{
    kms_aead_mode="keyring", kms_aead_operation="encrypt",
    kms_aead_algorithm=~"aes-(128|256)-gcm"
  }[90d])
) > 0.5 * 2^38

A histogram starts at zero in every new process, and increase() counts across those restarts. The [90d] range needs 90 days of retention: Prometheus keeps 15 days by default, so keep the metric in long-term storage, through remote write or in a backend with a longer retention. The bytes alert keeps to AES-GCM versions, the only ones with a volume bound. Rotate the version the alert names, as in Rotation cadence.

During a DEK rotation

  • “The keyring record could not be revalidated”, from the rotation until the old version is retired: a process that logs it is one a promotion can leave behind, and one that can still encrypt under the old version;
  • error.type KEY_VERSION_UNKNOWN on kms_aead.operation.duration, a read that met a version its process could not load, and KEY_VERSION_RETIRED once the old version is retired;
  • SweepReport::failed above zero, and the sweep’s WARN per record;
  • the values and bytes per version, which say when the next rotation is due, see Alerting on volume.

The metrics need the opentelemetry feature, see Metrics.

During a KEK rotation

  • “The keyring record could not be revalidated”, from the re-encryption until the disable: a process that logs it keeps the old encrypted DEKs, and its reads fail after the disable once its DEK cache entries expire;
  • error.type on kms_aead.kms.duration with kms_aead.operation decrypt_dek, after the disable: a DEK the re-encryption missed, or a process that still holds old bytes;
  • the rate of kms_aead.kms.duration with decrypt_dek, and ResourceExhausted or ThrottlingException in its error.type, during the burst;
  • an error_code on the Keyring re-encrypt DEKs span of the administrative job.

Rotate keys and re-encrypt values

Two keys rotate, on their own schedules:

  • a DEK encrypts values. A new DEK changes nothing already written, so the values under the old one are re-encrypted by a sweep before the old DEK is retired;
  • the KEK encrypts DEKs in the KMS. A new KEK version changes no value: the DEKs are encrypted again under it before the old version is disabled.

Both run without downtime, since the old key keeps decrypting until one of the last steps retires or disables it, and a check runs before that step. This page walks through each rotation and links to the procedure of each step. How often to rotate is in Rotation cadence.

DEK rotation

On a keyring, a DEK rotation is a new key version of a purpose, staged before it encrypts anything. The administrative job runs every call on its KeyringAdmin, and the application runs the sweep, see Permissions: applications and administration. In order:

  1. stage and promote the new version: rotate, export the keysets again, wait until every process has the pending version, promote. The steps and the waits are in Rotation cadence, and why the wait is needed in Staged rotation;
  2. sweep the records whose encryption marker is below the keyring’s current one. They are the records that can hold a value under an older version, and records with no value of the rotated purpose, whose re-encryption writes the marker alone, see Sweeps. A sweep is a job that runs on a schedule until its SweepReport shows nothing scanned. The query and the write per database:
  3. retire, then destroy the old version, once every process has refreshed since the promotion and no record is left under it, see Retiring the old version.

Rotation cadence

A rotation is staged: rotate(purpose) adds a pending version, which every process decrypts under once its record refreshes, and promote(key_id) makes it active once every process has had time to see it, see Staged rotation. The previous version keeps decrypting. Nothing is lost while the change propagates: processes on the old record encrypt under the previous version until their record refreshes, and those values decrypt.

The administrative job runs a rotation in steps, on its KeyringAdmin, see Permissions: applications and administration:

  1. rotate(purpose);
  2. export the Readable BigQuery and Tink keysets again, which then hold the pending version;
  3. wait the longest time any process may run without a successful refresh of its record, counted from staged_at(), and check that no process logged “The keyring record could not be revalidated” meanwhile;
  4. promote(key_id). Until record_ttl has passed since staged_at() it fails with PromotionTooEarly, whose remaining is the time left. promote_now(key_id) skips that guard, for a fleet known to have refreshed since the rotation or a compromise that cannot wait.

The rotate example runs the whole cycle, and a KEK re-encryption after it, on the memory store and the local KMS: cargo run -p kms-aead-keyring --example rotate --features ring,admin.

How often:

  • a randomised version is good for about 2^32 values, see Nonces, and an AES-GCM version for about 2^38 bytes, see Data volume. The keyring stops at neither, since its DEKs are shared across processes: estimate the values and bytes a fleet encrypts, or measure them, see Alerting on volume. At 550 values per second a version reaches 2^32 in 90 days, so rotate every 30 to 90 days, sooner at higher rates;
  • a deterministic version has no nonce, so it is rotated by policy and on compromise only. Every deterministic rotation adds a probe to each equality query until a full sweep re-encrypts every row, see Queries across rotations, so rotate deterministic versions rarely;
  • a beacon version likewise, since every beacon rotation adds a probe to each lookup until a re-index, see Rotating beacon versions.

After a promotion, export the Single BigQuery keysets of the new deterministic version, since a pending version has none.

Why nothing stops

  • A pending version decrypts in every process that has seen it and encrypts nothing, so by the promotion every process that reads a value under it already knows it;
  • a process that has not taken the promotion yet encrypts under the previous version, which stays DecryptOnly, so its values decrypt everywhere;
  • the sweep reads a value under the old version and writes it under the new one, conditional on the record as it read it, so a write of the application in between is never overwritten;
  • retire is the first step that refuses a read, and reinstate undoes it.

What can go wrong

What to alert on

The alerts of a DEK rotation are in During a DEK rotation.

KEK rotation

A KEK rotation is a new version of the key in the KMS. In order:

  1. rotate the KEK in the KMS, as its provider page describes under “Key versions and rotation”: Google Cloud KMS, AWS KMS, Azure Key Vault, Vault Transit or the local KMS;
  2. re-encrypt, check, disable, check again and destroy, as in Re-encrypt DEKs after a KEK rotation. A keyring’s part, reencrypt_deks and kek_versions_in_use, is in Re-encrypting a keyring’s DEKs, with a sample.

Why nothing stops

No value changes, and the old KEK version decrypts every DEK until it is disabled. The disable waits until no process holds an encrypted DEK from before the re-encryption, so by then every process reads through DEKs under the new version. A DEK the re-encryption missed fails in the application from the disable on, once its DEK cache entry expires, and the check after the disable finds it. Enabling the old version again restores every DEK under it, at once under Cloud KMS, see Google Cloud KMS.

Re-encrypting a keyring’s DEKs

The KEK rotates in the KMS on its own schedule. After a rotation, reencrypt_deks() decrypts every DEK in the record and encrypts it again under the KEK’s current version. No value changes. A keyring that is not re-encrypted keeps working as long as the old KEK versions stay enabled in the KMS.

reencrypt_deks is a KeyringAdmin call and runs in the administrative job, like every call that encrypts a DEK.

The record keeps the KEK version of each encrypted DEK, as the KMS reported it when it encrypted the DEK: KeyVersion::kek_version. reencrypt_deks returns one DekReencryption per version, with the KEK version its DEK was under before and the one it is under after the call, and kek_versions_in_use of the record lists every KEK version the record’s DEKs are under. Before the old KEK version is disabled, the record that Keyring::reload returns must list the new version alone, which needs no KMS call. Once the old version is disabled, reencrypt_deks runs again: it decrypts every DEK through the KMS and fails on one the KMS does not decrypt. Here with the local KMS, rotated from version 1 to version 2, where dropping version 1 from the provider stands for disabling it:

use std::num::NonZeroU32;

use kms_aead::backends::Ring;
use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{
    KmsKeyVersion, LocalKek, LocalKekId, LocalKekVersion, LocalKmsProvider,
};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    DekReencryption, KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions,
};
use secret_vault_value::SecretValue;

const TENANT: KeyringId = KeyringId::from_static("tenant-42");

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let kek_id = LocalKekId::try_from("tenant-kek".to_string())?;
let [v1, v2] = [1, 2].map(|version| LocalKekVersion::from(NonZeroU32::new(version).unwrap()));
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let before_rotation = LocalKmsProvider::<Ring>::new(
    kek_id.clone(),
    vec![LocalKek::from_secret(v1, SecretValue::new(vec![0x01; 32]), SymmetricKeyFormat::Raw)?],
)?;
registry
    .create(before_rotation, TENANT, KeyringAlgorithms::new())
    .await?;

// The administrative job after the rotation, with the new version encrypting
let rotated = LocalKmsProvider::<Ring>::new(
    kek_id.clone(),
    vec![
        LocalKek::from_secret(v1, SecretValue::new(vec![0x01; 32]), SymmetricKeyFormat::Raw)?,
        LocalKek::from_secret(v2, SecretValue::new(vec![0x02; 32]), SymmetricKeyFormat::Raw)?,
    ],
)?;
let admin = registry.admin(rotated, TENANT).await?;

// One entry per version: the KEK version its DEK was under before the call, and the one it is under after it
let moved: Vec<DekReencryption> = admin.reencrypt_deks().await?;
let new_kek_version = KmsKeyVersion::from(v2);
assert!(moved
    .iter()
    .all(|reencryption| reencryption.kek_version.as_ref() == Some(&new_kek_version)));

// The check before the old version is disabled: every DEK is under the new version
let record = admin.keyring().reload().await?;
assert_eq!(record.kek_versions_in_use(), [Some(&new_kek_version)]);

// The check once the old version is disabled: every DEK still decrypts
let disabled = LocalKmsProvider::<Ring>::new(
    kek_id,
    vec![LocalKek::from_secret(v2, SecretValue::new(vec![0x02; 32]), SymmetricKeyFormat::Raw)?],
)?;
registry.admin(disabled, TENANT).await?.reencrypt_deks().await?;
Ok(())
}

Under Cloud KMS, a reencrypt_deks that ran before the new primary version had propagated reports the old version as the one the DEK is under after the call, and the record keeps listing it: run reencrypt_deks again once the rotation has propagated. Under Vault Transit, min_decryption_version disables every version below it at once, which is why the check asks for the new version alone.

The whole procedure, with the application’s own DEKs and keysets, is in Re-encrypt DEKs after a KEK rotation.

A KEK version the KMS did not report

A None among the versions in use stands for the DEKs whose KMS reported no version: every DEK under AWS KMS, and under a KMS with versions, a version that is unknown, as with an application’s own provider that returns none. A Cloud KMS or Vault Transit response without a key version is logged at WARN, see Events. reencrypt_deks keeps such a DEK at None, so the check before the disable never passes. The procedure in Re-encrypt DEKs after a KEK rotation then goes from step 2 to step 4, and the check after the disable, step 6, is the only one.

Between the disable and that check, a DEK still under the old version fails in the application too, once its DEK cache entry has expired. Under AWS KMS only imported key material can be removed, see AWS KMS.

The KMS decrypt burst

reencrypt_deks gives every DEK new encrypted bytes, and the DEK cache keys its entries by those bytes. Each process that takes the refreshed record evicts the old entries, so its next call under each version decrypts that version’s DEK through the KMS again: one KMS decryption per process, per keyring and per version in use, within the bound of How late a change is seen after each reencrypt_deks. With a keyring per tenant, re-encrypt the keyrings in batches below the KMS’s request quota, with room for that burst, see Pacing. A sweep or an application over the quota fails with the KMS’s error, such as ResourceExhausted on Google Cloud KMS or ThrottlingException on AWS KMS, both a NetworkError.

What can go wrong

  • An early re-encryption or check under Cloud KMS, inside the propagation of the new primary version or of the disable, see Google Cloud KMS;
  • a pinned Azure version re-encrypts under the old version, see Azure Key Vault;
  • an early disable fails the reads of a process that still holds the old encrypted DEKs, see The check;
  • Vault Transit’s min_decryption_version disables every version below it at once, see Re-encrypting a keyring’s DEKs;
  • AWS KMS key material cannot be disabled when generated, and leaves the key unusable when imported material is deleted or expires, see AWS KMS;
  • a destroyed old version makes every backup taken before the re-encryption unreadable.

What to alert on

The alerts of a KEK rotation are in During a KEK rotation.

With kms-aead alone

DEKs

Without a keyring there is no version to stage, and the DEK rotates with the mode:

  • per-call envelope: every value has a DEK of its own, so there is no DEK to rotate;
  • store-less DEK reuse: the envelope renews its DEK by age, count and bytes, as its DekReusePolicy sets, and the values keep their encrypted DEK, so the renewal is the rotation and needs no sweep, see Store-less DEK reuse;
  • one fixed key, a deterministic key or a beacon key the application keeps: a second key under a second key id, both kept for reads, and a re-index of the values or beacons under the old one, see One fixed key and Rotating a beacon key.

A DEK that leaked keeps decrypting every value encrypted under it, whatever the KEK, so it is retired by the steps of A DEK of envelope values leaked, not by a routine rotation.

The KEK

The KEK rotates in the KMS, and before the old version is disabled, the DEKs stored in the values and apart from them are encrypted again under its new version with reencrypt_encrypted_dek, once per distinct encrypted DEK, and the application’s own encrypted keysets through the provider. No value is decrypted. The procedure, when the sweep starts, its pacing, the checks and a rollback are in Re-encrypt DEKs after a KEK rotation, and the alerts are those of During a KEK rotation, on kms_aead.kms.duration.

Re-encrypt DEKs after a KEK rotation

A KEK rotation makes the KMS encrypt new DEKs under a new key version, and every DEK stored before it keeps decrypting with the old version only. reencrypt_encrypted_dek and reencrypt_dek move a stored DEK to the current version, so the old version can be retired while the application keeps reading and writing:

  1. rotate the KEK in the KMS, as the page of each provider describes. Under Cloud KMS, wait until the new primary version has propagated, see Google Cloud KMS. Then wait until every store-less writer has renewed its DEK. Until then a writer keeps encrypting under its current DEK, encrypted under the old version, so the sweep of step 2 misses the values it writes, the check of step 3 does not see them, and they first fail at the check of step 6, after the disable. A writer renews its DEK when its DekReusePolicy says so, and at the latest when the DEK leaves its cache, at the cache’s DekCacheOptions::ttl, see The DEK lives in the cache;
  2. re-encrypt every stored DEK: the DEKs of the stored values, the DEKs stored apart from their values, and the record of each keyring under the KEK with KeyringAdmin::reencrypt_deks. Then export the keyrings’ keysets again and re-encrypt the application’s own encrypted keysets, see Encrypted keysets, and replace the old keyset bytes wherever they are kept, see Exporting a keyset to BigQuery;
  3. check that the kek_versions_in_use of every keyring record lists the new version alone, and so does the KEK version an application stores beside its own DEKs. A None never passes this check, see A KEK version the KMS did not report;
  4. wait until no process holds an encrypted DEK from before step 2: the longest record_ttl in the fleet after the last reencrypt_deks, with no process logging “The keyring record could not be revalidated” meanwhile, and every process has read its DEKs stored apart from their values again, see The check;
  5. disable the old version, and wait until the disable has propagated in the KMS, which takes a window under Cloud KMS, see Google Cloud KMS;
  6. check that the KMS decrypts every stored DEK, every keyring’s DEKs with reencrypt_deks, and every encrypted keyset, see The check. A DEK or a keyset it refuses is one the sweep missed: enable the old version again, sweep again, and go back to step 3;
  7. keep the old version disabled for as long as the backups of the stored values and of the keyring records are kept. Immediately before destroying it, run the check of step 6 again, and destroy it only when it passes.

A backup taken before the sweep holds the DEKs under the old version, so destroying the old version makes every such backup unreadable for good. Keyring records are the same, see Compromised versions. What a rotation, a disabled version and a destroyed version are differs per KMS, see the page of each provider.

The sweep

reencrypt_encrypted_dek makes two KMS calls: the KMS decrypts the DEK with the version that encrypted it and encrypts it again with its current one. The AEAD bytes of a value stay as they are, so the sweep takes no AAD, decrypts nothing, and the value decrypts as before. Each distinct encrypted DEK is re-encrypted once and joined with each of its values, so the values a store-less envelope wrote under one DEK still share one afterwards:

use std::collections::HashMap;

use kms_aead::backends::AeadBackend;
use kms_aead::formats::Envelope;
use kms_aead::{
    Encrypted, EncryptedDataEncryptionKey, KmsAeadDecryptionProvider, KmsAeadEnvelope,
    KmsAeadResult,
};
use secret_vault_value::SecretValue;

/// The bytes to write back for each stored value in `rows`, beside the bytes read, with its DEK
/// under the KEK's current version. Each distinct encrypted DEK is re-encrypted once.
async fn reencrypt_values<P, B>(
    envelope: &KmsAeadEnvelope<P, B>,
    rows: &[Vec<u8>],
) -> KmsAeadResult<Vec<(Vec<u8>, Vec<u8>)>>
where
    P: KmsAeadDecryptionProvider,
    B: AeadBackend,
{
    let mut reencrypted: HashMap<EncryptedDataEncryptionKey, EncryptedDataEncryptionKey> =
        HashMap::new();
    let mut updates = Vec::with_capacity(rows.len());
    for row in rows {
        let stored = Encrypted::<SecretValue, Envelope>::try_from(row.clone())?;
        let (bare, encrypted_dek) = stored.separate()?;
        let new_encrypted_dek = match reencrypted.get(&encrypted_dek) {
            Some(new_encrypted_dek) => new_encrypted_dek.clone(),
            None => {
                let new_encrypted_dek = envelope.reencrypt_encrypted_dek(&encrypted_dek).await?;
                reencrypted.insert(encrypted_dek, new_encrypted_dek.clone());
                new_encrypted_dek
            }
        };
        updates.push((row.clone(), Encrypted::join(&bare, &new_encrypted_dek)?.into_value()));
    }
    Ok(updates)
}
use std::num::NonZeroU32;
use kms_aead::backends::Ring;
use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{LocalKek, LocalKekId, LocalKekVersion, LocalKmsProvider};
use kms_aead::{DekReusePolicy, KmsAeadEnvelopeOptions};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let kek_id = LocalKekId::try_from("orders".to_string())?;
let [v1, v2] = [1, 2].map(|version| LocalKekVersion::from(NonZeroU32::new(version).unwrap()));
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::with_options(
    LocalKmsProvider::new(
        kek_id.clone(),
        vec![LocalKek::from_secret(v1, SecretValue::new(vec![0x01; 32]), SymmetricKeyFormat::Raw)?],
    )?,
    KmsAeadEnvelopeOptions::new().with_dek_reuse(DekReusePolicy::new()),
)?;
let mut rows = Vec::new();
for card in ["4111 1111 1111 1111", "5500 0000 0000 0004"] {
    rows.push(envelope.encrypt(b"orders/1042", &SecretValue::from(card)).await?.into_value());
}
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(LocalKmsProvider::new(
    kek_id.clone(),
    vec![
        LocalKek::from_secret(v1, SecretValue::new(vec![0x01; 32]), SymmetricKeyFormat::Raw)?,
        LocalKek::from_secret(v2, SecretValue::new(vec![0x02; 32]), SymmetricKeyFormat::Raw)?,
    ],
)?)?;
for (read, new) in reencrypt_values(&envelope, &rows).await? {
    if let Some(row) = rows.iter_mut().find(|row| **row == read) {
        *row = new;
    }
}
let encrypted_deks = rows
    .iter()
    .map(|row| Ok(Encrypted::<SecretValue, Envelope>::try_from(row.clone())?.separate()?.1))
    .collect::<KmsAeadResult<Vec<EncryptedDataEncryptionKey>>>()?;
assert_eq!(encrypted_deks[0], encrypted_deks[1]);
let disabled = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(LocalKmsProvider::new(
    kek_id,
    vec![LocalKek::from_secret(v2, SecretValue::new(vec![0x02; 32]), SymmetricKeyFormat::Raw)?],
)?)?;
for row in &rows {
    let stored = Encrypted::<SecretValue, Envelope>::try_from(row.clone())?;
    disabled.decrypt(b"orders/1042", &stored).await?;
}
Ok(())
}

Write each value back only where the stored bytes are still the ones read, with a compare-and-set (a write that applies only if the stored value is unchanged), such as UPDATE orders SET card = $new WHERE id = $id AND card = $read, or the store’s own conditional write. An unconditional write puts back the value the sweep read over one the application wrote in the meantime, which is then lost. A row the application rewrote keeps its new value, and the checks of steps 3 and 6 find it if its DEK is still under the old version.

reencrypt_dek does the same for one value. It gives each value an encrypted DEK of its own, so values that shared a DEK would then cost one KMS encryption each in the sweep and one KMS decryption each on a cache miss afterwards. The same reencrypt_encrypted_dek re-encrypts the DEKs stored apart from their values, such as those of the *_with_encrypted_dek calls, of beacons and of deterministic fields. A value or a DEK in a legacy layout fails with LEGACY_FORMAT, see Values written by 0.29 and earlier.

The DEK cache plays no part: the sweep decrypts through the provider and leaves the cache as it is, so it evicts no entry that serves reads. Every call encrypts again, also for a DEK already under the current version. The sweep needs KMS encrypt and decrypt on the KEK.

The kek_version() of the encrypted DEK that reencrypt_encrypted_dek returns names the KEK version the KMS encrypted it with. Under Cloud KMS, a sweep that ran before the new primary version had propagated shows the old version there, and the DEKs it names are re-encrypted again.

Encrypted keysets

An encrypted keyset is a KMS ciphertext as well, under the KEK version that encrypted it, and reencrypt_encrypted_dek refuses one with INVALID_KEY_FORMAT, since what the KMS decrypts from it is a serialised keyset. A sweep of the DEKs leaves every keyset under the old version, so a query or a reader that decrypts one fails once the old version is disabled:

  • a keyring’s export_bigquery_keyset and export_tink_keyset: export each keyset again, with the same selection, after reencrypt_deks and, under Cloud KMS, after the new primary version has propagated. The new export holds the same keys, encrypted under the KEK’s current version. Write its bytes wherever the old ones are kept: the query parameter of each KEYS.KEYSET_CHAIN, a column or a setting that holds the keyset, and the file or the setting a Tink reader decrypts. See BigQuery;
  • the application’s own encrypted keyset, such as first_level_keyset in One fixed key: the provider decrypts it and encrypts it again, and the new bytes replace the old ones wherever they are kept:
use kms_aead::{EncryptedDataEncryptionKey, KmsAeadDecryptionProvider, KmsAeadResult};

/// `first_level_keyset` encrypted again under the KEK version the provider encrypts with.
async fn reencrypt_keyset<P: KmsAeadDecryptionProvider>(
    provider: &P,
    first_level_keyset: &EncryptedDataEncryptionKey,
) -> KmsAeadResult<EncryptedDataEncryptionKey> {
    let keyset = provider.decrypt_data_encryption_key(first_level_keyset).await?;
    provider.encrypt_data_encryption_key(&keyset).await
}
use std::num::NonZeroU32;
use kms_aead::backends::Ring;
use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{LocalKek, LocalKekId, LocalKekVersion, LocalKmsProvider};
use kms_aead::{DataEncryptionKey, KmsAeadEncryptionProvider};
use secret_vault_value::SecretValue;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let kek_id = LocalKekId::try_from("orders".to_string())?;
let [v1, v2] = [1, 2].map(|version| LocalKekVersion::from(NonZeroU32::new(version).unwrap()));
let keyset = DataEncryptionKey::from(SecretValue::new(vec![0x0a; 16]));
let first_level_keyset = LocalKmsProvider::<Ring>::new(
    kek_id.clone(),
    vec![LocalKek::from_secret(v1, SecretValue::new(vec![0x01; 32]), SymmetricKeyFormat::Raw)?],
)?
.encrypt_data_encryption_key(&keyset)
.await?;
let rotated = LocalKmsProvider::<Ring>::new(
    kek_id.clone(),
    vec![
        LocalKek::from_secret(v1, SecretValue::new(vec![0x01; 32]), SymmetricKeyFormat::Raw)?,
        LocalKek::from_secret(v2, SecretValue::new(vec![0x02; 32]), SymmetricKeyFormat::Raw)?,
    ],
)?;
let reencrypted = reencrypt_keyset(&rotated, &first_level_keyset).await?;
let disabled = LocalKmsProvider::<Ring>::new(
    kek_id,
    vec![LocalKek::from_secret(v2, SecretValue::new(vec![0x02; 32]), SymmetricKeyFormat::Raw)?],
)?;
assert_eq!(disabled.decrypt_data_encryption_key(&reencrypted).await?, keyset);
Ok(())
}

The check decrypts the bytes of a BigQuery keyset and of the application’s own keyset through the provider, as it does an encrypted DEK, with EncryptedDataEncryptionKey::from of the bytes. A Tink keyset is a google.crypto.tink.EncryptedKeyset around the KMS ciphertext, and its check is a decryption with the Tink reader that uses it.

Pacing

The sweep makes two KMS calls per distinct encrypted DEK, and the check one, on top of the calls the application makes. Under a KMS with a request quota, as the cloud KMSs have, pace the sweep below it: a fixed number of DEKs per second, or a pause after each batch, with room left for the application. A sweep over the quota fails with the KMS’s error, such as ResourceExhausted on GCP, and so do the application’s own calls meanwhile.

The check

Once the old version is disabled, the KMS refuses every DEK still under it, so the check decrypts each distinct encrypted DEK through the provider, never through the DEK cache, which would serve a missed DEK from memory. It needs no AAD and decrypts no value, and it runs online, under every provider. Any error counts as a missed DEK:

use std::collections::HashSet;

use kms_aead::backends::AeadBackend;
use kms_aead::formats::Envelope;
use kms_aead::{
    Encrypted, EncryptedDataEncryptionKey, KmsAeadDecryptionProvider, KmsAeadEnvelope,
    KmsAeadResult,
};
use secret_vault_value::SecretValue;

/// The distinct encrypted DEKs of the values in `rows` that the provider fails to decrypt.
async fn missed_deks<P, B>(
    envelope: &KmsAeadEnvelope<P, B>,
    rows: &[Vec<u8>],
) -> KmsAeadResult<Vec<EncryptedDataEncryptionKey>>
where
    P: KmsAeadDecryptionProvider,
    B: AeadBackend,
{
    let mut encrypted_deks: HashSet<EncryptedDataEncryptionKey> = HashSet::new();
    for row in rows {
        let stored = Encrypted::<SecretValue, Envelope>::try_from(row.clone())?;
        let (_, encrypted_dek) = stored.separate()?;
        encrypted_deks.insert(encrypted_dek);
    }
    let mut missed = Vec::new();
    for encrypted_dek in encrypted_deks {
        if envelope
            .provider()
            .decrypt_data_encryption_key(&encrypted_dek)
            .await
            .is_err()
        {
            missed.push(encrypted_dek);
        }
    }
    Ok(missed)
}
use std::num::NonZeroU32;
use kms_aead::backends::Ring;
use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{LocalKek, LocalKekId, LocalKekVersion, LocalKmsProvider};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let kek_id = LocalKekId::try_from("orders".to_string())?;
let [v1, v2] = [1, 2].map(|version| LocalKekVersion::from(NonZeroU32::new(version).unwrap()));
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(LocalKmsProvider::new(
    kek_id.clone(),
    vec![LocalKek::from_secret(v1, SecretValue::new(vec![0x01; 32]), SymmetricKeyFormat::Raw)?],
)?)?;
let stored = envelope.encrypt(b"orders/1042", &SecretValue::from("4111 1111 1111 1111")).await?;
let rows = vec![stored.into_value()];
let disabled = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(LocalKmsProvider::new(
    kek_id,
    vec![LocalKek::from_secret(v2, SecretValue::new(vec![0x02; 32]), SymmetricKeyFormat::Raw)?],
)?)?;
assert_eq!(missed_deks(&disabled, &rows).await?.len(), 1);
Ok(())
}

A keyring’s record names the KEK version of each of its DEKs, as the KMS reported it, so a first check makes no KMS call and runs before the old version is disabled: kek_versions_in_use of the record that Keyring::reload returns must list the new version alone. Under Cloud KMS, a reencrypt_deks that ran before the new primary version had propagated leaves the old version listed. A None there is a version the KMS did not report, so the first check fails on it. Once the old version is disabled, KeyringAdmin::reencrypt_deks runs again: it decrypts every DEK in the record through the provider, and fails on one still under the old version. See Re-encrypting a keyring’s DEKs. An application that stores the kek_version of its own DEKs beside them checks those the same way.

Under the local KMS the check needs no disable. A provider that lists the new version alone, as the sample above builds it, refuses every DEK under the old version, so the check runs before the deploy that drops the old version from the list, and a missed DEK costs no outage and no redeploy.

Besides the store-less writers that step 1 of Re-encrypt DEKs after a KEK rotation waits for, two things keep using the old version after a rotation, and each sets when to disable it:

  • every DEK cache serves the DEKs it holds, without a KMS call, until their entries expire. A value the sweep missed fails to decrypt in the application only once its entry has expired, see DEK caching and reuse. The check does not wait for that, since it never reads a cache;
  • a process keeps the encrypted DEKs it read before the sweep. A keyring’s cached record holds the ones it had before reencrypt_deks until it is refreshed, at a change signal of the store or once it is older than record_ttl, and Cloud Storage and S3 send no signal, see Record cache. A process whose revalidations fail keeps its record for as long as they fail, and logs “The keyring record could not be revalidated; the cached record stays in use” at WARN on each failure. An encrypted DEK the application read from its settings at startup, as in One fixed key, stays as it was read. The DEK cache keys its entries by those bytes, so once an entry expires, the KMS decrypts the old bytes again and fails under a disabled old version, with no reload. This is the wait of step 4 in Re-encrypt DEKs after a KEK rotation.

A KMS whose changes take time to propagate, such as Cloud KMS, can keep encrypting under the old version for a while after the rotation and keep decrypting under it for a while after it is disabled. Wait before the sweep and again before trusting the check, see the page of each provider.

Rolling back a rotation

A swept value’s DEK is under the new version only, so a rollback keeps the new version enabled: disabling it makes every swept value and every value written since the rotation unreadable, until it is enabled again. Where the provider makes the old version encrypt again, rolling back to it needs no new sweep. To retire the new version afterwards, run the procedure above with the old version as the current one.

The rule per provider:

Sweeps

A sweep re-encrypts stored values under the active versions: after a rotation, to retire the old version, after a compromise, and to migrate envelope values. It is a job the application runs, a CLI or a Kubernetes Job, never a task inside the library: only the application knows its tables, its queries and its write rules. The job runs on a schedule, and again until its SweepReport shows nothing scanned. A run that stops part-way or fails on some records needs no checkpoint: the next run’s marker query returns exactly the records it did not write. Retiring the old version is a separate step of the administrative job, see Retiring the old version.

This page covers the mechanism every store shares: the encryption marker, the queries for the records behind and under a version, re-encrypting a value, running the job, retiring the old version and the trust of re-encrypted values. Read it before the page of your store, which holds that store’s schema, queries and example; the rotation procedure that calls a sweep is Rotate keys and re-encrypt values.

The encryption marker

A keyring record counts a re-encryption epoch, which moves on by one with every administrative write that makes a version active:

CallRe-encryption epoch
create, and open_or_create when it creates1
promotemoves on by one
mark_compromised of the active version, with its replacementmoves on by one
mark_compromised that writes the flag alone, or of any other versionunchanged
rotate, change_algorithmunchanged: the version they add is pending
retire, reinstate, destroy, reencrypt_deks, dangerously_destroy_all_versionsunchanged

A write moves the epoch once, however many versions it makes active. KeyringRecord::encryption_marker() returns it as an EncryptionMarker, which holds the epoch.

Markers compare as their epochs do, and so do their bytes, in Firestore, PostgreSQL and BigQuery alike, see Encryption markers for the bytes. EncryptionMarker::ENVELOPE is epoch 0, the marker of a record of envelope values, below the marker of every keyring.

Each record of the application keeps the marker in one field beside its encrypted fields. A write that touches any encrypted field of a record takes one Encryptor from keyring.encryptor(), encrypts all of the record’s encrypted fields again through it, computes its beacons again, and stores encryptor.record().encryption_marker() in the same write, as the reencrypt function of Running a sweep does. The encryptor keeps the record it took from the cache, so the marker names the epoch whose active versions the fields are under, also when the cache refreshes during the write.

A marker read from keyring.record() names whichever record the cache held when it was read. Read before the encrypting, it can name an older epoch than the versions the fields are under, which puts the record outside the range of those versions. Read after, it can name a newer one, and the record then drops out of every sweep.

Why the row holds an encryption marker

Decryption never reads the marker. Every keyring value carries its key id in its prefix, 0x01 followed by the key id, so a read finds the version that encrypted a value from the value alone.

The marker lets the database find rows, where the library cannot: encrypted bytes cannot be indexed or compared, and the library does not scan the application’s tables. A row carries one small column that a range query can use, and the column answers two questions:

  • which rows are still to be re-encrypted after a rotation: those with encryption_marker < current;
  • which rows can still hold a value under a version, before it is destroyed: those with a marker in the ReencryptRange of the version. A query that returns nothing makes the destroy safe.

The marker is an epoch and not a key version because the fields of a row are under different purposes, such as randomised, deterministic and beacon, and the versions of each purpose rotate independently. A version marker would need a column per purpose. The epoch is one counter that the keyring moves on whenever any version becomes active. An Encryptor is a snapshot of all active versions at one epoch, and each version records the epochs it was active in, so both questions are one range query on one column.

An application that never sweeps, because it keeps old versions alive or re-encrypts a row when it next writes it, may leave the column out. Bulk re-encryption and the safe destruction of old versions need it.

Finding records behind

The records a sweep still has to visit are those whose marker is below the current one:

  • encryption_marker < $1 with the marker of keyring.record().encryption_marker(), on one indexed field, in every store;
  • row.encryption_marker < current in Rust, on a record read back before its re-encryption.

The query also matches a record with nothing to re-encrypt: after a rotation of a purpose the record holds no value of, such as a beacon rotation for a record without beacons, its marker is below the current one all the same. The re-encryption then writes the encryptor’s marker alone, without decrypting anything or calling the KMS, and the record matches once.

Each process stamps the epoch of the record it caches. A process that has not refreshed its record since a promotion encrypts under the previous version and stamps the previous epoch, so its writes stay in the query and the next sweep visits them. So the final check that the query returns nothing runs once the longest time any process may run without a successful refresh of its record has passed since the promotion.

The marker comes from the cached record, so a job that starts right after a promotion in another process calls reload() first.

Records under a version

KeyVersion::reencrypt_range() returns the markers of the records that can hold a value under the version, as a ReencryptRange:

  • start(), the epoch of the write that made the version active;
  • end(), the epoch of the first write after it stopped being active that moved the epoch on, or None while there was none: the active version, and a version flagged compromised while it was active, until a version is next made active.

A version that was never active, pending or destroyed while pending, has no range, and neither has an unknown key id: record.version(key_id) is None. The queries:

StoreQuery
Firestoretwo range filters on encryption_marker, see Sweeps on Firestore
PostgreSQLWHERE encryption_marker >= $1 AND ($2::BYTEA IS NULL OR encryption_marker < $2) with &range.start() and &range.end()
BigQueryWHERE encryption_marker >= @start AND (@end IS NULL OR encryption_marker < @end), with @end a NULL of type BYTES for an open range
Rustrange.contains(row.encryption_marker)

The range serves two decisions:

  • after mark_compromised, the range of the compromised version returns every record to re-encrypt and decide on, see The trust of re-encrypted values. The writes of processes that have not seen the compromise yet are in it too: they encrypt under the version and stamp an epoch below the range’s end. Run the query again once the longest time any process may run without a successful refresh of its record has passed since the compromise, for the writes of the last of them. A version flagged compromised after it stopped being active moves no epoch, and keeps the range it had;
  • before retire, and again before destroy, the query of the version returning nothing shows that no record holds a value under it, see Retiring the old version. That check needs one record at most: limit(1) in Firestore, EXISTS in SQL.

One epoch counts the activations of every purpose of the keyring, so a range can match a record with no field of the version’s purpose, such as a record without beacons in the range of a beacon version. Its re-encryption finds every value current and writes the marker alone. No range holds EncryptionMarker::ENVELOPE, since every range starts at epoch 1 or later. Records of several keyrings in one table add the keyring’s id to the query, as the sweep’s query does, see Sweeps by store.

Re-encrypting a value

Encryptor::reencrypt(aad, value) returns None for a value under the active randomised version of the encryptor’s record, without decrypting it or calling the KMS. A value under an older version the encryptor’s record holds, a decrypt-only version with a higher key id than the active one included, is read with decrypt_with_trust and encrypted again under the active version. The Reencrypted it returns holds the new value and the trust of the version the old value was read under, so the compromised-value decision stays with the caller, see The trust of re-encrypted values. Reencrypted::outcome() is the record’s ReencryptOutcome::Reencrypted, with from_compromised set from that trust, and ReencryptOutcome::from(&reencrypted) of the returned Option is Skipped for None. reencrypt_deterministic does the same for deterministic values, under the deterministic feature.

An encryptor never encrypts a value back under an older version. A value under a version that is pending in the encryptor’s record, or missing from it, was encrypted by a process with a newer record, and an encryptor taken before a mark_compromised would otherwise move it back under the compromised version. The re-encryption fails with KeyringError::EncryptorOutdated, after reloading the cached record when it lacks the version or holds it as pending, under the same rate limit as decrypt’s reload for a key id it lacks. The encryptor keeps its own record, so that its marker still names every version the write encrypts under.

How such a failure ends:

  • the write is safe to retry: it takes a new encryptor from the reloaded record, which finds the value current or encrypts it under its active version;
  • inside reload_min_interval of another such reload the cached record may not have moved yet, and the retry fails the same way until it does;
  • when the store’s record itself holds the version as pending, as for a value from another keyring whose key id is pending here or after a restore from an older backup, every retry fails with ENCRYPTOR_OUTDATED, at no more than one store read per reload_min_interval;
  • a key id the reloaded record lacks too fails with KeyVersionUnknown.

A beacon cannot be re-encrypted: it is a MAC of the plaintext. encryptor.is_current(beacon.key_id()) applies the same rule to it: true under the active beacon version of the encryptor’s record, and the beacon stays as it is; false under an older one, and the field is read with decrypt_with_trust, whose plaintext gives both the value under the active version, through the encryptor’s encrypt, and the beacon under the active beacon version, through its beacon(field, &plaintext); and EncryptorOutdated under a version newer than the encryptor’s record.

When nothing needs a re-encryption, the write still stores the encryptor’s marker, conditional on the record as the sweep read it, and the re-encryption returns ReencryptOutcome::Skipped.

Running a sweep

sweep::reencrypt_records drives the application’s re-encryption over a stream of candidates, with at most concurrency in flight, and counts what happened. sweep::reencrypt_records_batched cuts the same stream into batches, re-encrypted and written back one batch per call, as BatchedSweepOptions sets: 100 candidates a batch and 4 batches in flight by default, DEFAULT_BATCH_SIZE and DEFAULT_CONCURRENCY. The stream returns each candidate as a Result, so that the query that finds them can fail into the report rather than end the sweep in silence. A sweep is data plane: it takes a Keyring and needs the application’s rights only, since a re-encryption encrypts under a DEK the record already holds. The rotation before it and the retire after it are the administrative job’s, on a KeyringAdmin. Here over an in-memory table, with both in one process:

use std::collections::BTreeMap;
use std::num::NonZeroUsize;
use std::sync::Mutex;

use futures_util::stream;
use kms_aead::backends::Ring;
use kms_aead::providers::LocalKmsProvider;
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::sweep::{self, ReencryptOutcome, EncryptionMarker, SweepReport};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldName, FieldSpec, Keyring, KeyringResult,
};
use kms_aead::providers::LocalKekId;
use kms_aead::KmsAeadResult;
use kms_aead_keyring::{
    KeyId, KeyringAdmin, KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions,
    Plaintext, Purpose,
};
use secret_vault_value::SecretValue;

type UsersKeyring = Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring>;

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);
const TENANT: KeyringId = KeyringId::from_static("tenant-42");

#[derive(Clone)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

#[derive(Clone)]
struct UserRow {
    email: Encrypted<Email, Randomized>,
    encryption_marker: EncryptionMarker,
}

/// The users table, by user id.
type Table = Mutex<BTreeMap<String, UserRow>>;

/// Re-encrypts the row of `user` under the active version, with the marker of the encryptor's record.
async fn reencrypt(keyring: &UsersKeyring, table: &Table, user: &str) -> KeyringResult<ReencryptOutcome> {
    let Some(row) = table.lock().unwrap().get(user).cloned() else {
        return Ok(ReencryptOutcome::Skipped);
    };
    let read: Vec<u8> = row.email.value().to_vec();
    let encryptor = keyring.encryptor().await;
    let aad = EMAIL.aad(&EntityId::try_from(user)?);
    let reencrypted = encryptor.reencrypt(&aad, &row.email).await?;
    let outcome = ReencryptOutcome::from(&reencrypted);
    // The value is current when the rotation was of a purpose this row holds no value of
    let email = reencrypted.map_or(row.email, |reencrypted| reencrypted.value);
    let encryption_marker: EncryptionMarker = encryptor.record().encryption_marker();
    // Conditional on the row as it was read: a row the application rewrote meanwhile keeps its
    // own value, which it encrypted under the active versions anyway.
    let mut table = table.lock().unwrap();
    match table.get_mut(user) {
        Some(stored) if stored.email.value() == read.as_slice() => {
            *stored = UserRow { email, encryption_marker };
            Ok(outcome)
        }
        _ => Ok(ReencryptOutcome::Skipped),
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(provider, TENANT, KeyringAlgorithms::new())
    .await?;
let keyring: &UsersKeyring = admin.keyring();
let table = Table::default();
for (user, email) in [("41", "ada@example.com"), ("42", "alice@example.com")] {
    let encryptor = keyring.encryptor().await;
    let email = encryptor
        .encrypt(&EMAIL.aad(&EntityId::try_from(user)?), &Email(email.to_string()))
        .await?;
    let encryption_marker: EncryptionMarker = encryptor.record().encryption_marker();
    table.lock().unwrap().insert(user.to_string(), UserRow { email, encryption_marker });
}
let staged: KeyId = admin.rotate(Purpose::Randomized).await?;
admin.promote_now(staged).await?;
// Every row whose marker is below the keyring's
let current: EncryptionMarker = keyring.record().encryption_marker();
let candidates = table
    .lock()
    .unwrap()
    .iter()
    .filter(|(_, row)| row.encryption_marker < current)
    .map(|(user, _)| user.clone())
    .collect::<Vec<String>>();

let report: SweepReport = sweep::reencrypt_records(
    keyring.id(),
    stream::iter(candidates.into_iter().map(Ok)),
    NonZeroUsize::new(8).unwrap(),
    |candidate| {
        let table = &table;
        async move { reencrypt(keyring, table, &candidate).await }
    },
)
.await;
println!("{report:?}");
assert_eq!(report.reencrypted, 2);
registry.shutdown(None).await;
Ok(())
}

The SweepReport counts every candidate once in scanned, and once more in reencrypted, skipped or failed:

OutcomeCounted inLogged
The re-encryption wrote the recordreencrypted, and reencrypted_from_compromised when the value was under a compromised versionnot logged
The record needed nothing, or changed after it was readskippednot logged
The re-encryption failedfailedWARN with the candidate’s Display and the error’s Display
The stream returned the candidate as an errorfailedWARN with the error’s Display
A batch of reencrypt_records_batched failed as a whole, or returned more or fewer outcomes than it was given candidatesfailed, every candidate of the batchone WARN per batch, with the number of candidates and the error’s Display or the number of outcomes

A failure does not stop the sweep. A stream whose query cannot go on returns its error and ends. A re-encryption that fails with EncryptorOutdated is a failure of the second row: a process with a newer record rewrote the record after the query returned it, and the next run’s query no longer returns it, because the process that encrypted it stamped a newer marker. A value under a version the store’s record itself holds as pending fails in every run instead, see above. The events are in Keyring events.

A candidate is the application’s own type, such as a record id, a struct of key columns or the record itself, and its Display names the record and nothing else. A record id is often an entity id, so read the sweep’s log as an administrative log.

The stream returns Result<T, E> and the re-encryption Result<ReencryptOutcome, E>, with the application’s own error type, any type that implements Display. The keyring’s calls inside it return a KeyringError, and a From impl on the application’s error lets ? convert it, as the examples on Firestore, PostgreSQL and BigQuery do with an error of their data store; a re-encryption with no errors of its own returns KeyringResult<ReencryptOutcome>, as above. The error’s Display is the application’s text and goes to the log as it is, so it carries no value, secret or personal data. The report counts failures and keeps no error: an application that wants the errors themselves records them inside its re-encryption.

Retiring the old version

Once the sweep is done, the administrative job retires the version a promotion replaced, and later destroys it, on its KeyringAdmin:

  1. wait, from the promotion, the longest time any process may run without a successful refresh of its record, see Staged rotation, and check that no process logged a failed revalidation meanwhile, see Keyring events. Until then a process on the old record encrypts under the old version and stamps the old epoch, see Finding records behind;
  2. run the sweep until a run reports nothing scanned and nothing failed;
  3. run the old version’s range query. When it returns nothing, retire(key_id). Reads under the version fail with KeyVersionRetired from then on, logged at WARN;
  4. export the Readable BigQuery and Tink keysets again, which leave a retired version out, and write them where the old ones are kept, see BigQuery and Tink interop. A keyset exported before keeps reading values under the retired version in SQL and in Tink;
  5. keep the version retired for as long as the backups of the stored values taken before the sweep are kept. A destroyed version makes the values in them unreadable, as a destroyed KEK version does, see Re-encrypt DEKs after a KEK rotation, and only a backup of the record from before the destroy still decrypts them, see below. A value the sweep missed fails with KeyVersionRetired: reinstate(key_id), export the keysets again, sweep again, and go back to step 3;
  6. run the range query again. When it still returns nothing, delete every copy of the keysets whose key_ids() include the retired version, then destroy(key_id). The other keysets, such as the Single keyset of the active deterministic version and the Readable keysets of other purposes, keep reading their values in SQL and in Tink. No call brings a destroyed version back.

destroy removes the encrypted DEK from the record only. A backup of the record still holds it, and so does every copy of a keyset exported while the version decrypted, both decrypted by the KMS as long as the KEK version that encrypted them exists, see What survives a shred. dangerously_shred() destroys every version and deletes the record, with the same copies left behind.

Sweeps by store

At millions of records a sweep streams its candidates from the store in one query and never holds its result in memory, and it writes them back in batches. Every example, on Firestore, PostgreSQL and BigQuery, has the same five properties:

  • it resumes without a checkpoint: the query is the checkpoint, since a re-encrypted record no longer matches it, so a cancelled or failed run is started again over the same query;
  • a concurrent writer wins: the write is conditional on the record the sweep read, and a record that changed in between is Skipped. The application’s own write re-encrypts every field under the active versions anyway;
  • concurrency bounds the batches in flight, and with them the load on both the store and the KMS. The DEK cache keeps each version’s key, so a sweep makes one KMS decrypt per key version and cache TTL, never one per record. The keys of a compromised version are the exception: they are decrypted for every value and never cached;
  • each write stores the marker of the encryptor that re-encrypted the record, so the record lies in the range of every version it is under;
  • it runs on a schedule until a run reports nothing scanned. The retire, and later the destroy, of the old version are the administrative job’s, see Retiring the old version.

The examples keep one keyring’s records in a collection or table. Each keyring counts its own epochs, so records of several keyrings in one table keep their keyring’s id beside the marker, and the query compares within one keyring, tenant = $2 AND encryption_marker < $1, on an index over both fields: a composite index in Firestore.

The trust of re-encrypted values

A sweep reads every field with decrypt_with_trust, and reports in ReencryptOutcome::Reencrypted whether the KeyTrust of any of them is compromised. A value read under a compromised version is untrusted data: whoever holds the leaked DEK can have forged it. Re-encrypting it under a new version makes it read as trusted everywhere afterwards.

So after a compromise the application decides per record before it re-encrypts:

  • a quarantine field beside the marker, for a person to review;
  • a comparison against a backup taken before the compromise;
  • or acceptance, when forged values do no harm.

SweepReport::reencrypted_from_compromised counts the records that went through that decision, or fewer on the BigQuery MERGE path, whose batches with a conflict count as skipped.

Sweeps on Firestore

A sweep of a Firestore collection: the encryption marker as a field, the query for the documents behind, and the conditional write back. The mechanism is in Sweeps, and the example has the five properties of Sweeps by store.

Schema and indexing

The marker is a bytes field, encryption_marker, and the query is one range filter on it. Firestore indexes a field ascending and descending by default, and the query needs the ascending index only, so a field override keeps just that one. firestore-rs declares it with its index management, behind its admin feature:

use firestore::{FirestoreDb, FirestoreIndexSyncReport, FirestoreResult};

/// Keeps the ascending index of `encryption_marker` in the `users` collection group, and drops the descending
/// one.
async fn sync_users_indexes(db: &FirestoreDb) -> FirestoreResult<FirestoreIndexSyncReport> {
    db.fluent()
        .indexes()
        .collection_group("users")
        .field_overrides(|f| f.fields([f.field("encryption_marker").indexes([f.ascending()])]))
        .sync()
        .await
}

The declaration runs from an administrative job, such as a deploy step, since .sync() needs the Firestore Admin API and roles/datastore.indexAdmin; the application that sweeps does not run it. The index management chapter of firestore-rs covers .plan(), .sync() and running them from a deploy.

A project that manages its indexes outside Rust sets the same override with gcloud:

gcloud firestore indexes fields update encryption_marker --collection-group=users --index=order=ASCENDING

Querying behind and by version

The documents behind are one filter, encryption_marker < current, as in the sweep below. The documents that can hold a value under a version, which the administrative job checks before retire and destroy, are the range of that version, see Records under a version. Firestore takes both bounds on the one field and serves them from its ascending index on encryption_marker, and an open range is one filter:

use firestore::{FirestoreDb, FirestoreResult};
use futures_util::stream::{self, BoxStream, StreamExt};
use kms_aead::backends::Ring;
use kms_aead::providers::GcpKmsProvider;
use kms_aead_keyring::store::FirestoreKeyringStore;
use kms_aead_keyring::sweep::{EncryptionMarker, ReencryptRange};
use kms_aead_keyring::{KeyId, KeyVersion, Keyring};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct UserDoc {
    #[serde(rename = "_firestore_id", skip_serializing)]
    id: String,
    #[serde(default)]
    encryption_marker: EncryptionMarker,
}

/// The users that can hold a value under `key_id`, as a stream: a range can hold millions.
async fn users_under<'a>(
    db: &'a FirestoreDb,
    keyring: &Keyring<FirestoreKeyringStore, GcpKmsProvider, Ring>,
    key_id: KeyId,
) -> Result<BoxStream<'a, FirestoreResult<UserDoc>>, Box<dyn std::error::Error>> {
    // The store's record: a compromise or promotion in another process is in it
    let range: Option<ReencryptRange> = keyring
        .reload()
        .await?
        .version(key_id)
        .and_then(KeyVersion::reencrypt_range);
    let Some(range) = range else {
        // Never active: no record holds a value under it
        return Ok(stream::empty().boxed());
    };
    let users: BoxStream<'a, FirestoreResult<UserDoc>> = db
        .fluent()
        .select()
        .from("users")
        .filter(|q| {
            q.for_all([
                q.field("encryption_marker").greater_than_or_equal(range.start()),
                range.end().and_then(|end| q.field("encryption_marker").less_than(end)),
            ])
        })
        .obj()
        .stream_query_with_errors()
        .await?;
    Ok(users)
}

fn main() {}

Re-encrypting in batches

The query streams with stream_query_with_errors(), so that a document that does not read is a failed candidate, and the sweep never ends early on it. sweep::reencrypt_records_batched cuts the documents into batches of 500, each re-encrypted through one encryptor and written back in one BatchWrite. Each write of the batch carries its document’s update time as its precondition, and Firestore refuses it once anything changed the document since the query read it:

use std::fmt::{self, Display, Formatter};
use std::num::NonZeroUsize;
use std::time::Duration;

use firestore::errors::FirestoreError;
use firestore::gcloud_sdk::google::rpc::Code;
use firestore::{
    paths, FirestoreBatchWriteResponse, FirestoreDb, FirestoreDbOptions,
    FirestoreSimpleBatchWriteOptions, FirestoreSimpleBatchWriter, FirestoreTimestamp,
    FirestoreWritePrecondition,
};
use futures_util::TryStreamExt;
use kms_aead::backends::Ring;
use kms_aead::providers::GcpKmsProvider;
use kms_aead::KmsAeadResult;
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::store::FirestoreKeyringStore;
use kms_aead_keyring::sweep::{self, BatchedSweepOptions, ReencryptOutcome, EncryptionMarker, SweepReport};
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldName, FieldSpec, Keyring, KeyringError, Plaintext,
};
use secret_vault_value::SecretValue;
use serde::{Deserialize, Serialize};
use kms_aead::providers::GcpKmsKeyRef;
use kms_aead_keyring::{KeyringId, KeyringRegistry, KeyringRegistryOptions};

type UsersKeyring = Keyring<FirestoreKeyringStore, GcpKmsProvider, Ring>;

const USERS: &str = "users";
const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);
/// Firestore's limit of writes in one `BatchWrite`.
const BATCH_SIZE: NonZeroUsize = NonZeroUsize::new(500).unwrap();
const CONCURRENCY: NonZeroUsize = NonZeroUsize::new(16).unwrap();
/// How long the batch writer retries a failed `BatchWrite` before the batch fails with its error.
/// The writer retries with no limit of its own, so without this a sweep against a Firestore that
/// refuses or fails its requests never ends.
const BATCH_WRITE_RETRY_LIMIT: Duration = Duration::from_secs(5);
/// How long a request waits for an answer, so that one to a Firestore that stopped answering fails.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

#[derive(Clone)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

#[derive(Deserialize)]
struct UserDoc {
    #[serde(rename = "_firestore_id")]
    id: String,
    #[serde(rename = "_firestore_updated")]
    updated: FirestoreTimestamp,
    email: Encrypted<Email, Randomized>,
}

/// The fields a re-encryption writes: the encrypted fields and the marker of the encryptor that encrypted
/// them.
#[derive(Serialize, Deserialize)]
struct UserFields {
    email: Encrypted<Email, Randomized>,
    encryption_marker: EncryptionMarker,
}

/// The document id, and nothing of its fields.
impl Display for UserDoc {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "{USERS}/{}", self.id)
    }
}

/// Why the sweep failed on a document or a batch: an error of the keyring or of the users
/// collection, or the status of a document's write in a batch, `None` for a status the batch did
/// not return.
enum SweepError {
    Keyring(KeyringError),
    Users(FirestoreError),
    Write(Option<Code>),
}

impl From<KeyringError> for SweepError {
    fn from(error: KeyringError) -> Self {
        SweepError::Keyring(error)
    }
}

impl From<FirestoreError> for SweepError {
    fn from(error: FirestoreError) -> Self {
        SweepError::Users(error)
    }
}

/// The text the sweep logs: codes, never Firestore's messages, since a deserialisation error can
/// quote the field it could not read.
impl Display for SweepError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            SweepError::Keyring(error) => write!(f, "the keyring failed with {}", error.code()),
            SweepError::Users(FirestoreError::DatabaseError(error)) => {
                write!(f, "the users collection failed with {}", error.public.code)
            }
            SweepError::Users(FirestoreError::DeserializeError(_)) => {
                f.write_str("a document of users did not deserialise")
            }
            SweepError::Users(_) => f.write_str("the users collection failed"),
            SweepError::Write(Some(code)) => write!(f, "its write failed with {code:?}"),
            SweepError::Write(None) => f.write_str("its write returned no status"),
        }
    }
}

/// Re-encrypts every user whose marker is below the current one, in batches of [`BATCH_SIZE`] with
/// [`CONCURRENCY`] in flight, and returns the sweep's report.
async fn sweep_users(
    keyring: &UsersKeyring,
    writer: &FirestoreSimpleBatchWriter,
) -> Result<SweepReport, FirestoreError> {
    let current: EncryptionMarker = keyring.record().encryption_marker();
    let candidates = writer
        .db
        .fluent()
        .select()
        .fields(paths!(UserFields::{email, encryption_marker}))
        .from(USERS)
        .filter(|q| q.field("encryption_marker").less_than(current))
        .obj::<UserDoc>()
        .stream_query_with_errors()
        .await?
        .err_into::<SweepError>();
    let report: SweepReport = sweep::reencrypt_records_batched(
        keyring.id(),
        candidates,
        BatchedSweepOptions::new()
            .with_batch_size(BATCH_SIZE)
            .with_concurrency(CONCURRENCY),
        |docs: Vec<UserDoc>| reencrypt_batch(keyring, writer, docs),
    )
    .await;
    Ok(report)
}

/// Re-encrypts a batch of documents through one encryptor and writes them back in one `BatchWrite`,
/// each write stamped with the encryptor's marker and conditional on the update time the query read.
/// A batch is not atomic: a document changed since the query fails its own write only, and the
/// sweep counts it as skipped.
async fn reencrypt_batch(
    keyring: &UsersKeyring,
    writer: &FirestoreSimpleBatchWriter,
    docs: Vec<UserDoc>,
) -> Result<Vec<(UserDoc, Result<ReencryptOutcome, SweepError>)>, SweepError> {
    let encryptor = keyring.encryptor().await;
    let encryption_marker: EncryptionMarker = encryptor.record().encryption_marker();
    let mut batch = writer.new_batch();
    let mut done: Vec<(UserDoc, Result<ReencryptOutcome, SweepError>)> =
        Vec::with_capacity(docs.len());
    let mut queued: Vec<(UserDoc, ReencryptOutcome)> = Vec::with_capacity(docs.len());
    for doc in docs {
        let queue = async {
            let aad = EMAIL.aad(&EntityId::try_from(doc.id.as_str())?);
            let reencrypted = encryptor.reencrypt(&aad, &doc.email).await?;
            let outcome = ReencryptOutcome::from(&reencrypted);
            // A current value still gets the encryptor's marker, so that it leaves the query.
            let email = reencrypted.map_or_else(|| doc.email.clone(), |reencrypted| reencrypted.value);
            writer
                .db
                .fluent()
                .update()
                .fields(paths!(UserFields::{email, encryption_marker}))
                .in_col(USERS)
                .precondition(FirestoreWritePrecondition::UpdateTime(doc.updated.into()))
                .document_id(&doc.id)
                .object(&UserFields { email, encryption_marker })
                .add_to_batch(&mut batch)?;
            Ok::<ReencryptOutcome, SweepError>(outcome)
        };
        match queue.await {
            Ok(outcome) => queued.push((doc, outcome)),
            Err(error) => done.push((doc, Err(error))),
        }
    }
    if queued.is_empty() {
        return Ok(done);
    }
    let response: FirestoreBatchWriteResponse = batch.write().await?;
    done.extend(queued.into_iter().enumerate().map(|(index, (doc, outcome))| {
        let code: Option<Code> = response
            .statuses
            .get(index)
            .and_then(|status| Code::try_from(status.code).ok());
        let outcome = match code {
            Some(Code::Ok) => Ok(outcome),
            // Written since the query: the writer encrypted the document under its own record.
            Some(Code::FailedPrecondition) => Ok(ReencryptOutcome::Skipped),
            _ => Err(SweepError::Write(code)),
        };
        (doc, outcome)
    }));
    Ok(done)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let key_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);
let db: FirestoreDb = FirestoreDb::with_options(
    FirestoreDbOptions::new("my-project".to_string()).with_request_timeout(REQUEST_TIMEOUT),
)
.await?;
let writer: FirestoreSimpleBatchWriter = db
    .create_simple_batch_writer_with_options(
        FirestoreSimpleBatchWriteOptions::new()
            .with_retry_max_elapsed_time(BATCH_WRITE_RETRY_LIMIT),
    )
    .await?;
let registry = KeyringRegistry::<FirestoreKeyringStore, Ring>::new(
    FirestoreKeyringStore::new(db.clone()),
    KeyringRegistryOptions::new(),
)?;
let keyring: UsersKeyring = registry
    .open(GcpKmsProvider::new(&key_ref).await?, KeyringId::from_static("tenant-42"))
    .await?;
let report: SweepReport = sweep_users(&keyring, &writer).await?;
println!("{report:?}");
registry.shutdown(None).await;
Ok(())
}

Operational limits

  • the retry limit ends the batch writer’s retries, and the request timeout ends a request that never gets an answer, the candidate query included, so a sweep against a Firestore that refuses, fails or stops answering its requests ends with an error;
  • CONCURRENCY batches of 500 writes in flight are a high write rate for a collection that has seen little traffic. Firestore advises starting a new collection at 500 writes a second and raising the rate by 50% every 5 minutes, its 500/50/5 rule, so raise CONCURRENCY step by step on one;
  • a range filter never matches a document without the field, so a document written before the marker needs the marker written first, see Move envelope values to a keyring;
  • a partitioned query does not fit the sweep: PartitionQuery takes no filter, so its workers would read every document, the current ones included.

Storage overhead

The marker takes 23 bytes of a document: the field name, encryption_marker, as an 18-byte string (17 bytes of UTF-8 and 1 more, by Firestore’s storage size rules), and the 5 bytes of the value. Its entry in the ascending index takes the size of the document’s name, of its parent’s name and 23 bytes for the field name and the value, plus 32 bytes. 10 million documents hold 0.23 GB of markers, and the index adds the names’ size to every entry.

Runnable example

The sweep_firestore example runs this sweep end to end, from the writes to the report, on the Firestore emulator.

Sweeps on PostgreSQL

A sweep of a PostgreSQL table: the encryption marker as a column, the query for the rows behind, and the conditional write back. The mechanism is in Sweeps, and the example has the five properties of Sweeps by store.

Schema and indexing

The marker is a BYTEA column with a btree index. EncryptionMarker is a BYTEA parameter and column through tokio-postgres with the postgres feature, and through sqlx with the sqlx feature:

CREATE TABLE users (
    id BIGINT PRIMARY KEY,
    email BYTEA NOT NULL,
    encryption_marker BYTEA NOT NULL
);
CREATE INDEX users_encryption_marker ON users (encryption_marker);

Querying behind and by version

The candidates are one query, encryption_marker < $1 with no ORDER BY, so the planner is free to read them from the index on encryption_marker. The query for the rows that can hold a value under a version is in Records under a version.

Re-encrypting in batches

  • query_raw streams the rows, and the query holds its connection for as long as it streams, so the UPDATEs go through a second one;
  • sweep::reencrypt_records_batched cuts the candidates into batches of 1000 rows, each re-encrypted through one encryptor and written back in one UPDATE over arrays of the ids, the new values and the values it read;
  • the UPDATE is conditional on the bytes it read, which a write of any other process changes, since every randomised value has its own nonce. A process that has not seen the promotion yet still encrypts under the old version and stamps the old epoch, which the row holds already, so the marker alone does not detect its write.
use std::collections::HashSet;
use std::fmt::{self, Display, Formatter};
use std::num::NonZeroUsize;

use futures_util::{future, StreamExt};
use kms_aead::backends::Ring;
use kms_aead::providers::GcpKmsProvider;
use kms_aead::KmsAeadResult;
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::store::PostgresKeyringStore;
use kms_aead_keyring::sweep::{self, BatchedSweepOptions, ReencryptOutcome, EncryptionMarker, SweepReport};
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldName, FieldSpec, Keyring, KeyringError, Plaintext,
};
use secret_vault_value::SecretValue;
use tokio_postgres::{Client, NoTls, Row};
use kms_aead::providers::GcpKmsKeyRef;
use kms_aead_keyring::{KeyringId, KeyringRegistry, KeyringRegistryOptions};
use tokio_postgres::Config;

type UsersKeyring = Keyring<PostgresKeyringStore<NoTls>, GcpKmsProvider, Ring>;

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);
const BATCH_SIZE: NonZeroUsize = NonZeroUsize::new(1000).unwrap();
const CONCURRENCY: NonZeroUsize = NonZeroUsize::new(16).unwrap();

#[derive(Clone)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

/// A row the query returned.
struct UserRow {
    id: i64,
    email: Encrypted<Email, Randomized>,
}

/// The row id, and nothing of its columns.
impl Display for UserRow {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "users/{}", self.id)
    }
}

/// Why the sweep failed on a row or a batch: an error of the keyring or of the users table.
enum SweepError {
    Keyring(KeyringError),
    Users(tokio_postgres::Error),
}

impl From<KeyringError> for SweepError {
    fn from(error: KeyringError) -> Self {
        SweepError::Keyring(error)
    }
}

impl From<tokio_postgres::Error> for SweepError {
    fn from(error: tokio_postgres::Error) -> Self {
        SweepError::Users(error)
    }
}

/// The text the sweep logs: codes, never the server's message, whose detail can quote a row's
/// values.
impl Display for SweepError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            SweepError::Keyring(error) => write!(f, "the keyring failed with {}", error.code()),
            SweepError::Users(error) => match error.code() {
                Some(state) => write!(f, "the users table failed with SQLSTATE {}", state.code()),
                None => f.write_str("the users table failed"),
            },
        }
    }
}

/// Re-encrypts every user whose marker is below the current one, read through `reader` and written
/// back through `writer` in batches of [`BATCH_SIZE`] with [`CONCURRENCY`] in flight, and returns
/// the sweep's report.
async fn sweep_users(
    keyring: &UsersKeyring,
    reader: &Client,
    writer: &Client,
) -> Result<SweepReport, tokio_postgres::Error> {
    let current: EncryptionMarker = keyring.record().encryption_marker();
    // A row that does not read is a failed candidate. An error of the stream itself is one too, and
    // ends it: once its connection drops, the stream returns that error on every poll and never
    // its end.
    let mut failed = false;
    let candidates = reader
        .query_raw("SELECT id, email FROM users WHERE encryption_marker < $1", [current])
        .await?
        .take_while(move |row: &Result<Row, tokio_postgres::Error>| {
            let more = !failed;
            failed = row.is_err();
            future::ready(more)
        })
        .map(|row: Result<Row, tokio_postgres::Error>| {
            let row: Row = row?;
            Ok::<UserRow, SweepError>(UserRow {
                id: row.try_get("id")?,
                email: row.try_get("email")?,
            })
        });
    let report: SweepReport = sweep::reencrypt_records_batched(
        keyring.id(),
        candidates,
        BatchedSweepOptions::new()
            .with_batch_size(BATCH_SIZE)
            .with_concurrency(CONCURRENCY),
        |batch: Vec<UserRow>| reencrypt_batch(keyring, writer, batch),
    )
    .await;
    Ok(report)
}

/// Re-encrypts a batch of rows through one encryptor and writes it back in one `UPDATE` that stamps
/// the encryptor's marker, row by row only where the row still holds the bytes the query read. A
/// row changed since the query is not returned by the `UPDATE`, and the sweep counts it as skipped.
async fn reencrypt_batch(
    keyring: &UsersKeyring,
    client: &Client,
    batch: Vec<UserRow>,
) -> Result<Vec<(UserRow, Result<ReencryptOutcome, SweepError>)>, SweepError> {
    let encryptor = keyring.encryptor().await;
    let encryption_marker: EncryptionMarker = encryptor.record().encryption_marker();
    let mut done: Vec<(UserRow, Result<ReencryptOutcome, SweepError>)> =
        Vec::with_capacity(batch.len());
    let mut queued: Vec<(UserRow, ReencryptOutcome)> = Vec::with_capacity(batch.len());
    let mut emails: Vec<Encrypted<Email, Randomized>> = Vec::with_capacity(batch.len());
    for user in batch {
        let reencrypt = async {
            let aad = EMAIL.aad(&EntityId::try_from(user.id.to_string())?);
            let reencrypted = encryptor.reencrypt(&aad, &user.email).await?;
            let outcome = ReencryptOutcome::from(&reencrypted);
            // A current value still gets the encryptor's marker, so that it leaves the query.
            let email = reencrypted.map_or_else(|| user.email.clone(), |reencrypted| reencrypted.value);
            Ok::<_, SweepError>((email, outcome))
        };
        match reencrypt.await {
            Ok((email, outcome)) => {
                emails.push(email);
                queued.push((user, outcome));
            }
            Err(error) => done.push((user, Err(error))),
        }
    }
    let ids: Vec<i64> = queued.iter().map(|(user, _)| user.id).collect();
    let read_emails: Vec<&Encrypted<Email, Randomized>> =
        queued.iter().map(|(user, _)| &user.email).collect();
    let written: HashSet<i64> = client
        .query(
            "UPDATE users SET email = batch.email, encryption_marker = $4
             FROM unnest($1::BIGINT[], $2::BYTEA[], $3::BYTEA[]) AS batch(id, email, read_email)
             WHERE users.id = batch.id AND users.email = batch.read_email
             RETURNING users.id",
            &[&ids, &emails, &read_emails, &encryption_marker],
        )
        .await?
        .iter()
        .map(|row| row.try_get("id"))
        .collect::<Result<HashSet<i64>, tokio_postgres::Error>>()?;
    done.extend(queued.into_iter().map(|(user, outcome)| {
        // Written since the query: the writer encrypted the row under its own record.
        let outcome = if written.contains(&user.id) {
            outcome
        } else {
            ReencryptOutcome::Skipped
        };
        (user, Ok(outcome))
    }));
    Ok(done)
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let key_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);
let config: Config = "postgres://app@localhost/app".parse()?;
let (client, connection) = config.connect(NoTls).await?;
tokio::spawn(connection);
let (reader, connection) = config.connect(NoTls).await?;
tokio::spawn(connection);
let registry = KeyringRegistry::<PostgresKeyringStore<NoTls>, Ring>::new(
    PostgresKeyringStore::new(config, NoTls),
    KeyringRegistryOptions::new(),
)?;
let keyring: UsersKeyring = registry
    .open(GcpKmsProvider::new(&key_ref).await?, KeyringId::from_static("tenant-42"))
    .await?;
let report: SweepReport = sweep_users(&keyring, &reader, &client).await?;
println!("{report:?}");
registry.shutdown(None).await;
Ok(())
}

Operational limits

  • CONCURRENCY bounds the batches in flight, but one writing connection runs their UPDATEs one after another; a pool of connections runs them in parallel;
  • a row that does not read is a failed candidate. An error of the stream itself is one too, and ends it: once the connection drops, the stream returns that error on every poll and never its end, so the example stops it at the first error with take_while;
  • the query holds one snapshot for as long as it streams, and while it is open VACUUM cannot reclaim the old versions of the rows the sweep updates; a scheduled job that ends and runs again keeps each snapshot short.

Storage overhead

The marker takes 6 bytes of a row: its 5 bytes and a 1-byte length header. A btree on a column of a few distinct epochs stores each one once per page with the list of its rows, which takes about 7 bytes per row of index. 10 million rows hold about 130 MB of markers and index.

Runnable example

The sweep_postgres example runs this sweep end to end, from the writes to the report, on a local PostgreSQL.

Sweeps on BigQuery

A sweep of a BigQuery table, in two paths: one UPDATE in SQL for the fields BigQuery reads, and a Rust path for the rest. The mechanism is in Sweeps. The Rust path has the five properties of Sweeps by store, and the SQL path states which of them it holds.

Schema and indexing

The marker is a BYTES column that every write of the encrypted fields sets. BigQuery has no index to declare, and the query reads the whole column, see Storage overhead:

CREATE TABLE users (
  id STRING NOT NULL,
  email BYTES NOT NULL,
  encryption_marker BYTES NOT NULL
);

Querying behind and by version

The rows behind are those with encryption_marker < @current, the current marker bound as a parameter and read from the record’s encryption_marker(), see Finding records behind. The administrative job retires the old version once its range query returns 0:

SELECT COUNT(*) FROM users
WHERE encryption_marker >= @start AND (@end IS NULL OR encryption_marker < @end);

Re-encrypting in SQL

A field BigQuery reads, declared with Interop::BigQuery, is re-encrypted by one UPDATE in SQL, with no Rust loop and no value leaving BigQuery. Its parameters come from a Readable(Purpose::Randomized) export, see Exporting a keyset to BigQuery: @kms_key is the export’s key_uri(), @keyset its value(), and @encryption_marker the bytes of its marker, keyset.encryption_marker().value():

UPDATE users
SET
  email = AEAD.ENCRYPT(
    KEYS.KEYSET_CHAIN(@kms_key, @keyset),
    AEAD.DECRYPT_BYTES(
      KEYS.KEYSET_CHAIN(@kms_key, @keyset), email, CAST(CONCAT('user/', id, '/email') AS BYTES)),
    CAST(CONCAT('user/', id, '/email') AS BYTES)),
  encryption_marker = @encryption_marker
WHERE encryption_marker < @encryption_marker;

AEAD.DECRYPT_BYTES, and AEAD.ENCRYPT of bytes, take the AAD as BYTES, the UTF-8 of the same text. AEAD.ENCRYPT encrypts under the keyset’s primary, which a Readable export sets to the active version of the record it reads from the store, and EncryptedKeyset::encryption_marker() is that record’s marker. So every row the statement re-encrypts lies in the range of the primary, as a row written through an Encryptor does. A keyset exported before a promotion has the previous version as its primary and the previous epoch’s marker, and the rows it re-encrypts stay in the next sweep’s query, so the sweep exports its keyset after the promotion. The export is a KeyringAdmin call of the administrative job.

The statement re-encrypts every encrypted field of the row, since the marker it writes covers all of them. Fields of several purposes are encrypted under one Readable keyset each, and the statement stamps the marker only when their encryption_marker() is the same; otherwise it exports them again. A row with a beacon, which SQL does not compute, goes through the Rust path below.

Of the five properties of Sweeps by store, the SQL path holds these:

  • it resumes without a checkpoint because the statement is atomic: a failed one changed nothing, and the next run’s WHERE finds every row it did not write;
  • it loses no concurrent write: BigQuery runs DML under snapshot isolation, and of two conflicting statements on the same rows one fails and runs again, and its WHERE then sees the other’s marker;
  • it makes no KMS call per record: BigQuery decrypts the keyset through Cloud KMS for the statement;
  • it runs on a schedule until it re-encrypts no row.

A Readable keyset leaves a compromised version out, so the values under it fail AEAD.DECRYPT_BYTES and the whole statement with them. After a compromise those rows go through the Rust path below, where the encryptor’s reencrypt reports their trust.

Re-encrypting in Rust

Values the statement cannot re-encrypt, such as ChaCha20-Poly1305 values or values under a custom AAD, are re-encrypted in Rust, in the same column. BigQuery runs only a few DML statements on one table at a time, so the write is one MERGE per batch of rows rather than one UPDATE per row, conditional on the bytes each row held:

MERGE users u
USING UNNEST(@rows) p
ON u.id = p.id AND u.email = p.old_email
WHEN MATCHED THEN UPDATE SET email = p.email, encryption_marker = @encryption_marker;

The rows stream from the application’s BigQuery client, one query of SELECT id, email, encryption_marker FROM users WHERE encryption_marker < @current, and sweep::reencrypt_records_batched cuts them into batches. Each batch is re-encrypted through one encryptor, and the client runs the MERGE with @encryption_marker bound to the marker of the encryptor’s record. Every row of a batch goes into @rows, the current ones with their bytes as they are, so that each gets the marker:

use std::fmt::{self, Display, Formatter};
use std::future::Future;
use std::num::NonZeroUsize;

use futures_util::Stream;
use kms_aead::backends::Ring;
use kms_aead::providers::GcpKmsProvider;
use kms_aead::KmsAeadResult;
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::store::FirestoreKeyringStore;
use kms_aead_keyring::sweep::{self, BatchedSweepOptions, ReencryptOutcome, EncryptionMarker, SweepReport};
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldName, FieldSpec, Keyring, KeyringError, KeyringResult,
    Plaintext, Encryptor,
};
use secret_vault_value::SecretValue;

type UsersKeyring = Keyring<FirestoreKeyringStore, GcpKmsProvider, Ring>;
type UsersEncryptor<'k> = Encryptor<'k, FirestoreKeyringStore, GcpKmsProvider, Ring>;

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);
const BATCH_SIZE: NonZeroUsize = NonZeroUsize::new(1000).unwrap();
/// BigQuery runs 2 mutating DML statements on a table at once and queues the rest.
const CONCURRENCY: NonZeroUsize = NonZeroUsize::new(2).unwrap();

#[derive(Clone)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

/// A row of `SELECT id, email FROM users WHERE encryption_marker < @current`.
struct UserRow {
    id: String,
    email: Encrypted<Email, Randomized>,
}

/// The row id, and nothing of its columns.
impl Display for UserRow {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "users/{}", self.id)
    }
}

/// One element of `@rows`: a row with the bytes it held and the bytes to write.
struct EmailUpdate {
    id: String,
    old_email: Vec<u8>,
    email: Encrypted<Email, Randomized>,
}

/// `email` of user `id` under the active version of `encryptor`, and the outcome of its
/// re-encryption. A value under that version comes back as it is, with `ReencryptOutcome::Skipped`.
async fn reencrypt_email(
    encryptor: &UsersEncryptor<'_>,
    id: &str,
    email: &Encrypted<Email, Randomized>,
) -> KeyringResult<(Encrypted<Email, Randomized>, ReencryptOutcome)> {
    let aad = EMAIL.aad(&EntityId::try_from(id)?);
    let reencrypted = encryptor.reencrypt(&aad, email).await?;
    let outcome = ReencryptOutcome::from(&reencrypted);
    // A current value still gets the encryptor's marker, so that it leaves the query.
    let email = reencrypted.map_or_else(|| email.clone(), |reencrypted| reencrypted.value);
    Ok((email, outcome))
}

/// Re-encrypts the `rows` of the query in batches, one encryptor per batch, and writes each batch
/// through `merge`, which runs the `MERGE` with `@encryption_marker` bound to the marker it is given, the
/// marker of the batch's encryptor, and returns its number of affected rows. `ClientError` is the
/// error of the application's BigQuery client, which a row that did not read returns and a
/// `KeyringError` converts into, and its `Display` is the text the sweep logs for a failure.
async fn sweep_emails<Rows, Merge, Merged, ClientError>(
    keyring: &UsersKeyring,
    rows: Rows,
    merge: Merge,
) -> SweepReport
where
    Rows: Stream<Item = Result<UserRow, ClientError>>,
    Merge: Fn(Vec<EmailUpdate>, EncryptionMarker) -> Merged,
    Merged: Future<Output = Result<u64, ClientError>>,
    ClientError: From<KeyringError> + Display,
{
    let options: BatchedSweepOptions = BatchedSweepOptions::new()
        .with_batch_size(BATCH_SIZE)
        .with_concurrency(CONCURRENCY);
    sweep::reencrypt_records_batched(keyring.id(), rows, options, |batch: Vec<UserRow>| {
        let merge = &merge;
        async move {
            let encryptor: UsersEncryptor<'_> = keyring.encryptor().await;
            let mut done: Vec<(UserRow, Result<ReencryptOutcome, ClientError>)> =
                Vec::with_capacity(batch.len());
            let mut queued: Vec<(UserRow, ReencryptOutcome)> = Vec::with_capacity(batch.len());
            let mut updates: Vec<EmailUpdate> = Vec::with_capacity(batch.len());
            for row in batch {
                match reencrypt_email(&encryptor, &row.id, &row.email).await {
                    Ok((email, outcome)) => {
                        updates.push(EmailUpdate {
                            id: row.id.clone(),
                            old_email: row.email.value().to_vec(),
                            email,
                        });
                        queued.push((row, outcome));
                    }
                    Err(error) => done.push((row, Err(error.into()))),
                }
            }
            let merged: u64 = merge(updates, encryptor.record().encryption_marker()).await?;
            // A `MERGE` returns a count, not the rows: a batch with one row a concurrent writer
            // changed counts every row as skipped
            let all_written = u64::try_from(queued.len()) == Ok(merged);
            done.extend(queued.into_iter().map(|(row, outcome)| {
                (row, Ok(if all_written { outcome } else { ReencryptOutcome::Skipped }))
            }));
            Ok(done)
        }
    })
    .await
}

fn main() {}

Operational limits

  • a batch is re-encrypted sequentially inside its call, and concurrency bounds the batches in flight, which BigQuery’s limit on concurrent DML per table sets low. The five properties hold per batch: a row that a concurrent writer changed fails the ON condition and stays in the query for the next run;
  • a MERGE returns a count, not the rows it changed, so a batch with one such row counts all its rows as Skipped, the ones it wrote included. Its re-encryptions from a compromised version then drop out of SweepReport::reencrypted_from_compromised, although they went through the trust decision in The trust of re-encrypted values, so on this path that count is a lower bound.

Storage overhead

The marker takes 7 bytes of a row: its 5 bytes and the 2 BigQuery counts for every BYTES value. BigQuery does not cluster a BYTES column, so the sweep’s query reads the whole encryption_marker column and nothing else: 7 bytes a row, about 70 MB at 10 million rows.

Runnable example

The sweep_bigquery example runs the UPDATE above end to end, from the writes to the count of re-encrypted rows, against Cloud KMS and BigQuery. It writes the rows through the Storage Write API, and the UPDATE re-encrypts them straight after: DML can modify rows recently written through its gRPC interface.

Incident runbook

A key leaked, or may have: a service account key in a repository, a DEK in a log, a backup in the wrong bucket. Each scenario starts with the steps that contain it, and explains the case after them. Rehearse each on a staging keyring, on a schedule, and record how long propagation took.

Which scenario

What happened, or what the alert saysScenario
A plaintext DEK leaked, or may have, under a keyringA plaintext DEK leaked
A DEK of values encrypted without a keyring leakedA DEK of envelope values leaked
A principal got KMS rights it should not have, or the KMS audit log shows an Encrypt or a Decrypt by one that should notA KMS IAM over-grant
An encrypted DEK or a keyring record leakedAn encrypted DEK or the keyring record leaked
An ERROR for a refused record that moves backwards, or a version the job did not createA version the administrative job did not create
A keyring record was deleted or corrupted, or a WARN about a record gone from the storeThe keyring record was deleted or corrupted
The KMS is downA KMS outage
A tenant’s values must become unreadableA scope’s values must become unreadable

A plaintext DEK leaked

Or is suspected to have.

  1. mark_compromised(key_id, note): the version is flagged and, if active, replaced in one write by a version that is active at once. The replacement skips the staged wait on purpose: encrypting under the leaked key stops at each process’s next refresh, and a process that has not seen the replacement yet reloads its record once, rate-limited, when it meets a value under it. When the KMS cannot encrypt a new DEK, the flag lands alone and encrypt fails with NoActiveVersion; once the KMS answers, rotate and promote_now at once, since nothing encrypts under the purpose meanwhile, or promote_now the pending version if the purpose has one. promote would refuse with PromotionTooEarly for up to record_ttl from the staging. A pending version itself is never compromised: destroy it instead;
  2. every process stops using the key within the bound of the record cache, and its DEK is evicted from the DEK cache. With the default Block policy values under the version stop decrypting through decrypt. Set Allow for the time of the sweep if availability matters more, and be aware the leaked DEK can forge values under its id meanwhile;
  3. sweep the records in the compromised version’s range, see Records under a version, reading them with decrypt_with_trust, and decide per record on the values read through the compromised version, see The trust of re-encrypted values. Run the range query again once every process has had time to refresh its record, for the writes of processes that had not seen the flag yet;
  4. export the BigQuery keysets again: a Readable keyset leaves the compromised version out. Delete the Single keyset of the compromised version once the sweep is done;
  5. retire and later destroy the version as in Retiring the old version.

Rotation protects nothing already copied: backups, point-in-time recovery and data exports still hold values the leaked DEK decrypts. Treat them as exposed and revoke the secrets inside them.

A DEK of envelope values leaked

Without a keyring. A DEK that leaked decrypts every value encrypted under it, and a KEK rotation does not change that. With a per-call envelope it is the DEK of one value, and with store-less DEK reuse of every value the writer encrypted until it renewed the DEK.

  1. stop encrypting under it: a store-less writer renews its DEK after invalidate of that DEK, or clear, on its envelope’s DEK cache, in every process, and the DEK is invalidated in every DEK cache that holds it, see The DEK lives in the cache;
  2. read each value under it with decrypt and encrypt it again with encrypt, which takes a new DEK, and write it back only where the stored bytes are still the ones read;
  3. a DEK the application keeps itself, such as the key of One fixed key or a beacon key, is replaced by a key under a new key id, and the values or beacons under the old one are encrypted or computed again;
  4. treat backups, point-in-time recovery and data exports as exposed: they still hold the values the leaked DEK decrypts, see What rotation does not protect.

A KMS IAM over-grant

  1. Fix the IAM binding, back to the split in KMS rights;
  2. rotate the KEK in the KMS and reencrypt_deks();
  3. with KMS data-access logs enabled in advance, list the Decrypt calls the wrong principal made: every encrypted DEK they decrypted is a leaked DEK, see A plaintext DEK leaked. Without those logs, every version is a leaked DEK.

An encrypted DEK or the keyring record leaked

Harmless by itself, since decrypting needs the KMS. If the attacker may also gain Decrypt on the KEK, follow the IAM over-grant steps. If the attacker may also write the keyring store, see A version the administrative job did not create and the store-writer threat in Keyring deployment.

A version the administrative job did not create

A version in the keyring record that the administrative job did not create.

  1. If the version is active, mark_compromised it, so that nothing new is encrypted under it from each process’s next refresh. If it is pending, destroy it;
  2. retire and destroy the version as in Retiring the old version, after a sweep if values were encrypted under it;
  3. check the KMS audit log for the Encrypt call that encrypted its DEK. None means its encrypted DEK was copied or relabelled from another version, of this keyring or of another under the same KEK, which the KMS decrypts as it would the original; one from a principal other than the administrative job is an IAM over-grant, see A KMS IAM over-grant;
  4. audit who can write the keyring store: the application has no write, and only the administrative job should.

How the case shows

This case starts from the ERROR event of a refused record that moves backwards, or from a version in the record that the administrative job’s log does not show. The event’s rule names the version that moved backwards, except the re-encryption epoch moved back, which names none: compare the versions of the record in the store with the job’s log to find the one it did not create. Either means that something other than the job wrote the record: a restore, which The keyring record was deleted or corrupted covers, or a writer of the store.

The keyring record was deleted or corrupted

The record is gone from the store, or unreadable.

  1. Restore the record from the store’s backup: Firestore point-in-time recovery, a PostgreSQL backup, or a noncurrent version of the Cloud Storage or S3 object. The encrypted DEKs inside are still valid under the KEK;
  2. repeat on the restored record every administrative call made after the copy was taken, from the administrative job’s log, before any process opens the keyring again;
  3. restart every process that took the deletion. It keeps the deleted record as the baseline of the id, and refuses the restored copy with RecordRegressed and an ERROR, because the copy revives versions the process holds destroyed. A process that starts after the restore has no baseline and takes the record.

A process that never saw the deletion, such as one whose revalidations were failing meanwhile, refuses an older copy as well, and logs an ERROR. Values are never lost with the record as long as a copy of it exists. Without any copy they are gone, so keep versioning on the bucket and back up the table.

What the processes do

A running process takes a record gone from the store as a shredded keyring, see Record cache. At its next revalidation, forced reload or administrative call it destroys every version of its cached record in memory, evicts the keyring’s keys from the DEK cache and logs a WARN, “The keyring store no longer holds the keyring record; every version is destroyed in this process”. Its handles then fail: encrypt with NoActiveVersion, decrypt with KeyVersionDestroyed, and reload with RecordMissing. Within the bound of how late a change is seen, an accidental deletion stops every process that holds the keyring. New processes fail at open with RecordMissing.

A shred writes the record with every version destroyed before it deletes it. A process that read that record logs an INFO for the deletion instead, and the process that ran the shred logs nothing. A process that first reads the store after the delete, such as one without push, logs the WARN for a shred too, so the WARN does not tell an accidental deletion from an erasure by itself.

A record that fails to parse or validate is a failed read instead: a running process keeps its cached record and logs the WARN of a failed revalidation, and new processes fail at open with RecordInvalid.

A KMS outage

DEKs in the cache serve reads and writes until their TTL. A longer DEK cache TTL buys time at the cost of a longer life of plaintext keys in memory. No decryption, encryption or rotation succeeds until the KMS returns, and errors carry the provider’s message. mark_compromised still lands the flag.

A scope’s values must become unreadable

To make a scope’s values unrecoverable on purpose, destroy the keys that decrypt them: the KEK’s versions with a KEK per scope, or KeyringAdmin::dangerously_shred() under a shared KEK. The procedure, what a shred leaves behind and how late each process takes it are in Erase one customer’s data for good.

Protect the keyring record

A keyring record decides which key versions read and which encrypt. Without a signature, its integrity rests on the access control of the keyring store: whoever can write the record can re-activate a compromised version, clear a flag or point a version at another DEK. Under an asymmetric KEK, which encrypts for anyone holding its public key, a writer can also plant a DEK of its own. A signed record closes these: the administration signs every record it writes, and every application refuses a record that no key it trusts has signed. See Signing the keyring record.

Roll out

An existing deployment moves in this order, and each step is safe to deploy before the next:

  1. Administrative binaries that know record signatures. An administrative write by a version without them rewrites the record from its own fields and removes the signature, see Readers before producers;
  2. the signing key’s public half to every registry, as VerifyIfSigned(keys). Records without a signature still read, and a signed one verifies from its first write;
  3. a signing administration, and sign_record on every keyring;
  4. Required on every application and on the administration.

The keys come from the application’s configuration, a JWK Set or the public key of the signing KMS key. They never come from the store or the record:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider, LocalSigningKeyName, LocalSigningProvider};
use kms_aead::signing::{Signer, SigningAlgorithm, VerifyingKeySet};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions, RecordSignaturePolicy,
};

const TENANT: KeyringId = KeyringId::from_static("tenant-42");

fn local_kek() -> Result<LocalKmsProvider<Ring>, Box<dyn std::error::Error>> {
    Ok(LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenants".to_string())?)?)
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let store = MemoryKeyringStore::new();
let before = KeyringRegistry::<_, Ring>::new(store.clone(), KeyringRegistryOptions::new())?;
before.create(local_kek()?, TENANT, KeyringAlgorithms::new()).await?;
// A KMS signing provider in production, see "Publish a rate sheet or a release anyone can verify"
let signer = Signer::<_, Ring>::new(LocalSigningProvider::<Ring>::ephemeral(
    LocalSigningKeyName::try_from("records".to_string())?,
    SigningAlgorithm::Ed25519,
)?)
.await?;
let keys = VerifyingKeySet::new([signer.verifying_key().clone()])?;

// Step 2: the administration's registry trusts the key and still reads unsigned records
let administration = KeyringRegistry::<_, Ring>::new(
    store.clone(),
    KeyringRegistryOptions::new()
        .with_record_signatures(RecordSignaturePolicy::VerifyIfSigned(keys.clone())),
)?;

// Step 3: sign the record as it is, with no other change
let admin = administration
    .admin(local_kek()?, TENANT)
    .await?
    .with_record_signer(signer)?;
admin.sign_record().await?;

// Step 4: an application that refuses a record no trusted key has signed
let application = KeyringRegistry::<_, Ring>::new(
    store,
    KeyringRegistryOptions::new().with_record_signatures(RecordSignaturePolicy::Required(keys)),
)?;
application.open(local_kek()?, TENANT).await?;
before.shutdown(None).await;
administration.shutdown(None).await;
application.shutdown(None).await;
Ok(())
}

A new keyring is signed from its first write with create_signed or open_or_create_signed. The administration re-signs the record on every write it makes: rotate, promote, dangerously_shred() and the rest need the signer’s KMS right, cloudkms.cryptoKeyVersions.useToSign on Cloud KMS. Under Required, a registry writes no record without a signer: create, open_or_create where it would create the record, and every write of an administration without a signer fail with RECORD_SIGNER_MISSING before any KMS call or store write. open_or_create reads the store once first, and refuses only when that read finds no record.

Rotate the signing key

Add the new public key to every registry’s set first, then run sign_record on every keyring with the new signer. Remove the old key from the sets once every keyring is signed by the new one. The rotation of the key itself is that of Publish a rate sheet or a release anyone can verify.

What a signature closes

  • a store writer without the signing key cannot change a record that applications verify: a cleared compromised flag, a re-activated version or a DEK planted under an asymmetric KEK fails with RECORD_SIGNATURE_INVALID, before any field of the record is used and before any KMS call;
  • under Required, an unsigned record fails with RECORD_UNSIGNED, so a keyring that was never signed, or whose signature a writer stripped, is not read.

What only Required closes

Under VerifyIfSigned, a running process that holds a signed record refuses a later unsigned one with RECORD_SIGNATURE_REMOVED, keeps the record it holds and logs an ERROR. The refusal is sticky: it lasts as long as the process, and a process that starts after a writer stripped the signature has no record to compare with and reads whatever the store holds. Only Required protects those processes, and the keyring whose record was never signed. Run Required on every application once step 3 is done.

A signature proves that a signer wrote the record, and not that it is the latest. A store writer can restore an older signed record. Running processes refuse a record that moves a version backwards with RECORD_REGRESSED, and a process that has just started has nothing to compare with. Keep backups and the store’s version history to compare against, see Keyring deployment.

Stop signing

Switch every reader to VerifyIfSigned, the administration’s registry included, write the record unsigned with dangerously_unsign_record on an administration without a signer, then restart the readers: the running ones refuse the unsigned record until they do. Under Required, dangerously_unsign_record fails with RECORD_SIGNER_MISSING.

What to watch for

  • Whoever may sign records and write the store may write any record. Give the signing right to the administration only, and read its audit log;
  • a keyring under an asymmetric KEK runs with Required on every application before the first DEK a public key encrypts, see Accept data from partners and devices that cannot read it back;
  • an administration without a signer is refused over a signed record with RECORD_SIGNER_MISSING, and under Required it writes nothing.

Full example available here.

Move envelope values to a keyring

An application that encrypted fields with KmsAeadEnvelope can move them to a keyring when it needs central rotation and retirement of keys, or BigQuery and Tink reads across rotations, see Keyring and field encryption. The values that KmsAeadEnvelope wrote, per call or store-less, move to keyring values in five steps. An EncryptionMarker is the 5 bytes a record stores beside its encrypted fields to name the key versions they are under, 0x01 and an epoch that counts re-encryptions, see The encryption marker:

  1. the model gains encryption_marker: EncryptionMarker, and every record without one reads as EncryptionMarker::ENVELOPE: through #[serde(default)], or a column default of its bytes, '\x0100000000', which is 0x01 and an epoch of 0;
  2. the field keeps its stored bytes, whose layout the marker names: envelope values under ENVELOPE, epoch 0, and keyring values under any other marker, since the epochs of a keyring start at 1;
  3. reads go through the marker: Keyring::decrypt_envelope_for_migration decrypts an envelope value, with the AAD and the algorithm the application used for it, and Keyring::decrypt a keyring value;
  4. the sweep’s query, encryption_marker < $1 with the current marker, finds every envelope record too, and the re-encryption encrypts it as keyring values through an encryptor and writes the marker of the encryptor’s record;
  5. once no record holds ENVELOPE, the read path drops its envelope branch.

A range query never matches a record whose marker is missing: Firestore skips a document without the field, and < in SQL is never true on NULL. A PostgreSQL column added with a default holds it in every existing row:

ALTER TABLE users ADD COLUMN encryption_marker BYTEA NOT NULL DEFAULT '\x0100000000';
CREATE INDEX users_encryption_marker ON users (encryption_marker);

A BigQuery column holds NULL in the rows already there until an UPDATE writes ENVELOPE into them:

ALTER TABLE users ADD COLUMN encryption_marker BYTES;
ALTER TABLE users ALTER COLUMN encryption_marker SET DEFAULT b'\x01\x00\x00\x00\x00';
UPDATE users SET encryption_marker = b'\x01\x00\x00\x00\x00' WHERE encryption_marker IS NULL;

The UPDATE in SQL of Sweeps on BigQuery does not decrypt an envelope value, so its WHERE leaves the envelope rows out with AND encryption_marker > b'\x01\x00\x00\x00\x00', and they go through the Rust sweep.

Firestore documents written before the marker get ENVELOPE written into them first, or the migration’s first sweep scans the whole collection and tests doc.encryption_marker < current on each, since #[serde(default)] reads a missing marker as ENVELOPE.

The sweep’s re-encryption branches on the marker. An envelope value is decrypted with the algorithm the application used for it and encrypted as a keyring value; a keyring value goes through Encryptor::reencrypt, and ReencryptOutcome::from(&reencrypted) turns its Option into the outcome. An envelope value names no key version, so its outcome has from_compromised: false:

let (email, outcome) = match StoredEmail::try_from(row)? {
    StoredEmail::Envelope(value) => {
        let email: Email = keyring
            .decrypt_envelope_for_migration(&envelope_aad(user), &value, ENVELOPE_ALGORITHM)
            .await?;
        let outcome = ReencryptOutcome::Reencrypted { from_compromised: false };
        (encryptor.encrypt(&aad, &email).await?, outcome)
    }
    StoredEmail::Keyring { value, .. } => {
        let reencrypted = encryptor.reencrypt(&aad, &value).await?;
        let outcome = ReencryptOutcome::from(&reencrypted);
        (reencrypted.map_or(value, |reencrypted| reencrypted.value), outcome)
    }
};

The keyring’s provider decrypts the envelope values, so they must have been encrypted by the keyring’s KEK. decrypt_envelope_for_migration reads Tink’s KMS envelope, the layout KmsAeadEnvelope writes. Values in a legacy layout, which kms-aead 0.29 and earlier wrote, fail with LEGACY_FORMAT: they are rewritten in place first with kms-aead 0.33, see Upgrading stored values. The layout of a value is always the marker’s, never inferred from its bytes.

decrypt_envelope_for_migration decrypts whatever encrypted DEK an envelope value carries, under the keyring’s KEK. It knows no key version, and so no compromised flag and no destroyed state: keep its branch in the read path for the migration only.

Full example available here, run it with cargo run -p kms-aead-keyring --example migrate --features ring,admin.

Stored values

This page specifies the types that carry what the library writes to a data store and reads back, and how they are stored. To encrypt the columns of a table, start with Encrypt personal data and secrets in your database. The bytes of each layout are in Values and DEKs.

Three types are involved:

  • Encrypted<T, F>: an encrypted value that decrypts to a T, in the layout of the format F;
  • Beacon<T>: a blind index of a T, stored beside its encrypted value for lookups;
  • Plaintext: the trait of every T, which fixes the bytes a value is encrypted as.

The T is a type of the application, such as an Email newtype, so a column names what it holds: Encrypted<Email, Envelope> and Beacon<Email>. Neither type holds a T, only the bytes to store.

Encrypted<T, F>

Every call that encrypts returns an Encrypted<T, F>. The format F comes from kms_aead::formats and fixes the layout of the bytes:

FormatHoldsWritten byRead bykey_id()Equality
Envelopethe value and its encrypted DEK, in Tink’s KMS envelopeKmsAeadEnvelope::encryptKmsAeadEnvelope::decryptnonone
Barethe AEAD output aloneKmsAeadEnvelope::encrypt_with_dek, AeadCipher::encrypt_bareKmsAeadEnvelope::decrypt_with_dek, AeadCipher::decrypt_barenonone
Randomizedthe AEAD output after a key idAeadCipher::encrypt, Encryptor::encryptAeadCipher::decrypt, Keyring::decryptyesnone
Deterministicthe AES-SIV output after a key idDeterministicCipher::encrypt, Encryptor::encrypt_deterministicDeterministicCipher::decrypt, Keyring::decrypt_deterministicyes== and Hash, in constant time
  • key_id() returns the KeyId that the Tink output prefix names, the key to decrypt the value with. The prefix is the byte 0x01 and the key id, at the start of the value. It is not authenticated: a changed key id fails to decrypt;
  • an Envelope value carries its encrypted DEK instead of a key id, and a Bare value names no key: the application keeps track of the key that decrypts it;
  • the randomised formats encrypt equal plaintexts into different values, so they have no ==. Compare value() to tell whether two values are the same stored bytes;
  • only Deterministic values are equal for equal plaintexts under one key and one AAD, which is what a lookup by the encrypted value needs, see Deterministic encryption;
  • Debug shows the length only.

See Formats of Encrypted for the layout and the shortest value of each format, and Values written by 0.29 and earlier for the legacy layouts, which the library refuses.

Bytes in and out

value() and into_value() return the bytes to store, and to_hex_string() returns them as lowercase hex. The only ways back are Encrypted::try_from for bytes and Encrypted::try_from_hex_string for hex in either case. Both check the bytes against the layout of F before any KMS call, so a truncated or foreign value fails when it is read, with INVALID_CIPHER_TEXT_FORMAT, UNKNOWN_CIPHER_TEXT_LAYOUT, INVALID_HEX, or LEGACY_FORMAT for a legacy layout. The check reads the framing only: a changed value fails to decrypt with DECRYPT.

use kms_aead::backends::Ring;
use kms_aead::formats::Randomized;
use kms_aead::{AeadAlgorithm, AeadCipher, Encrypted, KeyId};
use secret_vault_value::SecretValue;

fn main() -> kms_aead::KmsAeadResult<()> {
let cipher = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?;
let dek = cipher.generate_dek()?;
let encrypted: Encrypted<SecretValue, Randomized> =
    cipher.encrypt(KeyId::new(1), b"users/1042/token", &SecretValue::from("token"), &dek)?;

// The key the prefix names
assert_eq!(encrypted.key_id(), KeyId::new(1));

// Hex for a text column, bytes for a binary one
let stored_hex: String = encrypted.to_hex_string();
let stored: Vec<u8> = encrypted.into_value();

let from_bytes = Encrypted::<SecretValue, Randomized>::try_from(stored)?;
let from_hex = Encrypted::<SecretValue, Randomized>::try_from_hex_string(&stored_hex)?;
assert_eq!(from_bytes.value(), from_hex.value());

// A prefix with nothing after it is no randomised value
assert!(Encrypted::<SecretValue, Randomized>::try_from(vec![0x01, 0, 0, 0, 1]).is_err());
Ok(())
}

Storing

Encrypted is stored as bytes, and read back through TryFrom, so a malformed stored value fails in the decode:

  • serde, in every build: Serialize and Deserialize, a bytes value in Firestore and an array of numbers in serde_json;
  • postgres: ToSql and FromSql of postgres-types, for tokio-postgres, as BYTEA, and a slice as BYTEA[] for = ANY($1);
  • sqlx: sqlx’s Type, Encode, Decode and PgHasArrayType for PostgreSQL, as BYTEA. It depends on sqlx-core and sqlx-postgres only, so the application chooses sqlx’s runtime and TLS stack.

A field of a serde record, here in JSON:

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, KmsAeadEnvelope};
use serde::{Deserialize, Serialize};
use kms_aead::{KmsAeadResult, Plaintext};
use secret_vault_value::SecretValue;
#[derive(Debug, Clone, PartialEq)]
struct Email(String);
impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> { self.0.to_plaintext() }
    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

#[derive(Serialize, Deserialize)]
struct User {
    id: i64,
    email: Encrypted<Email, Envelope>,
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

let email = Email("alice@example.com".to_string());
let user = User {
    id: 1042,
    email: envelope.encrypt(b"users/1042/email", &email).await?,
};

let json: String = serde_json::to_string(&user)?;
let read_back: User = serde_json::from_str(&json)?;
let decrypted: Email = envelope.decrypt(b"users/1042/email", &read_back.email).await?;
assert_eq!(decrypted, email);
Ok(())
}

A BYTEA column, with sqlx:

use kms_aead::formats::Envelope;
use kms_aead::Encrypted;
use sqlx::PgPool;

#[derive(Clone)]
struct Email(String);
async fn store(pool: &PgPool, id: i64, email: &Encrypted<Email, Envelope>) -> sqlx::Result<()> {
    sqlx::query("INSERT INTO users (id, email) VALUES ($1, $2)")
        .bind(id)
        .bind(email)
        .execute(pool)
        .await?;
    Ok(())
}

async fn load(pool: &PgPool, id: i64) -> sqlx::Result<Encrypted<Email, Envelope>> {
    sqlx::query_scalar("SELECT email FROM users WHERE id = $1")
        .bind(id)
        .fetch_one(pool)
        .await
}

A TEXT column, as hex, with tokio-postgres:

use kms_aead::formats::Envelope;
use kms_aead::Encrypted;
use tokio_postgres::Client;

#[derive(Clone)]
struct Email(String);
async fn store(
    client: &Client,
    id: i64,
    email: &Encrypted<Email, Envelope>,
) -> Result<(), tokio_postgres::Error> {
    let email_hex: String = email.to_hex_string();
    client
        .execute("UPDATE users SET email_hex = $1 WHERE id = $2", &[&email_hex, &id])
        .await?;
    Ok(())
}

async fn load(
    client: &Client,
    id: i64,
) -> Result<Encrypted<Email, Envelope>, Box<dyn std::error::Error>> {
    let row = client
        .query_one("SELECT email_hex FROM users WHERE id = $1", &[&id])
        .await?;
    let email_hex: String = row.try_get("email_hex")?;
    Ok(Encrypted::<Email, Envelope>::try_from_hex_string(&email_hex)?)
}

Hex takes twice the space of the bytes. Use it where the data store has no binary type, or where the value travels as text.

Beacon<T>

A beacon, or blind index, is a truncated HMAC-SHA256 of a T’s plaintext under a beacon key. It is stored beside the field’s encrypted value, which stays randomised, and a data store matches it by equality without the plaintext or a decryption. The bytes are 0x01, the key id and the truncated HMAC, see Beacons.

  • key_id() returns the KeyId of the beacon key that calculated it, so that a column holds beacons of two keys during a re-index;
  • BeaconBits sets how many bits of the HMAC a beacon keeps, see Bits. BeaconBits::new returns None outside the range;
  • value() and into_value() return the bytes to store, and Beacon::try_from reads them back, failing with INVALID_BEACON_FORMAT on bytes of another layout;
  • == and Hash compare the bytes, == in constant time, and Debug shows the key id only.
use kms_aead::backends::Ring;
use kms_aead::{Beacon, BeaconAlgorithm, BeaconBits, BeaconMac, KeyId};
use kms_aead::{KmsAeadResult, Plaintext};
use secret_vault_value::SecretValue;
#[derive(Debug, Clone, PartialEq)]
struct Email(String);
impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> { self.0.to_plaintext() }
    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

fn main() -> KmsAeadResult<()> {
let mac = BeaconMac::<Ring>::new(BeaconAlgorithm::HmacSha256)?;
let beacon_key = mac.generate_dek()?;

let email = Email("alice@example.com".to_string());
let beacon: Beacon<Email> =
    mac.beacon(KeyId::new(1), b"users/email", BeaconBits::DEFAULT, &email, &beacon_key)?;

// [0x01][key id: 4 bytes][16 bits of HMAC: 2 bytes]
assert_eq!(beacon.key_id(), KeyId::new(1));
assert_eq!(beacon.value().len(), 7);

let read_back = Beacon::<Email>::try_from(beacon.value().to_vec())?;
assert_eq!(read_back, beacon);
Ok(())
}

Beacon<T> is stored as Encrypted is, as bytes, with serde and the postgres and sqlx features. A lookup matches the column by equality, so it gets an ordinary index:

CREATE TABLE users (
  id BIGINT PRIMARY KEY,
  email BYTEA NOT NULL,
  email_beacon BYTEA NOT NULL
);
CREATE INDEX users_email_beacon ON users (email_beacon);
use kms_aead::formats::Envelope;
use kms_aead::{Beacon, Encrypted};
use tokio_postgres::Client;

#[derive(Clone)]
struct Email(String);
// The candidates for one email, which the application decrypts and filters
async fn candidates(
    client: &Client,
    beacon: &Beacon<Email>,
) -> Result<Vec<Encrypted<Email, Envelope>>, tokio_postgres::Error> {
    let rows = client
        .query("SELECT email FROM users WHERE email_beacon = $1", &[beacon])
        .await?;
    rows.iter().map(|row| row.try_get("email")).collect()
}

See Beacons for calculating beacons with a KMS-encrypted beacon key, the context, normalisation and key rotation, and Beacons in kms-aead-keyring for beacons under key versions. Find a user by an encrypted email puts them to use.

Plaintext

Plaintext maps a type to the bytes it is encrypted as, and back. Every T of Encrypted<T, F> and Beacon<T> implements it. An application type implements it by mapping to one of the built-in types, such as a newtype over String that is encrypted as the same UTF-8 bytes:

use kms_aead::{KmsAeadResult, Plaintext};
use secret_vault_value::SecretValue;

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

fn main() -> KmsAeadResult<()> {
let email = Email("alice@example.com".to_string());
assert_eq!(Email::from_plaintext(email.to_plaintext()?)?, email);
Ok(())
}

A newtype over SecretValue is written the same way:

use kms_aead::{KmsAeadResult, Plaintext};
use secret_vault_value::SecretValue;

#[derive(Debug, Clone, PartialEq)]
struct Email(SecretValue);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        Ok(self.0.clone())
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        Ok(Email(plaintext))
    }
}

fn main() -> KmsAeadResult<()> {
let email = Email(SecretValue::from("alice@example.com"));
let decrypted: Email = Email::from_plaintext(email.to_plaintext()?)?;
assert_eq!(decrypted.0.as_sensitive_str(), "alice@example.com");
Ok(())
}

It differs from the String newtype as follows:

  • the decrypted value is zeroised on drop, and Debug prints *** instead of it;
  • text is encrypted as the same bytes as through String, so AEAD.DECRYPT_STRING still reads it;
  • there is no UTF-8 check on read, so bytes that are not UTF-8 decrypt without an error;
  • the text is reached through SecretValue’s accessors rather than as a &str: as_sensitive_str(), which panics on bytes that are not UTF-8, or sensitive_value_to_str(), which returns an error.

SecretValue suits values that are secrets or personal data, and String values that are used as text throughout.

The built-in types encode as follows. The encodings are fixed, so that other readers of the same values, such as BigQuery’s AEAD.DECRYPT_STRING, decode them:

TypeEncoding
StringUTF-8
Vec<u8>, SecretValuethe bytes themselves
i32, i64, u32, u64decimal ASCII, which SQL reads with CAST
JsonEncoded<T>the compact JSON of any serde type

A stored value is as long as its encoding plus a fixed overhead, so whoever reads the store reads the length of the plaintext: the number of digits of an integer, the length of a string. There is no impl for bool for this reason, since true and false differ in length. A type whose length must not show pads its encoding to a fixed length in its own Plaintext impl.

  • decrypt fails with INVALID_PLAINTEXT when the plaintext is not an encoding of T, and the error never quotes the bytes;
  • the decrypted value belongs to the application, which protects it. Only SecretValue as T is zeroised on drop; String and Vec<u8> take over the decrypted buffer without a copy;
  • a beacon is the HMAC of the encoded bytes, so normalisation, such as lowercasing an email, is the newtype’s job, see Beacons.

JsonEncoded<T> encrypts a structured value of any serde type as its compact JSON, which BigQuery reads with AEAD.DECRYPT_STRING and its JSON functions:

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, JsonEncoded, KmsAeadEnvelope};
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct Address {
    street: String,
    city: String,
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

let address = JsonEncoded::new(Address {
    street: "Mannerheimintie 1".to_string(),
    city: "Helsinki".to_string(),
});
let encrypted: Encrypted<JsonEncoded<Address>, Envelope> =
    envelope.encrypt(b"users/1042/address", &address).await?;
let decrypted: JsonEncoded<Address> = envelope.decrypt(b"users/1042/address", &encrypted).await?;
assert_eq!(decrypted, address);
Ok(())
}

JSON that does not decode

A plaintext that is not the JSON of its type, such as a record written by an older version of the application, fails with INVALID_PLAINTEXT and logs a WARN event with an outline of the JSON. By default the outline shows the shape: the type of every value, the nesting, and where serde_json stopped reading. It shows no value and no length, since a length gives away a hidden boolean.

Finding the field that changed takes more. A type opts into it with a policy, the second type parameter of JsonEncoded: a type of the application’s own that implements JsonRedaction and sets the constants it needs. Redaction policies lists what each shows and how FieldPaths names a field.

use kms_aead::redaction::{FieldPaths, JsonRedaction};
use kms_aead::JsonEncoded;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Customer {
    id: String,
    email: String,
    plan: String,
    renewal_date: String,
}

struct CustomerLog;

impl JsonRedaction for CustomerLog {
    const FIELD_NAMES: bool = true;
    const SIZES: bool = true;
    const REVEALED_FIELDS: FieldPaths = FieldPaths::from_static(&["id", "plan"]);
}

type CustomerJson = JsonEncoded<Customer, CustomerLog>;

let customer = CustomerJson::from(Customer {
    id: "cus_4821".to_string(),
    email: "ada.lovelace@example.com".to_string(),
    plan: "team".to_string(),
    renewal_date: "2027-03-01".to_string(),
});

JsonEncoded::new builds a value under the default policy, and from a value of a type with a policy of its own. A record written when plan was a number logs this outline under the default policy:

{<key>: <string>, <key>: <string>, <key>: <number>, <key>: <string>}

and this under CustomerLog:

89 bytes: {"id": "cus_4821", "email": <string, 24 chars>, "plan": 2, "renewal_date": <string, 10 chars>}

The outline names the field and the value that differs, and shows the length of the email and nothing else of it. A plaintext is encrypted because it is secret, so a policy reveals codes and identifiers only. A revealed value goes to the logs whenever the JSON does not decode: never reveal personal data. kms_aead::json=off in an EnvFilter turns the event off. The event’s fields are in Spans and events. RedactedJson outlines any JSON the same way, with no encryption, see Log a webhook payload that failed to parse.

Full example available here.

Redaction policies

A policy P says what an outline shows. JsonEncoded<T, P> outlines the JSON that fails to decode under it, and RedactedJson::new::<P>(bytes) outlines any bytes under it, with no encryption, see Log a webhook payload that failed to parse. A policy is a type of the application’s own that implements JsonRedaction and sets the constants it needs. Each constant is off by default:

ConstantEffect on the outline
FIELD_NAMESshows the keys of objects, except the keys of DATA_KEYED_MAPS
DATA_KEYED_MAPSlists the objects whose keys are data, such as a map from an email to a balance, so their keys stay hidden; balances[] names the values of the map balances
SIZESshows the length of every hidden value and key, the length of the JSON and the line and column of the failure
REVEALED_FIELDSshows the values of the listed fields, and the names of the fields on the way to each

A path is the names of the fields joined by ., with [] after a field for every item of the array it holds, such as customer.plan or items[].sku, and [].id for the items of an array at the top level. A path takes in the whole value at its end. A field whose name has a ., [ or ] cannot be named. A malformed path is a compile error in the build that uses the policy.

Bytes that do not start as JSON are outlined by their class: empty, whitespace only, hex digits, base64-like text, text or binary data. The limits of an outline:

  • the outline is one line of printable ASCII, 4 KiB at most, whatever the input;
  • a revealed string is escaped, with ", \, <, > and every character outside printable ASCII written as JSON escapes, and cut after 64 bytes;
  • the items of an array with the shape of the item before them print as a count, such as <2 more of the same shape>, and an array prints 8 items of different shapes at most;
  • serde_json reads 128 levels of nesting at most.

Envelope encryption

KmsAeadEnvelope encrypts values under data encryption keys (DEKs) on the crypto backend it is built with, and encrypts the DEKs with the KEK of its provider. A call that makes no KMS call is not async, and every call opens one DEBUG span, see Spans and events.

This page specifies the calls of KmsAeadEnvelope. To encrypt the columns of a table, read Encrypt personal data and secrets in your database. To make fewer KMS calls, read Cut KMS calls with a DEK cache and DEK reuse. To rotate the KEK, read Rotate keys and re-encrypt values.

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{AeadAlgorithm, KmsAeadEnvelope, KmsAeadEnvelopeOptions};
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
// AES-256-GCM by default
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

// Or another algorithm
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::with_options(
    provider,
    KmsAeadEnvelopeOptions::new().with_algorithm(AeadAlgorithm::ChaCha20Poly1305),
)?;
let _ = envelope;
Ok(())
}

The value does not record the algorithm, so the writer and the reader of a value must be configured with the same one. The backend can differ, see Crypto backends. The default, AES-256-GCM, is read by every implementation of Tink, Google’s cryptography library, too, see Tink’s KMS envelope. Values that an older release encrypted under another default are covered by Default algorithm.

Over a provider that only encrypts, such as the PublicKeyKekProvider of a producer, the envelope has the calls that encrypt: encrypt, encrypt_with_dek and the generate_encrypted_* calls. The calls that decrypt a DEK or a value, from decrypt to the re-encryptions, need a provider that implements KmsAeadDecryptionProvider too, as every KMS provider does, and do not compile over one that does not, see KMS providers.

Encrypting values

encrypt encrypts a value under a new DEK, encrypts the DEK with one KMS call, and returns both in one Encrypted<T, Envelope>, where T is the type of the value. decrypt decrypts the DEK with one KMS call, decrypts the value and returns a T. A value with no type of its own is a SecretValue:

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, KmsAeadEnvelope};
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

let aad = b"orders/1042";
let encrypted: Encrypted<SecretValue, Envelope> = envelope
    .encrypt(aad, &SecretValue::from("4111 1111 1111 1111"))
    .await?;

// The bytes to store, and the value read back from them
let stored: Vec<u8> = encrypted.into_value();
let read_back = Encrypted::<SecretValue, Envelope>::try_from(stored)?;

let decrypted: SecretValue = envelope.decrypt(aad, &read_back).await?;
assert_eq!(decrypted, SecretValue::from("4111 1111 1111 1111"));
Ok(())
}

The bytes in and out of an Encrypted are in Stored values.

The value is in Tink’s KMS envelope format for every provider, so Tink’s KmsEnvelopeAead reads it with the same KMS key and algorithm, see Tink’s KMS envelope.

A new DEK comes from the backend’s CSPRNG (cryptographically secure random number generator), or from the KMS generator when the provider is configured to use one, see KMS random generators.

Typed fields

encrypt and decrypt take a value of any type that implements Plaintext, such as an application’s Email newtype, and the result is an Encrypted<T, Envelope> that names the type. The calls run in the envelope’s mode, a DEK per value or store-less DEK reuse, and decrypt through the envelope’s DEK cache, whatever the type. Plaintext, the bytes of an Encrypted and how serde, tokio-postgres and sqlx store it are in Stored values.

AAD

The AAD is authenticated but not encrypted: a value decrypts only with the AAD it was encrypted with, and a wrong AAD fails with DECRYPT. Use it to bind a value to its place, such as <table>/<row id>/<column>, so that a value copied into another row or column fails to decrypt.

The AAD is not stored in the value, so the reader rebuilds it from the same data. It is never logged or put in an error, but it is not secret either: keep secrets in the value itself.

The keyring takes a structured AAD instead of free bytes, built from the field and the row, see Why the AAD is structured.

Working with DEKs yourself

The *_with_dek and *_with_encrypted_dek calls let the application keep one DEK for many values and store the encrypted DEK apart from them, such as one DEK per tenant or per file. The values are Encrypted<T, Bare>, with no encrypted DEK in them.

use kms_aead::backends::Ring;
use kms_aead::formats::Bare;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, KmsAeadEnvelope};
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

// One KMS call: a new DEK and the same DEK encrypted
let (dek, encrypted_dek) = envelope.generate_encrypted_dek().await?;

// No KMS call: encrypt and decrypt with the plaintext DEK
let first: Encrypted<SecretValue, Bare> =
    envelope.encrypt_with_dek(b"files/1/chunk/0", &SecretValue::from("first"), &dek)?;
let second: Encrypted<SecretValue, Bare> =
    envelope.encrypt_with_dek(b"files/1/chunk/1", &SecretValue::from("second"), &dek)?;
let decrypted: SecretValue = envelope.decrypt_with_dek(b"files/1/chunk/0", &first, &dek)?;
assert_eq!(decrypted, SecretValue::from("first"));

// Later, with only the encrypted DEK: the envelope decrypts it with the KMS
let decrypted: SecretValue = envelope
    .decrypt_with_encrypted_dek(b"files/1/chunk/1", &second, &encrypted_dek)
    .await?;
assert_eq!(decrypted, SecretValue::from("second"));
Ok(())
}

The calls are:

  • generate_encrypted_dek: a new DEK and the same DEK encrypted, one KMS call;
  • encrypt_with_dek and decrypt_with_dek: with a plaintext DEK, no KMS call;
  • encrypt_with_encrypted_dek and decrypt_with_encrypted_dek: with an encrypted DEK, decrypted through the envelope’s DEK cache, so one KMS call per call without a cache.

Be aware of the number of values one DEK encrypts: every value takes a random 96-bit nonce, which bounds the count, see Nonces.

Storing encrypted DEKs

EncryptedDataEncryptionKey holds the bytes the provider returned, which also name the KMS key version where the KMS needs one to decrypt after a rotation. Store value() or to_hex_string(), and read them back with EncryptedDataEncryptionKey::from or try_from_hex_string():

use kms_aead::backends::Ring;
use kms_aead::providers::{KmsKeyVersion, LocalKekId, LocalKmsProvider};
use kms_aead::{EncryptedDataEncryptionKey, KmsAeadEnvelope};

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;
let (_dek, encrypted_dek) = envelope.generate_encrypted_dek().await?;

let stored: Vec<u8> = encrypted_dek.value().to_vec();
let read_back_encrypted_dek = EncryptedDataEncryptionKey::from(stored);

let stored_hex: String = encrypted_dek.to_hex_string();
let read_back_hex_encrypted_dek = EncryptedDataEncryptionKey::try_from_hex_string(&stored_hex)?;

assert_eq!(read_back_encrypted_dek, read_back_hex_encrypted_dek);

// The KEK version beside it, for the check before an old KEK version is disabled
let stored_kek_version: Option<String> = encrypted_dek.kek_version().map(KmsKeyVersion::to_string);
let read_back_kek_version: Option<KmsKeyVersion> =
    stored_kek_version.map(KmsKeyVersion::try_from).transpose()?;
let read_back_encrypted_dek = match read_back_kek_version {
    Some(kek_version) => read_back_encrypted_dek.with_kek_version(kek_version),
    None => read_back_encrypted_dek,
};
assert_eq!(read_back_encrypted_dek.kek_version(), encrypted_dek.kek_version());
Ok(())
}

An encrypted DEK that the provider has just returned carries in kek_version() the version of the KEK that encrypted it, as the KMS reported it. It is None under AWS KMS, whose Encrypt response names no key material, and wherever the KMS reported no version. Decryption never needs it, and neither value() nor to_hex_string() holds it, so an encrypted DEK read back from them has none. Stored beside the encrypted DEK, it shows without a KMS call which DEKs are still under an old KEK version, see The check. with_kek_version puts it back on the encrypted DEK read from the bytes.

Equality and hashing take the bytes alone, so an encrypted DEK read back without its KEK version is the same key, to the DEK cache and in a map, as the one the provider returned with it.

The encrypted DEK is the one Tink stores in its KMS envelope, so Encrypted::join of a bare value and its encrypted DEK is an Encrypted<T, Envelope> that Tink reads. See Encrypted DEKs for each provider’s bytes.

Re-encrypting DEKs

After a KEK rotation, a DEK stored before it keeps decrypting with the old KEK version only. Two calls move a stored DEK to the version the provider encrypts with, without decrypting any value:

  • reencrypt_dek takes an Encrypted<T, Envelope> and returns it with its DEK under the current version;
  • reencrypt_encrypted_dek takes an EncryptedDataEncryptionKey, for the DEKs stored apart from their values, such as those of the *_with_encrypted_dek calls, of beacons and of deterministic fields, and for a DEK that many values share.

Each call makes two KMS calls, a decryption and an encryption, and never goes through the DEK cache. A value or a DEK in a legacy layout fails with LEGACY_FORMAT, see Values written by 0.29 and earlier.

The order of a rotation, the sweep, the checks around the disable of the old version and the rollback are in Re-encrypt DEKs after a KEK rotation.

One fixed key

This page specifies the calls that encrypt under one key the application holds, in the layout that Tink, Google’s cryptography library, and BigQuery read. For the BigQuery side of a column, read Decrypt columns in BigQuery SQL or with Tink. A column that needs key rotation belongs under a keyring.

AeadCipher::encrypt encrypts a field under a key the application holds, in Tink’s layout for a key with the output prefix TINK: [0x01][key id: u32 BE] before the AEAD value, an Encrypted<T, Randomized>. DeterministicCipher::encrypt does the same for an Encrypted<T, Deterministic>. The key id is a KeyId, the application’s constant. Tink and BigQuery read the values with a keyset, Tink’s serialised list of keys and their ids, of the one key under that id:

use kms_aead::backends::Ring;
use kms_aead::cache::{DekCache, DekCacheOptions};
use kms_aead::formats::{Randomized, TinkKeyType, TinkKeyset};
use kms_aead::providers::{GcpKmsKeyRef, GcpKmsProvider};
use kms_aead::{
    AeadAlgorithm, AeadCipher, DataEncryptionKey, Encrypted, EncryptedDataEncryptionKey, KeyId,
    KmsAeadEncryptionProvider, KmsAeadResult, Plaintext,
};
use secret_vault_value::SecretValue;

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

// The id of the one key, in every value and in the keyset
const EMAIL_KEY: KeyId = KeyId::new(1);

async fn example() -> KmsAeadResult<()> {
let key_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);
let provider = GcpKmsProvider::new(&key_ref).await?;
let cipher = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?;
let cache = DekCache::new(DekCacheOptions::new())?;

// Once, by an administrative job: the key encrypted by Cloud KMS, stored in the settings
let (_, encrypted_dek): (DataEncryptionKey, EncryptedDataEncryptionKey) =
    cipher.generate_encrypted_dek(&provider).await?;

// On every write and read: the key decrypted through the cache, no KMS call while it is cached
let email = Email("alice@example.com".to_string());
let (encrypted, _) = cache
    .with_dek(&provider, &encrypted_dek, |dek| {
        cipher.encrypt(EMAIL_KEY, b"users/1042/email", &email, dek)
    })
    .await?;
let encrypted: Encrypted<Email, Randomized> = encrypted?;

let (decrypted, _) = cache
    .with_dek(&provider, &encrypted_dek, |dek| {
        cipher.decrypt(b"users/1042/email", &encrypted, dek)
    })
    .await?;
let decrypted: Email = decrypted?;
assert_eq!(decrypted, email);

// Once, for BigQuery: the keyset of the one key, encrypted by the same Cloud KMS key
let mut keyset = TinkKeyset::new(EMAIL_KEY);
let (added, _) = cache
    .with_dek(&provider, &encrypted_dek, |dek| {
        keyset.add_key(EMAIL_KEY, TinkKeyType::from(cipher.algorithm()), dek)
    })
    .await?;
added?;
let first_level_keyset: EncryptedDataEncryptionKey = provider
    .encrypt_data_encryption_key(&DataEncryptionKey::from(keyset.to_bytes()))
    .await?;
let _ = first_level_keyset;
Ok(())
}

BigQuery reads the column with KEYS.KEYSET_CHAIN over the encrypted keyset, passed as a BYTES query parameter, beside the key’s Tink URI as a STRING one, gcp-kms://projects/my-project/locations/europe-north1/keyRings/my-key-ring/cryptoKeys/my-key:

SELECT AEAD.DECRYPT_STRING(
  KEYS.KEYSET_CHAIN(@kms_key, @first_level_keyset),
  u.email,
  CONCAT('users/', CAST(u.id AS STRING), '/email'))
FROM users u;
  • BigQuery reads AES-256-GCM values with AEAD.DECRYPT_STRING and AEAD.DECRYPT_BYTES, and the AES-SIV values of DeterministicCipher with DETERMINISTIC_DECRYPT_STRING and DETERMINISTIC_DECRYPT_BYTES. KEYS.KEYSET_CHAIN decrypts with Cloud KMS only;
  • AeadCipher::decrypt reads the values Tink and BigQuery write under the same key and id. The caller picks the key by key_id(), which the prefix names without authenticating it;
  • a rotation needs a second key id, values of both ids in one column and a keyset of both keys. kms-aead-keyring keeps those versions.

DEK caching and reuse

Without a cache, every read of a value decrypts its DEK with one KMS call, and every encrypt encrypts a new DEK with another. The library has two ways to make fewer KMS calls:

  • DekCache, a cache of decrypted DEKs, which serves repeated reads of values under the same DEK without the KMS;
  • store-less DEK reuse, with a DekReusePolicy, where one DEK encrypts many values, so a write calls the KMS only when the DEK is renewed.

This page specifies both, with their defaults and limits. To choose between them for a workload and to read the KMS call counts they save, read Cut KMS calls with a DEK cache and DEK reuse first.

DEK cache

kms_aead::cache::DekCache holds plaintext DEKs a provider decrypted, keyed by the provider’s KEK and the encrypted DEK’s bytes. A per-call envelope has no cache unless the options give it one:

use kms_aead::backends::Ring;
use kms_aead::cache::{DekCache, DekCacheOptions};
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{KmsAeadEnvelope, KmsAeadEnvelopeOptions};
use std::num::NonZeroUsize;
use std::time::Duration;

fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let cache = DekCache::new(
    DekCacheOptions::new()
        .with_ttl(Duration::from_secs(5 * 60))
        .with_max_entries(NonZeroUsize::new(10_000).expect("not zero")),
)?;

let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::with_options(
    provider,
    KmsAeadEnvelopeOptions::new().with_dek_cache(cache.clone()),
)?;
let _ = envelope;
Ok(())
}

decrypt, beacon and the *_with_encrypted_dek calls decrypt through the envelope’s cache, and a store-less encrypt keeps its DEK there. Clone shares the same cache, so one cache may serve several envelopes and several KEKs: an entry serves only a lookup that names the same KEK, and a key decrypted under one KEK never reaches a caller with the provider of another. A lookup, through DekCache::with_dek or an envelope call that decrypts, needs a KmsAeadDecryptionProvider, so the envelope of a producer over a PublicKeyKekProvider puts its DEK in a cache it shares and reads back only its own store-less DEK from it, to encrypt with it.

The cache:

  • serves an entry for its TTL after it was inserted, however often it is used, 15 minutes by default;
  • holds at most max_entries entries, 1024 by default, and evicts the oldest entry past it;
  • makes one provider call for concurrent misses of the same key, and every caller receives its result, the key or the error;
  • keeps no entry for a failed decryption, so during a KMS outage every call fails as fast as the KMS does;
  • zeroises a key when its entry leaves the cache: once it is evicted, invalidated, cleared, or purged after it expired.

DekCache::disabled() holds nothing, and every lookup calls the provider. It is what a per-call envelope has by default.

Sizing

Size max_entries above the number of distinct DEKs read per TTL. With per-call envelopes every value has its own DEK, so a cache helps only values read more than once within the TTL. With store-less writers the number of DEKs is the number of writers times the renewals per TTL, which is small.

A longer TTL saves more KMS calls, and keeps DEKs in memory for longer, see Key lifetime.

Invalidation

A disabled KMS key or a revoked IAM grant reaches the cached keys only when their entries expire. To drop one at once, invalidate it with the envelope’s own KEK:

use kms_aead::backends::Ring;
use kms_aead::cache::{DekCache, DekCacheOptions};
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{KmsAeadEnvelope, KmsAeadEnvelopeOptions};
use kms_aead::KmsAeadEncryptionProvider;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::with_options(provider,
    KmsAeadEnvelopeOptions::new().with_dek_cache(DekCache::new(DekCacheOptions::new())?))?;
let (_dek, encrypted_dek) = envelope.generate_encrypted_dek().await?;

// One encrypted DEK
envelope
    .dek_cache()
    .invalidate(envelope.provider().kek(), &encrypted_dek);

// Every DEK
envelope.dek_cache().clear();
Ok(())
}

Pass envelope.provider().kek() to invalidate, with the KmsAeadEncryptionProvider trait in scope: a KekRef built by hand that differs from it matches no entry.

Key lifetime

The cache runs no thread and no task of its own. Expired entries are dropped at the next call on the cache, at purge_expired, or when the last clone of the cache is dropped. With no calls, the bytes of an expired key stay in memory. An application whose process can sit idle while the cache holds keys, and that needs the TTL to bound their lifetime in memory, calls purge_expired on a timer of its own:

use kms_aead::cache::{DekCache, DekCacheOptions};
fn example() -> kms_aead::KmsAeadResult<()> {
let cache = DekCache::new(DekCacheOptions::new())?;

let purged = cache.clone();
tokio::spawn(async move {
    let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
    loop {
        interval.tick().await;
        purged.purge_expired();
    }
});
Ok(())
}

A key reaches the caller only inside the closure of DekCache::with_dek, and stays intact until the closure returns, whatever leaves the cache meanwhile. The closure must not keep a copy of the key: a copy taken out of it outlives the cache’s control of its lifetime.

Store-less DEK reuse

A KmsAeadEnvelope with a DekReusePolicy encrypts many values under one DEK and renews it at the first encryption past max_age, past max_uses or past max_bytes, whichever comes first. A renewal makes one KMS encrypt call. Each value still carries its encrypted DEK in Tink’s KMS envelope, so nothing is stored apart from the values, and values under earlier DEKs stay readable.

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{DekReusePolicy, Encrypted, KmsAeadEnvelope, KmsAeadEnvelopeOptions};
use secret_vault_value::SecretValue;
use std::num::NonZeroU64;
use std::time::Duration;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::with_options(
    provider,
    KmsAeadEnvelopeOptions::new().with_dek_reuse(
        DekReusePolicy::new()
            .with_max_age(Duration::from_secs(60 * 60))
            .with_max_uses(NonZeroU64::new(1_000_000).expect("not zero")),
    ),
)?;

// One KMS encryption for both values
let first: Encrypted<SecretValue, Envelope> =
    envelope.encrypt(b"events/1", &SecretValue::from("first")).await?;
let second: Encrypted<SecretValue, Envelope> =
    envelope.encrypt(b"events/2", &SecretValue::from("second")).await?;

// Read with any envelope over the same KEK and algorithm
let decrypted_first: SecretValue = envelope.decrypt(b"events/1", &first).await?;
let decrypted_second: SecretValue = envelope.decrypt(b"events/2", &second).await?;
assert_eq!(decrypted_first, SecretValue::from("first"));
assert_eq!(decrypted_second, SecretValue::from("second"));
Ok(())
}

The defaults are a max_age of 24 hours and a max_uses of 2^24. max_age must be longer than zero and max_uses at most 2^32, the bound for random 96-bit nonces under one key, see Nonces. Otherwise the envelope fails to build with INVALID_DEK_REUSE_POLICY.

Volume limit

max_bytes counts the plaintext bytes encrypted under the DEK. Its default depends on the algorithm:

AlgorithmDefault max_bytesMost allowed
AES-128-GCM, AES-256-GCM2^38 bytes (256 GiB)2^52 bytes
AES-256-GCM-SIVno limit beyond max_usesany
ChaCha20-Poly1305no limit beyond max_usesany

The default stays below the 2^38.5 bytes RFC 8446 allows under one AES-GCM key, and the most allowed is the 2^48 blocks of RFC 8452. AES-GCM-SIV and ChaCha20-Poly1305 have no volume bound beyond max_uses. The citations are in Data volume.

A max_bytes set in the policy replaces the default, under any algorithm. Above the most allowed, the envelope fails to build with INVALID_DEK_REUSE_POLICY.

A value that would take the count past max_bytes renews the DEK before it is encrypted. A value longer than max_bytes alone is encrypted under a new DEK of its own, as the per-call envelope does, and the current DEK stays in use for the next values.

The bounds count blocks of plaintext and AAD, and one more block per value, and max_bytes counts plaintext bytes only. At the default max_uses and an AAD of 16 bytes or less, the difference is at most 3 × 2^24 blocks beside the 2^34 blocks of the default.

The DEK lives in the cache

The envelope keeps only the encrypted DEK. Its plaintext lives in the envelope’s DekCache, which a store-less envelope always has: DekCache::new(DekCacheOptions::new()) unless the options give it another, and INVALID_DEK_REUSE_POLICY beside DekCache::disabled().

The first encryption after the DEK has left the cache renews it. So the DEK is renewed:

  • at the cache’s TTL, whatever max_age;
  • when the cache evicts it for capacity;
  • after invalidate with envelope.provider().kek(), or after clear.

A store-less encrypt never decrypts a DEK. A writer that renewed the DEK and finds it gone from the cache before it encrypts, evicted by a concurrent call or past a short TTL, encrypts with the DEK its renewal generated and puts it back in the cache, so a store-less writer over a PublicKeyKekProvider, which has no decryption, works as any other. An invalidate or clear that lands while a writer renews stops that writer from caching the new DEK: it encrypts with the DEK it generated, and the next writer renews.

In a cache shared with readers, size max_entries above the number of distinct DEKs read per TTL, or give the writer a cache of its own, otherwise reads evict the writer’s DEK and it renews more often than the policy says.

A writer that falls quiet leaves its DEK in memory until the cache’s next call or purge_expired, see Key lifetime. The values encrypted while the cache holds the DEK are readable by whoever reads the process’s memory in that window.

Deterministic encryption

Feature deterministic.

Randomised encryption gives a different cipher text every time, even for the same value. A deterministic algorithm gives equal cipher texts for equal values under one key and one AAD, so an encrypted column can be compared, joined or looked up by equality without decrypting it.

This page specifies DeterministicCipher and what deterministic encryption leaks. To find a row by an encrypted value, read Find a user by an encrypted email first. Under a keyring the same fields are in Deterministic fields.

The library provides AES-SIV (RFC 5297) with a 64-byte key, DeterministicAlgorithm::Aes256Siv. Its name for FromStr and Display is aes-256-siv. DeterministicCipher takes a backend, as AeadCipher does, and draws its keys from the backend’s CSPRNG (cryptographically secure random number generator). Every backend encrypts and decrypts with the RustCrypto aes-siv crate, so a value encrypted under one backend decrypts under any other.

AES-SIV is not a FIPS-approved mode. A FIPS deployment keeps deterministic fields outside its validated boundary, also on aws-lc-fips, where the keys come from the DRBG (deterministic random bit generator, the random source) of the FIPS module.

Deterministic encryption fits exact-match lookups where the leak of equality is acceptable. When a field only needs lookups and its stored value should stay randomised, a beacon fits instead, see Beacons.

What it leaks

Be aware what equal cipher texts tell a reader of the stored data, without any key:

  • Equality: which rows hold the same value;
  • Frequency: how often each value occurs. On a column with few distinct values, such as a country, a status or a yes/no answer, the most frequent cipher text is the most frequent value, and the values can be read back from public statistics.

And since there is no nonce, a leaked deterministic key lets its holder test candidate values against the whole column offline.

So deterministic encryption fits fields that are looked up by equality and have high entropy, such as emails and external ids. Do not use it:

  • for a column with few distinct values or a skewed distribution;
  • when equality itself is sensitive;
  • when the value is never looked up by equality: randomised encryption leaks nothing of the kind.

The AAD narrows what leaks: values are equal only under the same AAD, so a per-tenant AAD keeps equal values of two tenants apart.

An AAD that a lookup can rebuild names the field and never the row, so a deterministic value also decrypts in any other row of the same field. A deterministic field never decides identity or authorisation on its own; where identity matters, the check reads a randomised copy of the field, bound to the row by its AAD.

Usage

DeterministicCipher encrypts and decrypts with a DataEncryptionKey of DeterministicAlgorithm::key_len() bytes, 64 for AES-SIV, and refuses a key of another length with INVALID_KEY_LENGTH, such as the 16 or 32 bytes of a randomised algorithm’s key. The application keeps track of which key serves which algorithm, as kms-aead-keyring does with its key ids.

use kms_aead::backends::Ring;
use kms_aead::formats::Deterministic;
use kms_aead::{DeterministicAlgorithm, DeterministicCipher, Encrypted, KeyId};
use secret_vault_value::SecretValue;

fn main() -> kms_aead::KmsAeadResult<()> {
let cipher = DeterministicCipher::<Ring>::new(DeterministicAlgorithm::Aes256Siv)?;
let dek = cipher.generate_dek()?;

let aad = b"customers/email";
let first: Encrypted<SecretValue, Deterministic> =
    cipher.encrypt(KeyId::new(1), aad, &SecretValue::from("user@example.com"), &dek)?;
let second: Encrypted<SecretValue, Deterministic> =
    cipher.encrypt(KeyId::new(1), aad, &SecretValue::from("user@example.com"), &dek)?;

// Equal values give equal cipher texts, to look up by
assert_eq!(first, second);
let decrypted: SecretValue = cipher.decrypt(aad, &first, &dek)?;
assert_eq!(decrypted, SecretValue::from("user@example.com"));
Ok(())
}

An Encrypted<T, Deterministic> is Tink’s output prefix, which names the key by its KeyId, and then the output of RFC 5297, which starts with its synthetic IV: the AES-SIV tag that is derived from the plaintext and the AAD, and that makes equal inputs give equal values. The layout is in Formats of Encrypted. Tink, Google’s cryptography library, and BigQuery read it with a keyset of that key, see One fixed key. Its equality compares in constant time, and its Debug prints only the length, since the bytes tell which values are equal.

Keys encrypted by a KMS

The envelope generates and decrypts deterministic keys with its provider:

use kms_aead::backends::Ring;
use kms_aead::formats::Deterministic;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{DeterministicAlgorithm, DeterministicCipher, Encrypted, KeyId, KmsAeadEnvelope};
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;
let algorithm = DeterministicAlgorithm::Aes256Siv;

// A new key, and the same key encrypted, to store
let (dek, encrypted_dek) = envelope.generate_encrypted_deterministic_dek(algorithm).await?;

// Later: decrypt the stored key
let decrypted_dek = envelope.decrypt_deterministic_dek(algorithm, &encrypted_dek).await?;

let cipher = DeterministicCipher::<Ring>::new(algorithm)?;
let encrypted: Encrypted<SecretValue, Deterministic> =
    cipher.encrypt(KeyId::new(1), b"aad", &SecretValue::from("value"), &dek)?;
let decrypted: SecretValue = cipher.decrypt(b"aad", &encrypted, &decrypted_dek)?;
assert_eq!(decrypted, SecretValue::from("value"));
Ok(())
}

decrypt_deterministic_dek calls the provider every time and does not go through the envelope’s DEK cache. To cache deterministic keys, use DekCache::with_dek, which holds the keys of both kinds of algorithm.

DeterministicCipher::generate_encrypted_dek does the same with any provider.

Beacons

A beacon, or blind index, finds rows by a field’s value without decrypting the column: an HMAC-SHA256 of the value under a beacon key, truncated, stored beside the encrypted field. A query calculates the beacon of the value it looks for and matches it by equality. Beacon<T> holds the bytes to store, and the beacon key is a 32-byte key encrypted by the KMS, as a DEK is.

This page specifies beacons: the calls, what a beacon leaks and the bits. To look a user up by an encrypted email from start to finish, read Find a user by an encrypted email first.

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{
    Beacon, BeaconAlgorithm, BeaconBits, BeaconMac, Encrypted, KeyId, KmsAeadEnvelope,
    KmsAeadResult, Plaintext,
};
use secret_vault_value::SecretValue;

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

// The application's id of its beacon key, which every beacon names
const EMAIL_BEACON_KEY: KeyId = KeyId::new(1);

impl Email {
    // The beacon of an email matches regardless of case
    fn new(email: &str) -> Self {
        Email(email.to_lowercase())
    }
}

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

// Once, by an administrative job: the beacon key, stored beside the application's settings
let (_, encrypted_dek) = BeaconMac::<Ring>::new(BeaconAlgorithm::HmacSha256)?
    .generate_encrypted_dek(envelope.provider())
    .await?;

// On every write: the field and its beacon
let email = Email::new("Alice@Example.com");
let encrypted: Encrypted<Email, Envelope> =
    envelope.encrypt(b"users/1042/email", &email).await?;
let beacon: Beacon<Email> = envelope
    .beacon(EMAIL_BEACON_KEY, b"users/email", BeaconBits::DEFAULT, &email, &encrypted_dek)
    .await?;

// A lookup: the beacon of the value looked for, then a decryption of each matching row
let probe: Beacon<Email> = envelope
    .beacon(
        EMAIL_BEACON_KEY,
        b"users/email",
        BeaconBits::DEFAULT,
        &Email::new("alice@example.com"),
        &encrypted_dek,
    )
    .await?;
assert_eq!(probe, beacon);
let decrypted: Email = envelope.decrypt(b"users/1042/email", &encrypted).await?;
assert_eq!(decrypted, email);
Ok(())
}
  • the context, users/email here, names the field and never a row, so that equal values in one field give equal beacons. A beacon of one field never matches a beacon of another;
  • the key id, a KeyId, is the application’s number for the beacon key, written into every beacon so that a column can hold beacons of two keys at once;
  • the beacon key is decrypted through the envelope’s DEK cache, as a DEK is.

Beacon<T> is stored as Encrypted is, with serde and the postgres and sqlx features, and read back through TryFrom, which checks its layout, see Stored values. See Values and DEKs for its bytes.

A message authentication code (MAC) over a value’s bytes, which is not truncated and never serves a lookup, is in Beacons and MACs.

What a beacon leaks

A beacon column leaks to anyone who reads it, without any key:

  • Equality: which rows are likely to hold the same value;
  • Frequency: how often each value occurs, as far as the bits tell values apart.

And a leaked beacon key lets its holder test candidate values against the whole column offline.

So beacons fit fields that are looked up and have many distinct values, such as emails and external ids. Do not use them for low-cardinality fields, such as a status, a country or a yes/no answer, whose values the frequencies give away.

Bits

BeaconBits sets how many bits of the HMAC a beacon keeps, 1 to 256; BeaconBits::DEFAULT is 16. With n distinct values in a column and b bits, about n / 2^b values share each beacon:

  • fewer bits: more values share a beacon, so a lookup returns more rows, which the application decrypts and filters by the plaintext. A column of short beacons leaks less;
  • more bits: fewer rows to filter, down to one per value once 2^b is far above n, and the column then leaks which rows hold equal values as a deterministic column does.

An equal beacon never proves an equal value: a lookup always decrypts the rows it found and compares the plaintexts. The bits enter the HMAC, so beacons of one value under different bits never match: after a change of a column’s bits, its stored beacons match no lookup until a re-index computes them again. The numbers of the default for a column of 1,000,000 emails are in Find a user by an encrypted email.

Normalisation

A beacon is the HMAC of the bytes the Plaintext type encodes, so Alice@Example.com and alice@example.com give different beacons unless the type normalises the value. Normalising is the application’s job: the newtype normalises when it is made, as Email::new lowercases above, and every write and every lookup goes through it.

BigQuery

BigQuery’s SQL has no HMAC-SHA256 with a KMS-encrypted DEK, so a query in BigQuery cannot calculate a beacon. It matches beacons the application calculated and passed in as query parameters.

Rotating a beacon key

Rotating a beacon key in store-less mode is manual. Generate the new key and keep both, write beacons under the new one, query with a beacon under each key until a re-index has rewritten every stored beacon, then drop the old key. Beacon::key_id tells which key wrote a stored beacon. kms-aead-keyring does this with key versions, see Beacons.

Streaming encryption

Feature stream.

The library encrypts a value of any length as a streamed value: a header, then chunks of 16 KiB, each one authenticated on its own and bound to its position. A writer encrypts a value whose length it does not know in advance, holding one chunk in memory. A reader decrypts any byte range by fetching only the chunks that cover it.

Streaming fits files, uploads, backups and other objects in a store that serves Range requests. Fields of a record are Encrypted values, see Stored values.

This page specifies the streaming calls. To store uploads and serve byte ranges of them, read Store customer uploads and serve byte ranges first. To encrypt an HTTP body as it streams, read Send a large export over HTTP, encrypted.

The value comes in three forms, which differ in the bytes in front of the Cobblestone message. That message is the salt, the key commitment and the chunks that every form shares, in the chunked encryption format that C2SP specifies, see Format.

  • the prefixed form starts with Tink’s output prefix, 0x01 and a key id, as every keyring value does. AeadCipher::stream_encryptor writes it, and it is the only form a keyring writes and reads;
  • the envelope form starts with the encrypted DEK, as Tink’s KMS envelope does, so the value decrypts with nothing stored beside it. KmsAeadEnvelope::stream_encryptor writes it;
  • the bare form is the Cobblestone message alone, for a caller that keeps the key id or the encrypted DEK itself. The _bare calls of AeadCipher and KmsAeadEnvelope write it.

Every form uses AES-256-GCM, so the DEK is 32 bytes. The header holds a key commitment: 32 bytes derived from the DEK, the salt and the AAD. The decryptor derives it again, and refuses a wrong key, a wrong AAD or a modified header with STREAM_KEY_COMMITMENT before it decrypts a chunk.

Encrypting and decrypting

A value that arrives as a Stream of Bytes, such as a request body or an object-store download, goes through two types that need no bridge to tokio’s I/O traits, and comes back out as a Stream. Each holds one chunk in memory, whatever the length of the value:

  • EncryptingStream takes a Stream of plaintext and yields the value: the header first, then one item per chunk, the final chunk when its source ends;
  • DecryptingStream takes the stored bytes after the header and yields the plaintext, one item per chunk, and only once the chunk is authentic. It reads its source to the end, which is the end of the value.

Both yield KmsAeadResult<Bytes>. A value that is cut, modified or extended ends in an error item, STREAM_LENGTH or DECRYPT, never in a clean end. The error is the last item. An error of the source is STREAM_IO. A source that is not Unpin goes through Box::pin.

The encryptor and the decryptor come from the cipher: AeadCipher::stream_encryptor and stream_decryptor make the prefixed form, stream_encryptor_bare and stream_decryptor_bare the bare one. A decryptor is made from the header and the DEK.

A value read from start to end needs no stored length. Every chunk but the last has the same stored size, a full chunk with its tag, and the last one is shorter. A chunk is decrypted as soon as a full stored chunk has arrived, and the bytes left when the source ends are the final chunk. The sizes are in Streamed values.

  • A value cut at a chunk boundary, or less than a tag (16 bytes) into a chunk, ends without that shorter chunk, STREAM_LENGTH;
  • a value cut further into a chunk, or followed by more bytes, ends in a final chunk that is not authentic, DECRYPT.

A ranged read does need the stored length: it fetches the chunks of a range without reading what comes before, so only the length tells it where the final chunk is and how long it is, see Reading a range.

use kms_aead::backends::Ring;
use kms_aead::{AeadAlgorithm, AeadCipher};
use std::sync::Arc;

use bytes::Bytes;
use futures::{stream, StreamExt, TryStreamExt};
use kms_aead::stream::{DecryptingStream, EncryptingStream, StreamFormat};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let cipher = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?;
let dek = cipher.generate_dek()?;
let body = stream::iter([Bytes::from_static(b"a request "), Bytes::from_static(b"body")])
    .map(Ok::<_, std::io::Error>);
let encryptor = cipher.stream_encryptor_bare(b"upload/7/file", &dek)?;
let stored: Vec<Bytes> = EncryptingStream::new(encryptor, body).try_collect().await?;
let stored = stored.concat();

let header_len = StreamFormat::Bare.header_len();
let header = &stored[..header_len];
let decryptor = cipher.stream_decryptor_bare(b"upload/7/file", header, &dek)?;
let after_header = stream::iter([Bytes::copy_from_slice(&stored[header_len..])]).map(Ok::<_, std::io::Error>);
let response: Vec<Bytes> = DecryptingStream::new(Arc::new(decryptor), after_header).try_collect().await?;
assert_eq!(response.concat(), b"a request body");
Ok(())
}

A caller that holds the whole stored value from its first byte, such as a download, does not split the header off: KmsAeadEnvelope and Keyring have decrypting_stream and decrypting_reader, which read the header from the front of the source, make the decryptor and return the stream or the reader positioned at the first chunk, see With an envelope and With a keyring.

Full example available here.

The tokio adapters

Two wrapper types and two functions put the encryptor and the decryptor on tokio’s AsyncWrite and AsyncRead. Each holds one chunk in memory, whatever the length of the value:

  • EncryptingWriter encrypts what is written to it and writes the value to a sink. Call shutdown on it: only the shutdown writes the final chunk;
  • DecryptingReader reads a value from a source positioned after the header and yields its plaintext;
  • encrypt_stream and decrypt_stream run a whole source through a writer or a reader into a sink.

A std::io::Error that a wrapper returns for a failure of the value, such as a chunk that is not authentic, carries the KmsAeadError as its inner error: error.get_ref() and downcast_ref::<KmsAeadError>() find it.

Reading a range

A ranged read has three steps:

  • plan_chunk_read on the value’s StreamFormat takes the stored length of the value, as the store reports it, and a plaintext range, and returns a ChunkReadPlan: the chunks that cover the range and the stored bytes to fetch. .. is the whole plaintext. It needs no key, so a stored length that the length rules refuse fails before any KMS call. StreamFormat::Prefixed and StreamFormat::Bare are the prefixed and bare forms, and EnvelopeStreamHeader::form is the form of an envelope value;
  • the caller fetches plan.ciphertext() from the store, a byte range counted from the start of the value;
  • decrypt_chunk_read on a decryptor takes the plan and the fetched bytes, and returns the plaintext of exactly the range asked for, as a Plaintext type: Vec<u8> or SecretValue.

One zip entry of 63 KB at offset 1,000,000 of a value of 5,000,000 bytes covers four chunks, and the read fetches 65,600 bytes. An entry that starts in the last byte of a chunk covers five chunks.

use kms_aead::backends::Ring;
use kms_aead::stream::StreamFormat;
use kms_aead::{AeadAlgorithm, AeadCipher};
use kms_aead::stream::encrypt_stream;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let cipher = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?;
let dek = cipher.generate_dek()?;
let plaintext = vec![7_u8; 5_000_000];
let source = &plaintext[..];

// Encrypting: the bare form, with a DEK the caller holds, from any `AsyncRead` such as a file
let encryptor = cipher.stream_encryptor_bare(b"backups/2026-10", &dek)?;
let mut stored = Vec::new();
encrypt_stream(encryptor, source, &mut stored).await?;

// Decrypting: the stored length goes into the plan, which needs no key, and the header comes from
// the store
let plan = StreamFormat::Bare.plan_chunk_read(stored.len() as u64, 1_000_000..1_064_512)?;
assert_eq!(plan.chunks(), 61..65);
assert_eq!(plan.ciphertext(), 1_000_456..1_066_056);

let fetched = &stored[plan.ciphertext().start as usize..plan.ciphertext().end as usize];
let decryptor = cipher.stream_decryptor_bare(
    b"backups/2026-10",
    &stored[..StreamFormat::Bare.header_len()],
    &dek,
)?;
let entry: Vec<u8> = decryptor.decrypt_chunk_read(&plan, fetched)?;
assert_eq!(entry, plaintext[1_000_000..1_064_512]);
Ok(())
}

Make one decryptor per request, in an Arc: its methods take &self, and the ranges, threads and DecryptingReader of that request share it. The header is read once per request and no range fetches it again. Do not cache the decryptor across requests: it decrypts until it is dropped, see Limits.

With an envelope

Streamed values come in the same modes as other values, an envelope or a keyring, see Choosing a mode. An envelope chooses and encrypts the DEK as encrypt does, and writes one of two forms:

  • stream_encryptor writes the envelope form, one object that holds everything a reader needs. A reader learns the header’s length from its first 4 bytes, the length w of the encrypted DEK, and every chunk sits 4 + w bytes after its place in the bare form. A KEK rotation rewrites every object;
  • stream_encryptor_bare writes the bare form and returns the encrypted DEK, which the application stores beside the object, such as in its metadata or its database row. The chunks sit at fixed offsets, and a KEK rotation re-encrypts the stored DEKs with reencrypt_encrypted_dek and leaves the objects as they are.
use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::KmsAeadEnvelope;
use kms_aead::stream::{encrypt_stream, EnvelopeStreamHeader};
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("backups".to_string())?)?;
let plaintext = vec![7_u8; 5_000_000];
let source = &plaintext[..];
let envelope = KmsAeadEnvelope::<_, Ring>::new(provider)?;

// Encrypting: the envelope form, with the encrypted DEK inside the value, from any `AsyncRead`
let encryptor = envelope.stream_encryptor(b"backups/2026-10").await?;
let mut stored = Vec::new();
encrypt_stream(encryptor, source, &mut stored).await?;

// Decrypting: the header's length from its first 4 bytes, then the header
let header_len = EnvelopeStreamHeader::header_len(&stored[..4])?;
let header = EnvelopeStreamHeader::try_from(&stored[..header_len])?;
let plan = header.form().plan_chunk_read(stored.len() as u64, 1_000_000..1_064_512)?;
let fetched = &stored[plan.ciphertext().start as usize..plan.ciphertext().end as usize];
let decryptor = envelope.stream_decryptor(b"backups/2026-10", &header).await?;
let entry: Vec<u8> = decryptor.decrypt_chunk_read(&plan, fetched)?;
assert_eq!(entry, plaintext[1_000_000..1_064_512]);
Ok(())
}

A caller that reads the value from its first byte fetches no header separately: decrypting_stream takes the stored value as a Stream of Bytes, and decrypting_reader as an AsyncRead. Each reads the first 4 bytes, w, and checks it before it reads on or calls the KMS, then reads the header and returns the adapter at the first chunk.

use bytes::Bytes;
use futures::{stream, StreamExt, TryStreamExt};
use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::stream::EncryptingStream;
use kms_aead::KmsAeadEnvelope;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("backups".to_string())?)?;
let envelope = KmsAeadEnvelope::<_, Ring>::new(provider)?;
let upload = stream::iter([Bytes::from_static(b"a request body")]).map(Ok::<_, std::io::Error>);
let encryptor = envelope.stream_encryptor(b"backups/2026-10").await?;
let stored: Vec<Bytes> = EncryptingStream::new(encryptor, upload).try_collect().await?;
let download = stream::iter(stored).map(Ok::<_, std::io::Error>);
// The download streams the object from its first byte to its last
let response = envelope.decrypting_stream(b"backups/2026-10", download).await?;
let plaintext: Vec<Bytes> = response.try_collect().await?;
assert_eq!(plaintext.concat(), b"a request body");
Ok(())
}

stream_decryptor_bare decrypts the bare form from its header and the stored encrypted DEK, see The DEK beside the object. Full example of reading a range from both forms available here.

With a keyring

The stream feature of kms-aead-keyring adds Encryptor::stream_encryptor, Keyring::stream_decryptor and, for a value served whole, Keyring::decrypting_stream and decrypting_reader, which read the header from the front of the source. The first two return the same StreamEncryptor and StreamDecryptor, in the prefixed form, under the active version for a write and under the version the header names for a read. The keyring applies its lifecycle states and its compromised_reads policy as decrypt does, and a FieldAad that carries an Interop is refused, since neither Tink nor BigQuery reads a streamed value.

The lifecycle states and the policy apply when the decryptor is made. A decryptor holds the key derived for its value, never the DEK, and keeps decrypting after the version is retired, destroyed or flagged compromised, and after a shred of the keyring, until it is dropped. Make it per request, as above, so that a shred takes effect for the next request. A request that serves only the whole value, with no ranges, calls decrypting_stream or decrypting_reader, which make their own decryptor.

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    EntityId, EntityKind, FieldName, FieldSpec, KeyringAlgorithms, KeyringId, KeyringRegistry,
    KeyringRegistryOptions,
};
use std::sync::Arc;

use kms_aead_keyring::stream::{
    ChunkReadPlan, DecryptingReader, EncryptingWriter, PrefixedStreamHeader, StreamDecryptor,
    StreamEncryptor, StreamFormat,
};
use tokio::io::AsyncWriteExt;
/// An object of an object store that serves `Range` requests, held in memory.
struct Object(Vec<u8>);
impl Object {
    async fn read(&self, range: std::ops::Range<u64>) -> std::io::Result<Vec<u8>> {
        Ok(self.0[range.start as usize..range.end as usize].to_vec())
    }
    async fn read_from(&self, offset: u64) -> std::io::Result<&[u8]> {
        Ok(&self.0[offset as usize..])
    }
    fn size(&self) -> u64 {
        self.0.len() as u64
    }
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("uploads".to_string())?)?;
let admin = registry
    .open_or_create(provider, KeyringId::from_static("tenant-42"), KeyringAlgorithms::new())
    .await?;
let keyring = admin.keyring();
let upload_id = EntityId::try_from("upload-7")?;
let upload = vec![7_u8; 1_200_000];
let mut body = &upload[..];
let mut object_writer = Vec::new();

const UPLOAD_FILE: FieldSpec = FieldSpec::new(
    EntityKind::from_static("upload"),
    FieldName::from_static("file"),
);

// Encrypting an upload: the length is not known in advance and nothing of the body is held whole
let aad = UPLOAD_FILE.aad(&upload_id);
let encryptor: StreamEncryptor<Ring> = keyring.encryptor().await.stream_encryptor(&aad).await?;
let mut writer = EncryptingWriter::new(encryptor, &mut object_writer);
tokio::io::copy(&mut body, &mut writer).await?;
writer.shutdown().await?;
let stored_len: u64 = writer.stored_len_written();
let object = Object(object_writer);
assert_eq!(object.size(), stored_len);

// Serving one zip entry: the plans first, from the store's size, so that a size the length rules
// refuse reaches neither the store nor the KMS
let last: ChunkReadPlan = StreamFormat::Prefixed.plan_final_chunk_read(object.size())?;
let plan: ChunkReadPlan = StreamFormat::Prefixed.plan_chunk_read(object.size(), 1_000_000..1_064_512)?;

// Then the header once and one decryptor per request, which reads the final chunk, so that the
// length is authentic before any range is served
let head: Vec<u8> = object.read(0..StreamFormat::Prefixed.header_len() as u64).await?;
let header = PrefixedStreamHeader::try_from(head.as_slice())?;
let decryptor: Arc<StreamDecryptor<Ring>> = Arc::new(keyring.stream_decryptor(&aad, &header).await?);
decryptor.decrypt_chunk_read::<Vec<u8>>(&last, &object.read(last.ciphertext()).await?)?;
let bytes: Vec<u8> = object.read(plan.ciphertext()).await?;
let entry: Vec<u8> = decryptor.decrypt_chunk_read(&plan, &bytes)?;

// The whole value as a response body, over the same decryptor
let body = DecryptingReader::new(
    decryptor.clone(),
    object.read_from(StreamFormat::Prefixed.header_len() as u64).await?,
);
assert_eq!(entry, upload[1_000_000..1_064_512]);
drop(body);
registry.shutdown(None).await;
Ok(())
}

A write stores the encryption marker of the encryptor’s record beside the object’s own record, as it does for fields, so that a sweep finds the object by the marker, see Sweeps.

Full example available here.

Driving the I/O yourself

StreamEncryptor and StreamDecryptor take bytes and return bytes, and read and write nothing themselves, so they run under any runtime; the adapters above are built on them. An application that reads its source with another runtime, or in a loop of its own, calls them directly.

An encryptor takes the plaintext in pieces of any size: the value is header(), the bytes every push returns, then the bytes finish returns. A decryptor decrypts the chunks of a plan from plan_chunk_read, as in Reading a range, and .. plans the whole value.

use kms_aead::backends::Ring;
use kms_aead::stream::StreamFormat;
use kms_aead::{AeadAlgorithm, AeadCipher};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cipher = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?;
let dek = cipher.generate_dek()?;
let mut encryptor = cipher.stream_encryptor_bare(b"backups/2026-10", &dek)?;
let mut stored = encryptor.header().to_vec();
for piece in [b"first piece, ".as_slice(), b"second piece".as_slice()] {
    stored.extend(encryptor.push(piece)?);
}
stored.extend(encryptor.finish()?);

let header = &stored[..StreamFormat::Bare.header_len()];
let decryptor = cipher.stream_decryptor_bare(b"backups/2026-10", header, &dek)?;
let plan = StreamFormat::Bare.plan_chunk_read(stored.len() as u64, ..)?;
let plaintext: Vec<u8> = decryptor.decrypt_chunk_read(&plan, &stored[plan.ciphertext().start as usize..])?;
assert_eq!(plaintext, b"first piece, second piece");
Ok(())
}

Full example available here.

Limits

Be aware of these when serving streamed values:

  • the stored length a ranged read plans with is the store’s word until the final chunk has been decrypted. A store that cuts an object inside a chunk and reports the shorter size passes the length rules and every range that stays clear of the cut chunk. A range counted from the end of the value needs the final chunk first. Read the final chunk through plan_final_chunk_read once per object before the first range, or keep the length and a hash of the plaintext in a record you trust and compare the end of the final chunk’s plaintext() with it;
  • DecryptingReader, DecryptingStream and decrypt_stream yield the plaintext of a chunk as soon as the chunk is authentic, so a value cut or modified further on has already given its earlier bytes out when the error comes. Write to a place you can discard. A reader stopped before its clean end has authenticated the chunks it yielded and nothing of the length;
  • the same three read their source to its end and decrypt the final chunk only then. Bytes after the value make its final chunk fail with DECRYPT, so a value inside a longer source goes through a source cut to its length, such as tokio’s AsyncReadExt::take, and a source that stays open after the value holds its final chunk back;
  • an EncryptingWriter dropped before its shutdown leaves a value that no reader decrypts whole;
  • a decryptor keeps the key derived for its value until it is dropped, and decrypts with it after a shred, a destroy or a compromised flag of its version. A decryptor cached across requests outlives them, so build one per request;
  • an encryptor, and an EncryptingWriter or EncryptingStream over it, keeps the key derived for its value until it is dropped: a compromised flag or a destroy of its version does not stop an upload in progress;
  • STREAM_IO names a failure of the source or the sink of encrypt_stream or decrypt_stream, or of the source of an EncryptingStream or a DecryptingStream. The retry is the whole stream again from the start, with a new encryptor or a fresh read of the source;
  • a streamed value is not an Encrypted<T, F>: it has no plaintext type and carries no signature or MAC. Origin or integrity that a party without the DEK can check is a detached Signature<T> or Mac<T> over a digest of the plaintext, see Signatures and MACs;
  • one DEK is an AES-256-GCM key for randomised values and the key of HMAC-SHA-512 for streamed values. A deployment that wants one key per primitive keeps a keyring for streamed values apart from the keyring of its fields;
  • a sweep re-encrypts a streamed value whole: decrypt it under the version it names and encrypt it again under the active one. The library has no helper for that.

The errors a streamed value adds are in Error handling.

Format

A streamed value is one message of C2SP chunked encryption, Cobblestone-256: keys derived with HKDF-SHA-512 (the key derivation function built on HMAC) and chunks of AES-256-GCM. C2SP is the Community Cryptography Specification Project, a home for small specifications that come with test vectors. The prefixed form puts Tink’s output prefix in front and the envelope form the encrypted DEK, so an implementation of Cobblestone-256, such as the cryptography.cobblestone module of pyca/cryptography, decrypts a value from the offset where the Cobblestone message starts, with the DEK. The Go package filippo.io/cobblestone implements Cobblestone-128 only, on AES-128-GCM, and reads none of these values. The bytes, the offsets, the length rules and the seeking rules are in Streamed values.

The library runs the 35 vectors of Project Wycheproof for the specification, in every form, on every backend, see c2sp_chunked_encryption_aes_256_gcm_test.json.

Signatures and MACs

The library signs an application’s bytes with an asymmetric key held by a KMS, or by the local KMS, and verifies the signature without the KMS: in Rust on any crypto backend, and in a browser with WebCrypto. Beside the signature it offers a MAC, a keyed hash, under a symmetric key version of a keyring, for integrity inside one trust domain. Signatures are Ed25519 and ECDSA on P-256 with SHA-256; MACs are HMAC-SHA256 and HMAC-SHA512. Neither hides the bytes, see Envelope encryption for that.

This page specifies the signing and MAC types and calls. To publish something others verify, read Publish a rate sheet or a release anyone can verify. To detect tampering between your own services, read Detect tampering with jobs and rows between your services. To protect the keyring record, read Protect the keyring record.

Signature or MAC

SignatureMAC
Keyan asymmetric key: the private half signs, the public half verifiesone symmetric key: it computes and verifies
Who verifiesanyone holding the public key, with no KMS and no secret: another service, a browser, an offline toola holder of the key: a process with KMS decrypt on the keyring’s KEK and read access to its record
Who can forgethe holder of the private key onlyevery verifier
Costone KMS call per signaturean HMAC in process

Use a signature for a public archive, a document a browser checks, a bundle another organisation verifies, or a record whose writer must be told apart from its readers, such as the keyring record. Use a MAC for bytes that one application’s processes hand each other: a cache entry, a job, a token, a row whose integrity must not depend on the store. Be aware a MAC never proves origin to anyone who could not have computed it.

Signing and verifying

A signed value has a payload type and the bytes that stand for it. The payload type is signed with the bytes, so a signature over one kind of document never verifies as another kind. The library signs the SHA-256 of the payload, so a KMS sees the same few bytes whatever the size of the document. Canonicalise a document that may be serialised again before it is signed: write it in one fixed form, so that every serialiser produces the same bytes.

A serde type implements SignableType to name its payload type, and the call passes it as JsonEncoded::new(value), whose payload is the compact JSON of the value. Signer::sign and Verifier::verify_signed take and return the JsonEncoded, and the outer type, Signature or Signed, says what the bytes are for. A type with another encoding implements Signable itself, see Another encoding.

A Signer signs through a signing provider. Its verifying key goes into a VerifyingKeySet, the public keys a verifier trusts, which to_jwks writes as a JWK Set (RFC 7517, a JSON document that lists public keys) and from_jwks reads back:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalSigningKeyName, LocalSigningProvider};
use kms_aead::signing::{Signature, Signer, SigningAlgorithm, Verifier, VerifyingKeySet};
use kms_aead::{JsonEncoded, KmsAeadResult, SignedPayloadType, SignableType};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct Invoice {
    number: String,
    customer: String,
    currency: String,
    total_cents: u64,
}

impl SignableType for Invoice {
    const PAYLOAD_TYPE: SignedPayloadType =
        SignedPayloadType::from_static("application/vnd.example.invoice+json");
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> KmsAeadResult<()> {
// The local provider stands in for a KMS key, see the providers below
let provider = LocalSigningProvider::<Ring>::ephemeral(
    LocalSigningKeyName::try_from("invoices".to_string())?,
    SigningAlgorithm::Ed25519,
)?;
let signer = Signer::<_, Ring>::new(provider).await?;

// Once, by the signer's owner: the public key as a JWK Set, for verifiers and browsers
let jwks: String = VerifyingKeySet::new([signer.verifying_key().clone()])?.to_jwks()?;

let invoice = JsonEncoded::new(Invoice {
    number: "INV-1042".to_string(),
    customer: "Northwind Traders".to_string(),
    currency: "EUR".to_string(),
    total_cents: 12_500,
});
let stored: Vec<u8> = signer.sign(&invoice).await?.into_value();

// Anywhere: no KMS, no secret
let verifier = Verifier::<Ring>::new(VerifyingKeySet::from_jwks(&jwks)?)?;
let signature = Signature::<JsonEncoded<Invoice>>::try_from(stored)?;
verifier.verify(&invoice, &signature)?;

let forged = JsonEncoded::new(Invoice { total_cents: 1_250, ..invoice.0 });
assert_eq!(verifier.verify(&forged, &signature).unwrap_err().code(), "SIGNATURE_INVALID");
Ok(())
}

A verifier in another language checks the exact bytes that were signed. Publish the payload bytes with the signature, as to_payload returned them, rather than rebuilding them from fields: another serialiser may order the members or format numbers differently.

The signing providers sit beside the encryption providers, each in the feature of its KMS and named by a key reference that names one key version, never “the latest”: GcpKmsSigningProvider, AwsKmsSigningProvider, AzureKmsSigningProvider, HcVaultTransitSigningProvider and LocalSigningProvider, in every build. The algorithms and the key reference of each are in the Signing section of its page, see KMS providers. Be aware the private key of a LocalSigningProvider is in process memory, with no IAM, no audit log and no HSM.

Full example available here.

Attached and detached

Signer::sign returns a detached Signature<T>, a small value to store beside the bytes, and sign_attached a Signed<T> that carries the payload. Verifier::verify checks a detached signature against the payload as read; Verifier::verify_signed checks an attached value and only then decodes and returns its payload. MACs have the same pair: a detached Mac<T>, checked with verify_mac on a keyring, and an attached WithMac<T>, which mac_attached computes and verify_with_mac checks before it returns the payload. The four types are stored as Encrypted is, with serde, postgres and sqlx, and none implements PartialEq. The bytes are in Signature and MAC formats.

Another encoding

A type whose payload is not JSON implements Signable itself: to_payload returns the bytes that are signed, and from_payload decodes the bytes of an attached value after they verified. Both fail with INVALID_PAYLOAD. This statement is signed as its UTF-8 text:

use kms_aead::errors::KmsAeadEncryptionError;
use kms_aead::{KmsAeadResult, Signable, SignableType, SignedPayloadType};

struct Statement(String);

impl SignableType for Statement {
    const PAYLOAD_TYPE: SignedPayloadType =
        SignedPayloadType::from_static("text/vnd.example.statement");
}

impl Signable for Statement {
    fn to_payload(&self) -> KmsAeadResult<Vec<u8>> {
        Ok(self.0.clone().into_bytes())
    }

    fn from_payload(payload: &[u8]) -> KmsAeadResult<Self> {
        std::str::from_utf8(payload)
            .map(|text| Statement(text.to_string()))
            .map_err(|_| {
                KmsAeadEncryptionError::create("INVALID_PAYLOAD", "The payload is not UTF-8 text")
            })
    }
}

Payloads that do not decode

verify_signed and verify_with_mac decode a payload after it verified. A JsonEncoded payload that is not the JSON of its type fails with INVALID_PAYLOAD, which never quotes the payload, and logs a WARN event with an outline of the JSON, which the type’s policy sets as it does for an encrypted value, see JSON that does not decode.

Key ids and rotation

Every value starts with a key id that selects the key the verifier tries. The id of a signing key is the first four bytes of its JWK thumbprint (RFC 7638), so a signer and every verifier agree on it without a registry. A publisher with a numbering of its own sets it with Signer::with_key_id. A key set holds one key per id, and a verifier refuses an id its set lacks with SIGNING_KEY_UNKNOWN. The set is the trust root: a key in it verifies, and a key removed from it verifies nothing, whatever the KMS still holds. Keep one set per publisher.

A signing key rotates by publishing before signing:

  1. create the new key version in the KMS, or the new key on AWS KMS, or a new local version;
  2. add the new signer’s verifying_key() to the published key set beside the current key;
  3. switch the signers to the new version once the verifiers have refreshed the set;
  4. keep the old key in the set for as long as its signatures are verified. Removing it revokes every signature under it, which is the response to a compromised key.

Key formats

Every loader of a key takes the format of its bytes as an enum from kms_aead::formats, and no loader guesses it:

  • PrivateKeyFormat: Pkcs8Der or Pkcs8Pem, for LocalSigningKey and LocalAsymmetricKek;
  • PublicKeyFormat: Raw, SpkiDer, SpkiPem or Jwk, for VerifyingKey. An asymmetric KEK’s public key takes all but Raw;
  • SymmetricKeyFormat: Raw, Base64 or Jwk, for LocalKek.

openssl genpkey -algorithm ed25519 writes the PEM that Pkcs8Pem reads. from_file and from_env read a key of up to 32 KiB from a file or a variable:

use std::num::NonZeroU32;

use kms_aead::formats::{PrivateKeyFormat, PublicKeyFormat};
use kms_aead::providers::{LocalSigningKey, LocalSigningKeyVersion};
use kms_aead::signing::{SigningAlgorithm, VerifyingKey};
use kms_aead::{KeyId, KmsAeadResult};
use secret_vault_value::SecretValue;

fn main() -> KmsAeadResult<()> {
// redacter:allow-begin
let pem = "-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEIJ1hsZ3v/VpguoRK9JLsLMREScVpezJpGXA7rAMcrn9g
-----END PRIVATE KEY-----
";
// redacter:allow-end
let key = LocalSigningKey::from_secret(
    LocalSigningKeyVersion::from(NonZeroU32::MIN),
    SecretValue::from(pem),
    PrivateKeyFormat::Pkcs8Pem,
)?;

// The public key out in one format and back in
let spki = key.verifying_key().encode(PublicKeyFormat::SpkiPem)?;
let verifying =
    VerifyingKey::from_bytes(SigningAlgorithm::Ed25519, &spki, PublicKeyFormat::SpkiPem)?;
assert_eq!(verifying.key_id(), KeyId::new(0x90fa_cafe));
Ok(())
}

In a browser

A browser verifies a detached signature with WebCrypto: import the keys of the JWK Set, read the key id from the signature, hash the payload, build the pre-image and call verify. The pre-image is the exact bytes a signature covers: the payload type and the payload’s SHA-256 in the DSSE pre-authentication encoding (PAE), see Signature and MAC formats. WebCrypto takes the ECDSA signature as r || s, the two 32-byte numbers of the signature written one after the other, and the Ed25519 signature as the 64 bytes of RFC 8032, which SubtleCrypto.verify supports in Chrome 137, Firefox 129 and Safari 17. P-256 works in every engine with WebCrypto.

// jwks: the parsed JWK Set; payloadType: the type's payload type string;
// payload and signature: Uint8Array. Returns the JWK that verified, or null.
async function verifyDetached(jwks, payloadType, payload, signature) {
  if (signature.length < 6 || signature[0] !== 0x01) {
    throw new Error("not a detached signature");
  }
  const keyId = new DataView(signature.buffer, signature.byteOffset, 5).getUint32(1);
  const raw = signature.subarray(5);
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", payload));
  const preImage = pae(payloadType, digest);
  const jwk = await keyWithId(jwks, keyId);
  if (jwk === null || raw.length !== 64) return null;
  const [importParams, verifyParams] = algorithmOf(jwk);
  const key = await crypto.subtle.importKey("jwk", jwk, importParams, false, ["verify"]);
  const verified = await crypto.subtle.verify(verifyParams, key, raw, preImage);
  return verified ? jwk : null;
}

// The one key of the set with this id, or null: a miss is a refusal, never a search.
async function keyWithId(jwks, keyId) {
  for (const jwk of jwks.keys) {
    if ((await keyIdOf(jwk)) === keyId) return jwk;
  }
  return null;
}

// "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in ASCII decimal.
function pae(payloadType, body) {
  const ascii = new TextEncoder();
  const type = ascii.encode(payloadType);
  const head = ascii.encode(`DSSEv1 ${type.length} `);
  const middle = ascii.encode(` ${body.length} `);
  const out = new Uint8Array(head.length + type.length + middle.length + body.length);
  out.set(head, 0);
  out.set(type, head.length);
  out.set(middle, head.length + type.length);
  out.set(body, head.length + type.length + middle.length);
  return out;
}

function algorithmOf(jwk) {
  if (jwk.kty === "OKP" && jwk.crv === "Ed25519") {
    return [{ name: "Ed25519" }, { name: "Ed25519" }];
  }
  if (jwk.kty === "EC" && jwk.crv === "P-256") {
    return [{ name: "ECDSA", namedCurve: "P-256" }, { name: "ECDSA", hash: "SHA-256" }];
  }
  throw new Error("unsupported key");
}

// The id the publisher set, else the first four bytes of the RFC 7638 thumbprint: the members in
// lexicographic order, no whitespace. JSON.stringify keeps the insertion order, and base64url
// values need no escaping.
async function keyIdOf(jwk) {
  if (Number.isInteger(jwk.kms_aead_key_id)) return jwk.kms_aead_key_id;
  const members =
    jwk.kty === "OKP"
      ? { crv: jwk.crv, kty: jwk.kty, x: jwk.x }
      : { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };
  const input = new TextEncoder().encode(JSON.stringify(members));
  const digest = await crypto.subtle.digest("SHA-256", input);
  return new DataView(digest).getUint32(0);
}

An attached value is split first: w is the big-endian u16 at bytes 5 and 6, the signature the w bytes after it, and the payload the rest; verify before using the payload. The test vectors of Signature and MAC test vectors run against this code in CI.

MACs in a keyring

A keyring holds MAC key versions beside its other versions, under the purpose Mac: HMAC-SHA256 keys of 32 bytes or HMAC-SHA512 keys of 64 bytes, encrypted by the KEK as every DEK is, with the states, staged rotation and compromised flag of the others, see Key versions and lifecycle. Encryptor::mac computes a Mac<T> under the active MAC version and Encryptor::mac_attached a WithMac<T>. Keyring::verify_mac and verify_with_mac verify under the version a value names, with the keyring’s compromised-version policy as decrypt applies it. One MAC version serves every payload type of an application.

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{JsonEncoded, SignedPayloadType, SignableType};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions, MacAlgorithm,
};
use serde::{Deserialize, Serialize};

#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Job {
    task: String,
    image_id: u64,
}

impl SignableType for Job {
    const PAYLOAD_TYPE: SignedPayloadType = SignedPayloadType::from_static("example.com/jobs/v1");
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("jobs".to_string())?)?;
let admin = registry
    .open_or_create(
        provider,
        KeyringId::from_static("tenant-42"),
        KeyringAlgorithms::new().with_mac(MacAlgorithm::HmacSha256),
    )
    .await?;
let keyring = admin.keyring();

let job = JsonEncoded::new(Job { task: "resize".to_string(), image_id: 7 });
let mac = keyring.encryptor().await.mac(&job).await?;
keyring.verify_mac(&job, &mac).await?;

let with_mac = keyring.encryptor().await.mac_attached(&job).await?;
let verified = keyring.verify_with_mac(&with_mac).await?.0;
assert_eq!(verified, job.0);
registry.shutdown(None).await;
Ok(())
}

A value under a retired version fails with KEY_VERSION_RETIRED, so compute a new MAC over the payload under the active version before retiring the old one; sweeps re-encrypt Encrypted fields and not MACs. A process on a version that predates MACs refuses a record with a MAC version, so upgrade every process that reads the keyring before the first MAC version is created, see Readers before producers. Authenticator computes and verifies MACs with a key the caller holds.

Full example available here.

Beacons and MACs

Both are HMACs under a keyring version, and they serve different ends, see Beacons:

BeaconMAC
Purposefind rows by a field’s value without decrypting itprove that bytes were not changed since a key holder computed the tag
Outputthe first bits bits of HMAC-SHA256, truncated on purpose so that values collidethe full tag, 32 or 64 bytes, never truncated
TypeBeacon<T>, T: PlaintextMac<T> and WithMac<T>, T: Signable
Equalityequal beacons mean likely equal values, by designequal tags mean an equal payload under the key, which verify says

Signing the keyring record

A keyring record decides which versions are read and which encrypts, and its integrity rests on the store’s access control, see Keyring deployment. A store writer can re-activate a compromised version or point a version at another DEK, and under an asymmetric KEK, which encrypts for anyone holding its public key, plant a DEK of its own, see Asymmetric KEKs. A signed record closes both: the administration signs every record it writes, and an application refuses a record that no key it trusts has signed.

  • the administration holds a KeyringAdmin with a record signer, a Signer on any signing provider. KeyringRegistry::create_signed and open_or_create_signed sign the record from its first write, and with_record_signer adds a signer to an admin;
  • a signing admin re-signs the record on every write and refuses an unsigned record with RECORD_UNSIGNED; only sign_record signs an unsigned record. A NoRecordSigner admin refuses to overwrite a signed record with RECORD_SIGNER_MISSING;
  • every registry verifies the signature of every record it reads, before any field is used and before any KMS call. KeyringRegistryOptions::record_signatures decides what an unsigned record means: VerifyIfSigned(keys), the default, reads it, and Required(keys) refuses it with RECORD_UNSIGNED. A signature that does not verify fails with RECORD_SIGNATURE_INVALID under both.

The verifying keys come from the application’s configuration, a JWK Set or the public key of the KMS key, never from the store or the record:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider, LocalSigningKeyName, LocalSigningProvider};
use kms_aead::signing::{Signer, SigningAlgorithm, VerifyingKeySet};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions, RecordSignaturePolicy,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let signer = Signer::<_, Ring>::new(LocalSigningProvider::<Ring>::ephemeral(
    LocalSigningKeyName::try_from("records".to_string())?,
    SigningAlgorithm::Ed25519,
)?)
.await?;
let keys = VerifyingKeySet::new([signer.verifying_key().clone()])?;

let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new().with_record_signatures(RecordSignaturePolicy::Required(keys)),
)?;
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("records".to_string())?)?;
let admin = registry
    .open_or_create_signed(
        provider,
        signer,
        KeyringId::from_static("tenant-42"),
        KeyringAlgorithms::new(),
    )
    .await?;
assert!(admin.keyring().record().signature().is_some());
registry.shutdown(None).await;
Ok(())
}

Full example available here. The signed bytes are in The signed keyring record.

Moving an existing deployment to signed records, rotating the signing key, what only Required closes and stopping signing are in Protect the keyring record.

Limits

  • whoever may sign records may write any record, and a signature proves the record was written by a signer, not that it is the latest: a store writer can restore an older signed record, which running processes refuse when it moves a version backwards;
  • a signature is valid for as long as its key is in the verifier’s set. There is no expiry and no revocation list, so put a timestamp or a recipient in the payload: nothing outside the payload type and the payload is authenticated;
  • ECDSA signatures are malleable: a third party can turn a valid signature into another valid one for the same message. Never use signature bytes as an identifier or compare them for equality; Ed25519 signatures are unique for a key and a message;
  • a MAC is forged by every holder of its key, which is every process with KMS decrypt on the keyring’s KEK and read access to its record;
  • the library does not sign the public key set. How it reaches a verifier is the deployment’s control;
  • RSA signatures, secp256k1, P-384, P-521, ML-DSA, JWS and COSE are not supported.

The errors of signing are in Error handling.

Crypto backends

This page specifies the crypto backends: the libraries that run the AEAD algorithms, the algorithms each one has, and the calls that need no KMS. To pick one for a build, FIPS included, read Choose a provider and a backend first.

The AEAD algorithms run on a crypto library that a feature compiles in. Each backend feature adds a type to kms_aead::backends, and AeadCipher, DeterministicCipher, KmsAeadEnvelope and LocalKmsProvider take that type as their backend type parameter B. A build may enable any number of backends, and there is no default one.

FeatureTypeLibrary
ringRingring
aws-lcAwsLcaws-lc-rs
aws-lc-fipsAwsLc, on the FIPS moduleaws-lc-rs
rustcryptoRustCryptothe RustCrypto AEADs

There is no default because Cargo unifies features: a default chosen by features would change for every crate in a build when one crate enables another backend.

Code generic over the backend

The backend types implement AeadBackend, a sealed trait in kms_aead::backends. Its items are the constant NAME, the backend’s name in spans and logs: ring, aws-lc or rustcrypto, and generate_random_bytes. AeadBackend names the crypto engine for every primitive the library runs on it: the AEAD algorithms, the beacon HMAC, the RSA operations of asymmetric KEKs and the signature verification. Code that works with any backend bounds its type parameter with AeadBackend and nothing else:

use kms_aead::backends::{AeadBackend, Ring};
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{KmsAeadEnvelope, KmsAeadResult};
use secret_vault_value::SecretValue;

struct Orders<B> {
    envelope: KmsAeadEnvelope<LocalKmsProvider<B>, B>,
}

impl<B: AeadBackend> Orders<B> {
    fn new() -> KmsAeadResult<Self> {
        let provider = LocalKmsProvider::ephemeral(LocalKekId::try_from("orders".to_string())?)?;
        Ok(Self {
            envelope: KmsAeadEnvelope::new(provider)?,
        })
    }

    async fn round_trip(&self, card: &SecretValue) -> KmsAeadResult<SecretValue> {
        let encrypted = self.envelope.encrypt(b"orders/1042", card).await?;
        self.envelope.decrypt(b"orders/1042", &encrypted).await
    }
}

#[tokio::main(flavor = "current_thread")]
async fn main() -> KmsAeadResult<()> {
let orders = Orders::<Ring>::new()?;
let card = SecretValue::from("4111 1111 1111 1111");
assert_eq!(orders.round_trip(&card).await?, card);
Ok(())
}

B::generate_random_bytes(len) returns len bytes from the CSPRNG of the backend B, for secrets the application generates itself. A CSPRNG is a cryptographically secure random number generator, the kind of source that keys and nonces need.

Algorithms

AlgorithmKeyRingAwsLcRustCrypto
ChaCha20Poly1305 (RFC 8439)32 bytesyesyesyes
Aes128Gcm16 bytesyesyesyes
Aes256Gcm, the envelope’s default32 bytesyesyesyes
Aes256GcmSiv (RFC 8452)32 bytesnoyesyes
RsaOaepSha256 encryption under an asymmetric KEK2048, 3072 or 4096 bitsnoyesyes
local RSA private halfnoyesyes

Every AEAD algorithm writes [nonce: 12][ciphertext][tag: 16], with a random nonce from the backend’s CSPRNG, see Values and DEKs. The two RSA rows are the RSA-OAEP (RSA encryption with OAEP padding) of Asymmetric KEKs: the encryption of a DEK with the public key, and the private half of a LocalAsymmetricKmsProvider. A backend that does not implement the algorithm fails at construction, never later, with KmsAeadError::UnsupportedAlgorithm and the code UNSUPPORTED_ALGORITHM:

use kms_aead::backends::Ring;
use kms_aead::{errors::KmsAeadError, AeadAlgorithm, AeadCipher};

let result = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256GcmSiv);
assert!(matches!(result, Err(KmsAeadError::UnsupportedAlgorithm(_))));

Streamed values, with the stream feature, run AES-256-GCM for their chunks and HMAC-SHA-512 for the key derivation, which every backend has: hmac::HMAC_SHA512 on ring and aws-lc-rs, and Hmac<Sha512> of the hmac and sha2 crates on RustCrypto. A value encrypted on one backend decrypts on every other, see Streaming encryption.

AeadAlgorithm reads and writes its names with FromStr and Display: chacha20-poly1305, aes-128-gcm, aes-256-gcm and aes-256-gcm-siv.

AEAD without a KMS

AeadCipher encrypts and decrypts values with a key the application holds. encrypt_bare writes the AEAD output alone, an Encrypted<T, Bare>:

use kms_aead::backends::Ring;
use kms_aead::formats::Bare;
use kms_aead::{AeadAlgorithm, AeadCipher, Encrypted};
use secret_vault_value::SecretValue;

fn main() -> kms_aead::KmsAeadResult<()> {
let cipher = AeadCipher::<Ring>::new(AeadAlgorithm::ChaCha20Poly1305)?;
let dek = cipher.generate_dek()?;

let aad = b"orders/1042";
let cipher_text: Encrypted<SecretValue, Bare> =
    cipher.encrypt_bare(aad, &SecretValue::from("secret"), &dek)?;
let decrypted: SecretValue = cipher.decrypt_bare(aad, &cipher_text, &dek)?;

assert_eq!(decrypted, SecretValue::from("secret"));
Ok(())
}

Full example available here.

encrypt writes an Encrypted<T, Randomized>: the same output after Tink’s TINK prefix, which names the key by a KeyId, see One fixed key.

generate_dek makes a DEK without a KMS. generate_encrypted_dek makes a DEK and encrypts it with a provider in one call, for an application that stores the encrypted DEK itself. The other calls of AeadCipher make no KMS call and open no span.

Cross-backend compatibility

Every backend writes the same bytes for the same algorithm, so a value encrypted by one backend decrypts with any other that implements its algorithm. A writer on Ring and a reader on AwsLc work together, and moving an application from one backend to another needs no migration of its data:

use kms_aead::backends::{Ring, RustCrypto};
use kms_aead::formats::Bare;
use kms_aead::{AeadAlgorithm, AeadCipher, Encrypted};
use secret_vault_value::SecretValue;

fn main() -> kms_aead::KmsAeadResult<()> {
let writer = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?;
let reader = AeadCipher::<RustCrypto>::new(AeadAlgorithm::Aes256Gcm)?;

let dek = writer.generate_dek()?;
let cipher_text: Encrypted<SecretValue, Bare> =
    writer.encrypt_bare(b"aad", &SecretValue::from("secret"), &dek)?;

let decrypted: SecretValue = reader.decrypt_bare(b"aad", &cipher_text, &dek)?;
assert_eq!(decrypted, SecretValue::from("secret"));
Ok(())
}

ring

ChaCha20-Poly1305, AES-128-GCM and AES-256-GCM. It has no AES-256-GCM-SIV and no RSA encryption, so an encryption with a public key and a local RSA private half fail at construction with UNSUPPORTED_ALGORITHM. ring does not zeroise its expanded key schedules, so they stay in freed memory after each call.

aws-lc-rs and FIPS

aws-lc builds aws-lc-rs with every algorithm. It is the backend that adds no second crypto library to a build with a cloud provider, since the default features of the providers already build aws-lc-rs for TLS.

aws-lc-fips runs the same backend on the AWS-LC FIPS module, and builds only the FIPS module, so it does not need aws-lc. It needs CMake and Go to build. Be aware it moves every user of aws-lc-rs in the build to the FIPS module, the rustls aws-lc-rs provider included. A build with both features compiles both C libraries, and aws-lc-rs runs on the FIPS one. AES-256-GCM is the algorithm for FIPS deployments. AES-SIV, the deterministic algorithm, is not FIPS-approved, see Deterministic encryption.

aws-lc-rs copies the key into an AEAD context that AWS-LC allocates with its own allocator, which overwrites every allocation with zeros before freeing it. The expanded key schedule does not stay in freed memory after a call, as long as the application leaves AWS-LC’s allocator in place. The record keys AES-256-GCM-SIV derives for each call live on the stack, and AWS-LC does not clear them.

RustCrypto

Every algorithm, in pure Rust, with getrandom as the CSPRNG. It needs no C compiler. The feature turns on the crates’ zeroize features, so their key objects, and the Poly1305 and POLYVAL keys (the authentication keys of ChaCha20-Poly1305 and AES-256-GCM-SIV) each call derives, are zeroised when dropped.

The feature adds the rsa crate for RSA-OAEP. Its private-key operation runs only in a LocalAsymmetricKmsProvider on RustCrypto. Encrypting with the public key is a public-key operation with no private key to leak, and a cloud reader runs no RSA. Every application that enables rustcrypto carries rsa in its lockfile. A local KMS on RustCrypto decrypts DEKs from trusted sources only, such as its own keyring record. A process that decrypts what others send runs its private half on AwsLc, or in a KMS.

KMS providers

A provider encrypts and decrypts data encryption keys with one key encryption key (KEK). Each one is a type in kms_aead::providers, enabled by its feature:

KMSTypeFeature
Google Cloud KMSGcpKmsProvidergcp-kms-encryption
AWS KMSAwsKmsProvideraws-kms-encryption
Azure Key Vault, and Managed HSMAzureKmsProviderazure-kms-encryption
HashiCorp Vault TransitHcVaultTransitProviderhashicorp-vault-transit-kms-encryption
Local KMS, a KEK the process holdsLocalKmsProvidernone, in every build
Local KMS, an RSA KEK the process holdsLocalAsymmetricKmsProvidernone, in every build

Every provider has a page with the same sections, in this order: configuration, authentication and permissions; key versions and rotation; asymmetric KEKs; signing; limits; and errors. A section that a provider does not support says so.

This page specifies what the providers share. To pick one, read Choose a provider and a backend. For the rights the applications and the administration need, read Permissions: applications and administration. For rotating the KEK, read Rotate keys and re-encrypt values.

Every KMS provider above implements the two provider traits, KmsAeadEncryptionProvider, which encrypts DEKs, and KmsAeadDecryptionProvider, which decrypts them, and KmsAeadEnvelope takes any of them:

use kms_aead::backends::AwsLc;
use kms_aead::providers::{GcpKmsKeyRef, GcpKmsProvider};
use kms_aead::KmsAeadEnvelope;

async fn example() -> kms_aead::KmsAeadResult<()> {
let kms_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);
let provider = GcpKmsProvider::new(&kms_ref).await?;
let envelope = KmsAeadEnvelope::<GcpKmsProvider, AwsLc>::new(provider)?;
let _ = envelope;
Ok(())
}

Each provider names its configured KEK on every decryption, so a DEK encrypted under another KEK fails at the KMS and never decrypts a value. provider.kek() returns that KEK as a KekRef: the KMS and the key name. It is also the provider and key field of the KMS spans, see Spans and events, and the key of the DEK cache, see DEK caching and reuse. Nothing else is checked: an encrypted DEK carries no context that the KMS authenticates, see Security considerations.

Asymmetric KEKs

A KEK can be an RSA key pair: its public half encrypts a DEK with RSA-OAEP (RSA encryption with OAEP padding), in the process of whoever holds the public key, and its private half decrypts it. Each provider above reads the 0x02 encrypted DEK of such an encryption beside its own bytes, and fetches the public key for the administration with a public_key call. No side needs the KMS encrypt right: the encryption is a local operation, and the KMS only decrypts. The layout, the choices and the limits are in Asymmetric KEKs. To build a deployment on them, read Accept data from partners and devices that cannot read it back.

Two further providers are in every build and hold the public key:

  • PublicKeyKekProvider encrypts, for a producer that must never decrypt. It implements KmsAeadEncryptionProvider alone, so an envelope over it has no call that decrypts a DEK or a value, and no keyring opens over it;
  • AsymmetricKekProvider encrypts with the public key and decrypts through the KMS provider of the same KEK, for the keyring administration.

The call that fetches the public key, on the provider the administration holds:

KMSPublic key
Google Cloud KMSGcpKmsProvider::public_key(&version)
AWS KMSAwsKmsProvider::public_key()
Azure Key VaultAzureKmsProvider::public_key(None) for the latest version, or Some(&version)
Vault TransitHcVaultTransitProvider::public_key(None) or Some(&version)
Local KMSLocalAsymmetricKmsProvider::public_key(None) for its encrypting version

The rights of a reader and of the administration are in Under an asymmetric KEK, with the exact permissions of each KMS on its page above.

encrypts_with_public_key() is true for PublicKeyKekProvider, AsymmetricKekProvider and LocalAsymmetricKmsProvider, so that a keyring refuses the BigQuery and Tink exports its KEK cannot serve.

KMS random generators

By default a DEK comes from the CSPRNG of the crypto backend. The GCP and AWS providers can take it from the KMS instead, at the cost of one more KMS request per new DEK:

  • GCP: GcpKmsProviderOptions::new().with_use_kms_random_gen(true), Cloud KMS GenerateRandomBytes at the HSM protection level;
  • AWS: AwsKmsProviderOptions::new().with_use_kms_random_gen(true), AWS KMS GenerateRandom.

Azure, Vault Transit and the local KMS always use the backend’s CSPRNG. Nonces always come from the backend’s CSPRNG.

Your own provider

An application can implement the provider traits for a KMS of its own, or as a wrapper around another provider: KmsAeadEncryptionProvider, with kek, encrypt_data_encryption_key and the defaulted generate_key_material and encrypts_with_public_key, and KmsAeadDecryptionProvider, with decrypt_data_encryption_key. A provider that only encrypts implements the first alone, and the calls that decrypt do not compile over it. A wrapper implements each trait where the provider it wraps does, as this one, which counts decryptions, does:

use std::sync::atomic::{AtomicU64, Ordering};

use kms_aead::{
    DataEncryptionKey, EncryptedDataEncryptionKey, KekRef, KmsAeadDecryptionProvider,
    KmsAeadEncryptionProvider, KmsAeadResult,
};
use secret_vault_value::SecretValue;

/// The provider `P`, with a count of its decryptions.
struct Counted<P> {
    inner: P,
    decryptions: AtomicU64,
}

impl<P: KmsAeadEncryptionProvider> KmsAeadEncryptionProvider for Counted<P> {
    fn kek(&self) -> &KekRef {
        self.inner.kek()
    }

    async fn encrypt_data_encryption_key(
        &self,
        dek: &DataEncryptionKey,
    ) -> KmsAeadResult<EncryptedDataEncryptionKey> {
        self.inner.encrypt_data_encryption_key(dek).await
    }

    async fn generate_key_material(&self, len: usize) -> KmsAeadResult<Option<SecretValue>> {
        self.inner.generate_key_material(len).await
    }

    fn encrypts_with_public_key(&self) -> bool {
        self.inner.encrypts_with_public_key()
    }
}

impl<P: KmsAeadDecryptionProvider> KmsAeadDecryptionProvider for Counted<P> {
    async fn decrypt_data_encryption_key(
        &self,
        encrypted_dek: &EncryptedDataEncryptionKey,
    ) -> KmsAeadResult<DataEncryptionKey> {
        self.decryptions.fetch_add(1, Ordering::Relaxed);
        self.inner.decrypt_data_encryption_key(encrypted_dek).await
    }
}

The implementation:

  • is Send and Sync, and writes encrypt_data_encryption_key, decrypt_data_encryption_key and generate_key_material as async fn, whose futures must be Send. The traits have no dyn form, so code that holds a provider is generic over it;
  • returns from kek() a KekRef with KmsProvider::Other and a key name that identifies the key across every KMS instance it may address. A wrapper returns the inner provider’s kek();
  • names that KEK to the KMS on every decryption;
  • adds to the encrypted DEK that encrypt_data_encryption_key returns, with with_kek_version, the KEK version the KMS’s response names, never the one it expects, and none when the response names none;
  • returns true from encrypts_with_public_key() when it encrypts DEKs with the public half of a key pair, so that a keyring refuses the BigQuery and Tink exports its KEK cannot serve. The method has a default of false;
  • keeps key material, plaintext or encrypted, out of its errors’ Display and Debug.

generate_key_material has a default implementation that returns Ok(None), so the backend generates the key.

Google Cloud KMS

Feature gcp-kms-encryption, or gcp-kms-encryption-webpki for the bundled WebPKI roots, see Cargo features.

GcpKmsKeyRef names a CryptoKey by its project, location, key ring and key. The provider encrypts under the primary version of the key, and each encrypted DEK records the version that encrypted it, so DEKs encrypted before a rotation still decrypt afterwards.

This page specifies GcpKmsProvider. To compare it with the other KMS providers, read Choose a provider and a backend. For the rights the applications and the administration need, read Permissions: applications and administration. For rotating the KEK, read Rotate keys and re-encrypt values.

use kms_aead::backends::AwsLc;
use kms_aead::providers::{GcpKmsKeyRef, GcpKmsProvider, GcpKmsProviderOptions};
use kms_aead::KmsAeadEnvelope;
use secret_vault_value::SecretValue;

async fn example() -> kms_aead::KmsAeadResult<()> {
let kms_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);

let provider = GcpKmsProvider::new(&kms_ref).await?;
let envelope = KmsAeadEnvelope::<GcpKmsProvider, AwsLc>::new(provider)?;

// Or with DEKs from the Cloud KMS generator at the HSM protection level
let envelope = KmsAeadEnvelope::<GcpKmsProvider, AwsLc>::new(
    GcpKmsProvider::with_options(
        &kms_ref,
        GcpKmsProviderOptions::new().with_use_kms_random_gen(true),
    )
    .await?,
)?;

let cipher_text = envelope
    .encrypt(b"orders/1042", &SecretValue::from("secret"))
    .await?;
let _ = cipher_text;
Ok(())
}

Full example available here.

Configuration, authentication and permissions

GcpKmsProvider::new and with_options build a Cloud KMS client with the application default credentials, and fail with a SystemError when the client cannot be built, such as when no credentials are found. They look for credentials in the following places, preferring the first location found:

  • A JSON file whose path is specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable;
  • A JSON file in a location known to the gcloud command-line tool using gcloud auth application-default login;
  • On Google Compute Engine, Cloud Run, GKE, etc., the metadata server.

For local development don’t confuse gcloud auth login with gcloud auth application-default login, since the first one authorises only the gcloud tool to access the Cloud Platform.

GcpKmsProvider::with_client takes a client the application built itself, for other credentials.

GcpKmsProviderOptions has one option, use_kms_random_gen, false by default: true takes DEKs from Cloud KMS GenerateRandomBytes at the HSM protection level in place of the backend’s CSPRNG, at the cost of one more KMS request per DEK, see KMS random generators.

The principal needs cloudkms.cryptoKeyVersions.useToEncrypt and useToDecrypt on the key, as in the roles/cloudkms.cryptoKeyEncrypterDecrypter role, and cloudkms.locations.generateRandomBytes on the location when the KMS generator is on.

Key versions and rotation

A rotation adds a version to the CryptoKey and makes it the primary version, by hand or on the key’s rotation schedule. New DEKs are encrypted under the primary version from then on, and Cloud KMS decrypts every DEK with the version that encrypted it, for as long as that version is enabled.

To retire the old version, disable it once the sweep has reached every value, see Re-encrypt DEKs after a KEK rotation: decryptions under it fail, and enabling it again restores them. Destroying it schedules its destruction, 30 days later by default, and until then the version can be restored.

Changing the primary version and disabling a version are eventually consistent in Cloud KMS, see Cloud KMS resource consistency. Until a new primary version has propagated, Encrypt may still use the previous one. A disabled version “typically remains usable for encrypting and decrypting data for up to 1 minute after it is disabled”, and for several hours in exceptional cases. So:

  • start the sweep only once the new primary version has propagated. The kek_version() of the encrypted DEK an encryption returns, and the kek_version field of the KMS encrypt DEK span, name the version Cloud KMS encrypted with, the N of cryptoKeyVersions/N, see Spans and events. A keyring whose reencrypt_deks ran before the new primary version had propagated still lists the old version among its kek_versions_in_use: run reencrypt_deks again, see Re-encrypting a keyring’s DEKs;
  • run the check only once the disable has propagated, and run it again before destroying the version. A check inside that window passes on DEKs that are still under the old version.

Enabling a version is strongly consistent, see Cloud KMS resource consistency: an enabled version is available at once, so enabling the old version again after a failed check takes effect immediately.

Rolling back a rotation

Make the old version the primary version again, and keep the new version enabled: every swept value and every value written since the rotation is under the new version only, and disabling it makes them unreadable until it is enabled again. See Rolling back a rotation.

Asymmetric KEKs

A CryptoKey with the purpose ASYMMETRIC_DECRYPT and an algorithm RSA_DECRYPT_OAEP_2048_SHA256, RSA_DECRYPT_OAEP_3072_SHA256 or RSA_DECRYPT_OAEP_4096_SHA256 is an asymmetric KEK, see Asymmetric KEKs. 3072 bits is the size Cloud KMS marks as recommended. Asymmetric keys have no primary version and no automatic rotation, so a version is always named:

  • GcpKmsProvider::public_key(&version) sends GetPublicKey for the CryptoKeyVersion and returns the public key with the version the response names as its KEK version, for the producers. It fails with ASYMMETRIC_KEK_PUBLIC_KEY for a version whose algorithm is not RSA_DECRYPT_OAEP_2048_SHA256, RSA_DECRYPT_OAEP_3072_SHA256 or RSA_DECRYPT_OAEP_4096_SHA256;
  • a decryption of a 0x02 encrypted DEK sends AsymmetricDecrypt on <key>/cryptoKeyVersions/<version>, with the RSA block as ciphertext. The encrypted DEK names the version, as a symmetric ciphertext does. The request carries no CRC32C checksum fields (CRC32C is the 32-bit checksum with which Cloud KMS detects corruption in transit): a corrupted DEK fails the value’s AEAD;
  • the principal of a reader needs cloudkms.cryptoKeyVersions.useToDecrypt, as in roles/cloudkms.cryptoKeyDecrypter, and the administration also cloudkms.cryptoKeyVersions.viewPublicKey, as in roles/cloudkms.publicKeyViewer. Nobody needs useToEncrypt.

An asymmetric decryption costs more of the quota than a symmetric one, see Keyrings under an asymmetric KEK.

Signing

GcpKmsSigningProvider signs with one CryptoKeyVersion of a key with the purpose ASYMMETRIC_SIGN, see Signatures and MACs. GcpKmsSigningKeyRef names the key as GcpKmsKeyRef does, and adds the version, the N of cryptoKeyVersions/N, and the algorithm: Ed25519 for an EC_SIGN_ED25519 version and EcdsaP256Sha256 for EC_SIGN_P256_SHA256. Asymmetric keys have no primary version, so a signer always names one.

use std::num::NonZeroU32;

use kms_aead::backends::AwsLc;
use kms_aead::formats::PublicKeyFormat;
use kms_aead::providers::{GcpKmsSigningKeyRef, GcpKmsSigningProvider};
use kms_aead::signing::{Signer, SigningAlgorithm};

async fn example() -> kms_aead::KmsAeadResult<()> {
let key_ref = GcpKmsSigningKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-signing-key".to_string(),
    NonZeroU32::MIN,
    SigningAlgorithm::EcdsaP256Sha256,
);

let provider = GcpKmsSigningProvider::new(&key_ref).await?;
let signer = Signer::<_, AwsLc>::new(provider).await?;

// The public key to publish for the verifiers
let jwk = signer.verifying_key().encode(PublicKeyFormat::Jwk)?;
let _ = jwk;
Ok(())
}

The provider authenticates as GcpKmsProvider does, and GcpKmsSigningProvider::with_client takes a client the application built itself. Creating the provider sends no request; Signer::new sends the first one. Cloud KMS lists EC_SIGN_ED25519 under the software protection level only, so a key at the HSM protection level signs with P-256.

  • sign sends AsymmetricSign with the pre-image (the exact bytes a signature covers, see Signature and MAC formats) as data for Ed25519, and the SHA-256 of the pre-image as digest.sha256 for P-256. Each carries its CRC32C checksum, dataCrc32c or digestCrc32c;
  • a response fails with SIGNATURE_ENCODING when verifiedDataCrc32c or verifiedDigestCrc32c is false, when signatureCrc32c is missing or does not match the signature, or when the signature is not 64 bytes (Ed25519) or strict DER (P-256), which is converted to r || s (the two 32-byte integers of an ECDSA signature, one after the other). A name other than the configured version fails with SIGNING_KEY_MISMATCH;
  • verifying_key sends GetPublicKey and parses pem. A key of another algorithm than the configured one fails with SIGNING_ALGORITHM_MISMATCH, and a pem that does not parse with INVALID_PUBLIC_KEY;
  • the principal needs cloudkms.cryptoKeyVersions.useToSign and cloudkms.cryptoKeyVersions.viewPublicKey, as in roles/cloudkms.signerVerifier. roles/cloudkms.signer alone lacks viewPublicKey.

A rotation is a new CryptoKeyVersion that a new signer names, see Key ids and rotation.

Limits

  • Changing the primary version and disabling a version are eventually consistent, see Key versions and rotation;
  • an asymmetric KEK has no primary version and no automatic rotation, and an asymmetric decryption costs more of the quota than a symmetric one, see Asymmetric KEKs;
  • Cloud KMS lists EC_SIGN_ED25519 under the software protection level only, so a key at the HSM protection level signs with P-256, see Signing.

Errors

The code of a failed KMS call is the gRPC status code, such as PermissionDenied or NotFound. Which codes are a NetworkError and which an EncryptionError is in Retries. GcpKmsSigningProvider returns the same codes, with a SignatureError where the encryption provider returns an EncryptionError.

AWS KMS

Feature aws-kms-encryption, see Cargo features.

AwsKmsKeyRef names the key by the AWS account and the key id, which is anything AWS KMS accepts: a key id, a key ARN, an alias name such as alias/orders, or an alias ARN.

This page specifies AwsKmsProvider. To compare it with the other KMS providers, read Choose a provider and a backend. For the rights the applications and the administration need, read Permissions: applications and administration. For rotating the KEK, read Rotate keys and re-encrypt values.

use kms_aead::backends::AwsLc;
use kms_aead::providers::{AwsKmsKeyRef, AwsKmsProvider, AwsKmsProviderOptions};
use kms_aead::KmsAeadEnvelope;
use secret_vault_value::SecretValue;

async fn example() -> kms_aead::KmsAeadResult<()> {
let kms_ref = AwsKmsKeyRef::new(
    "123456789012".to_string(),
    "arn:aws:kms:eu-west-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab".to_string(),
);

let provider = AwsKmsProvider::new(&kms_ref).await?;
let envelope = KmsAeadEnvelope::<AwsKmsProvider, AwsLc>::new(provider)?;

// Or with DEKs from AWS KMS GenerateRandom
let envelope = KmsAeadEnvelope::<AwsKmsProvider, AwsLc>::new(
    AwsKmsProvider::with_options(
        &kms_ref,
        AwsKmsProviderOptions::new().with_use_kms_random_gen(true),
    )
    .await?,
)?;

let cipher_text = envelope
    .encrypt(b"orders/1042", &SecretValue::from("secret"))
    .await?;
let _ = cipher_text;
Ok(())
}

Full example available here.

Configuration, authentication and permissions

AwsKmsProvider::new loads the AWS configuration from the environment, as the AWS SDK does: environment variables, the shared config and credentials files, the instance or container role, and the session of aws login. It sends no request, so missing credentials or an unreachable endpoint fail the first encryption or decryption.

Without aws_region in the key reference, the provider takes the region of the AWS configuration it loads. Set one with AwsKmsKeyRef::new(..).with_aws_region(region).

AwsKmsProviderOptions has one option, use_kms_random_gen, false by default: true takes DEKs from AWS KMS GenerateRandom in place of the backend’s CSPRNG, at the cost of one more KMS request per DEK, see KMS random generators.

The principal needs kms:Encrypt and kms:Decrypt on the key, and kms:GenerateRandom when the KMS generator is on.

Key ARN and aliases

A decryption names the configured key to AWS KMS, so a DEK encrypted under another key fails with IncorrectKeyException, even when the principal may decrypt with that key.

Configure the key ARN rather than an alias: a DEK encrypted under an alias that later moves to another key fails to decrypt with IncorrectKeyException.

The provider turns the key id into an ARN with the region and the account: an alias name into an alias ARN, a key id into a key ARN, and an ARN stays as it is. That ARN always starts with arn:aws:, so outside the aws partition, such as in GovCloud or China, give the full ARN.

Key versions and rotation

AWS KMS rotates the key material of a key, on its rotation schedule or on demand, and keeps every earlier key material for as long as the key exists. A DEK encrypted before a rotation decrypts afterwards. An encryption’s response names no key material, so the kek_version() of the encrypted DEK it returns is None.

Key material that AWS KMS generated cannot be disabled or deleted on its own. The sweep of Re-encrypt DEKs after a KEK rotation is optional for it: it moves each DEK to the current key material, and with nothing to disable, the check and the destruction do not apply.

Imported key material is deleted in two ways:

  • DeleteImportedKeyMaterial, for the material a KeyMaterialId names or the current one without it;
  • its expiry: ExpirationModel defaults to KEY_MATERIAL_EXPIRES, and at its ValidTo, at most 365 days after the import, AWS KMS deletes the material without any call.

Either way the key moves to PendingImport, and AWS KMS refuses every operation with it, whichever material a DEK is under, until the same material is imported again. Import with KEY_MATERIAL_DOES_NOT_EXPIRE, or import again before ValidTo, and keep a copy of every material to import again.

A sweep therefore retires no imported key material from a key in use, and with every kek_version None, neither a keyring record nor a stored kek_version shows which DEKs are under which material. After a deletion or an expiry, import the material again and decrypt every stored DEK: each keyring’s with reencrypt_deks, the application’s own as in The check. An error means the key is still in PendingImport: ListKeyRotations lists each material with its import state, and the one still missing is imported again.

Rolling back a rotation

A rotation needs no rollback: AWS KMS keeps every earlier key material decrypting, and key material that AWS KMS generated cannot be disabled. See Rolling back a rotation.

Asymmetric KEKs

A KMS key of the spec RSA_2048, RSA_3072 or RSA_4096 with the usage ENCRYPT_DECRYPT is an asymmetric KEK, see Asymmetric KEKs:

  • AwsKmsProvider::public_key() sends GetPublicKey for the configured key and returns the DER SubjectPublicKeyInfo, for the producers. The key must be of usage ENCRYPT_DECRYPT and list RSAES_OAEP_SHA_256 among its EncryptionAlgorithms, and the call fails with ASYMMETRIC_KEK_PUBLIC_KEY otherwise, and when the response holds no public key;
  • a decryption of a 0x02 encrypted DEK sends Decrypt with the configured key as KeyId, EncryptionAlgorithm RSAES_OAEP_SHA_256 and the RSA block as CiphertextBlob. AWS KMS takes no encryption context with the RSA algorithms. The encrypted DEK records no key version, as under a symmetric key;
  • AWS KMS does not rotate an asymmetric key: a rotation is a new key, by hand, and so a new keyring;
  • the principal of a reader needs kms:Decrypt on the key, and the administration also kms:GetPublicKey. Nobody needs kms:Encrypt.

An asymmetric key is configured by its ARN, as a symmetric key is. AWS prices and limits the RSA requests apart from the symmetric ones, see Keyrings under an asymmetric KEK.

Signing

AwsKmsSigningProvider signs with an asymmetric KMS key of the usage SIGN_VERIFY, see Signatures and MACs. AwsKmsSigningKeyRef names the key as AwsKmsKeyRef does, and adds the algorithm: Ed25519 for an ECC_NIST_EDWARDS25519 key and EcdsaP256Sha256 for ECC_NIST_P256.

use kms_aead::backends::AwsLc;
use kms_aead::formats::PublicKeyFormat;
use kms_aead::providers::{AwsKmsSigningKeyRef, AwsKmsSigningProvider};
use kms_aead::signing::{Signer, SigningAlgorithm};

async fn example() -> kms_aead::KmsAeadResult<()> {
let key_ref = AwsKmsSigningKeyRef::new(
    "123456789012".to_string(),
    "arn:aws:kms:eu-west-1:123456789012:key/1234abcd-12ab-34cd-56ef-1234567890ab".to_string(),
    SigningAlgorithm::EcdsaP256Sha256,
);

let provider = AwsKmsSigningProvider::new(&key_ref).await?;
let signer = Signer::<_, AwsLc>::new(provider).await?;

// The public key to publish for the verifiers
let jwk = signer.verifying_key().encode(PublicKeyFormat::Jwk)?;
let _ = jwk;
Ok(())
}

The provider loads the AWS configuration and takes the region as AwsKmsProvider does, and AwsKmsSigningProvider::with_client takes a client the application built itself. Creating the provider sends no request; Signer::new sends the first one.

An asymmetric key has no versions, and a rotation is a new key. Configure the key id or the key ARN, never an alias: an alias that moves to another key would sign with a key that the key id of the signature does not name. An alias name, alias/…, or an alias ARN fails at creation with AWS_SIGNING_KEY_ALIAS, a SystemError.

  • sign sends Sign with MessageType RAW and ED25519_SHA_512 for Ed25519, and with DIGEST and ECDSA_SHA_256 for P-256, where the message is the SHA-256 of the pre-image (the exact bytes a signature covers, see Signature and MAC formats). The pre-image is within the 4,096-byte limit of Message, see Signature and MAC formats;
  • a response whose KeyId is not the configured key fails with SIGNING_KEY_MISMATCH, and one whose SigningAlgorithm is not the requested one with SIGNING_ALGORITHM_MISMATCH. A P-256 signature is DER, converted to r || s (the two 32-byte integers of an ECDSA signature, one after the other); one that is not strict DER, or an Ed25519 signature that is not 64 bytes, fails with SIGNATURE_ENCODING;
  • verifying_key sends GetPublicKey and parses the DER PublicKey. A KeySpec other than the configured one fails with SIGNING_ALGORITHM_MISMATCH;
  • the principal needs kms:Sign and kms:GetPublicKey on the key.

Limits

  • The kek_version() of an encrypted DEK is None, so neither a keyring record nor a stored kek_version shows which DEKs are under which key material, see Key versions and rotation;
  • key material that AWS KMS generated cannot be disabled or deleted on its own, and deleted or expired imported key material puts the key in PendingImport, where AWS KMS refuses every operation with it;
  • AWS KMS does not rotate an asymmetric key: a rotation is a new key, and so a new keyring, see Asymmetric KEKs;
  • a signing key is named by its key id or key ARN, and an alias fails at creation, see Signing;
  • BigQuery does not read AWS KMS values, and Tink reads a keyring’s keysets only for a key named by its ARN, see Choose a provider and a backend.

Errors

An error AWS KMS returned keeps its AWS error code, such as IncorrectKeyException or NotFoundException, and the message AWS KMS returned. An EncryptionError keeps the SDK error as its root cause. A response without the encrypted DEK, the plaintext DEK or the random bytes it was asked for fails with AWS_ERROR, an EncryptionError. Which errors are a NetworkError and which an EncryptionError is in Retries. AwsKmsSigningProvider returns the same codes, with a SignatureError where the encryption provider returns an EncryptionError.

Azure Key Vault

Feature azure-kms-encryption, or one of the TLS variants in Cargo features.

AzureKmsKeyRef names the key by the vault URL and the key name. Without a key version, the latest version encrypts new DEKs. Each encrypted DEK records the version that encrypted it, and the decryption uses that version, so DEKs encrypted before a rotation still decrypt afterwards.

This page specifies AzureKmsProvider. To compare it with the other KMS providers, read Choose a provider and a backend. For the rights the applications and the administration need, read Permissions: applications and administration. For rotating the KEK, read Rotate keys and re-encrypt values.

The provider takes any Azure credential, for example one from azure_identity:

use kms_aead::backends::AwsLc;
use kms_aead::providers::{AzureKmsKeyRef, AzureKmsProvider};
use kms_aead::KmsAeadEnvelope;
use secret_vault_value::SecretValue;

async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let kms_ref = AzureKmsKeyRef::new(
    "https://my-vault.vault.azure.net".to_string(),
    "my-key".to_string(),
);

// Azure CLI or Azure Developer CLI credentials for local runs;
// use `azure_identity::ManagedIdentityCredential` in Azure deployments
let credential = azure_identity::DeveloperToolsCredential::new(None)?;

let provider = AzureKmsProvider::new(&kms_ref, credential)?;
let envelope = KmsAeadEnvelope::<AzureKmsProvider, AwsLc>::new(provider)?;

let cipher_text = envelope
    .encrypt(b"orders/1042", &SecretValue::from("secret"))
    .await?;
let _ = cipher_text;
Ok(())
}

Full example available here.

Configuration, authentication and permissions

The provider sends no request until the first encryption or decryption. The principal needs the wrapKey and unwrapKey key operations, Key Vault’s names for encrypting and decrypting a DEK, as in the “Key Vault Crypto User” role.

Options

AzureKmsProviderOptions has:

  • algorithm: an AzureKmsAlgorithm, Key Vault’s alg of the wrapKey and unwrapKey operations, which must suit the key type: RsaOaepSha256 (RSA-OAEP-256) for RSA keys, Aes256KeyWrap (A256KW) for Managed HSM AES keys. The default, DEFAULT_ALGORITHM, is RsaOaepSha256 for every key, so a Managed HSM AES key needs algorithm set to Aes256KeyWrap and the provider built with AzureKmsProvider::with_options. RsaOaepSha1 (RSA-OAEP) is for an RSA key whose encrypted DEKs were written with it. The other AES key wraps, Aes128KeyWrap (A128KW), Aes192KeyWrap (A192KW), Pkcs11AesKeyWrap (CKM_AES_KEY_WRAP) and Pkcs11AesKeyWrapWithPadding (CKM_AES_KEY_WRAP_PAD), are for Managed HSM AES keys too. RSA1_5 is not offered. Encrypted DEKs do not record the algorithm, so it stays fixed for the life of the key;
  • client_options: settings passed to the Azure SDK, such as a custom HTTP transport or retry policy.

A Managed HSM AES key, with Aes256KeyWrap:

use kms_aead::providers::{
    AzureKmsAlgorithm, AzureKmsKeyRef, AzureKmsProvider, AzureKmsProviderOptions,
};

fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let kms_ref = AzureKmsKeyRef::new(
    "https://my-hsm.managedhsm.azure.net".to_string(),
    "my-aes-key".to_string(),
);
let credential = azure_identity::DeveloperToolsCredential::new(None)?;

let provider = AzureKmsProvider::with_options(
    &kms_ref,
    AzureKmsProviderOptions::new().with_algorithm(AzureKmsAlgorithm::Aes256KeyWrap),
    credential,
)?;
let _ = provider;
Ok(())
}

Key versions and rotation

A rotation adds a version to the key, by hand or by the key’s rotation policy. Without a key version in AzureKmsKeyRef, the latest version encrypts new DEKs; with one, that version does, so move it to the new version before a sweep. A sweep with a provider pinned to the old version re-encrypts under the old version. The kek_version() of the encrypted DEK an encryption returns is the version Key Vault encrypted with, read from the kid of its response.

Once the sweep has reached every value, see Re-encrypt DEKs after a KEK rotation, disable the old version: Key Vault refuses to decrypt under it, and enabling it again restores it. Key Vault deletes a key with all its versions and never one version alone, so the old version stays disabled rather than destroyed.

Encrypted DEKs

Key Vault decrypts only with the key version that encrypted, so the provider’s encrypted DEK carries it before Key Vault’s encrypted DEK, in the library’s own layout, see Encrypted DEKs. No Tink client exists for Azure, so Tink does not read the values of this provider, and the plaintext Key Vault encrypts is the raw DEK of 16, 32 or 64 bytes, rather than the DEK as Tink serialises it. Every algorithm takes it, Aes256KeyWrap too, which takes only multiples of 8 bytes. Store the encrypted DEK as it is, see Envelope encryption.

Rolling back a rotation

Pin the old version in AzureKmsKeyRef, and keep the new version enabled: every swept value and every value written since the rotation is under the new version only, and disabling it makes them unreadable until it is enabled again. See Rolling back a rotation.

Asymmetric KEKs

An RSA key of 2048, 3072 or 4096 bits, RSA or RSA-HSM, is an asymmetric KEK, see Asymmetric KEKs. The provider encrypts with it through wrapKey; a 0x02 encrypted DEK moves the encryption into the producer, and the provider decrypts through unwrapKey:

  • AzureKmsProvider::public_key(None) sends GetKey for the latest version, or public_key(Some(&version)) for one, and returns the JSON Web Key’s n and e as the public key of the version the kid of the response names. It fails with ASYMMETRIC_KEK_PUBLIC_KEY for a key whose kty is not RSA or RSA-HSM, whose key_ops lack unwrapKey, or whose kid names no version or another key;
  • a decryption of a 0x02 encrypted DEK sends unwrapKey on the key and the version the encrypted DEK names, with alg RSA-OAEP-256. This path ignores AzureKmsProviderOptions::algorithm, which stays the algorithm of the 0x01 layout;
  • the principal of a reader needs keys/unwrap/action, and the administration also keys/get. “Key Vault Crypto Service Encryption User” carries read, wrap and unwrap and no decrypt. Nobody needs keys/wrap/action.

An existing deployment on an RSA key is under an asymmetric KEK already and needs no re-encryption to move its encryptions to the producers, see Migrating an Azure or Transit RSA deployment. A Managed HSM AES key stays on wrapKey and unwrapKey with Aes256KeyWrap: it is a symmetric KEK and has no public half.

Signing

AzureKmsSigningProvider signs with one version of an EC P-256 key, EC or EC-HSM, with ES256, see Signatures and MACs. Key Vault signs no Ed25519, so the provider’s algorithm is EcdsaP256Sha256. AzureKmsSigningKeyRef names the vault, the key and the version, which a signer requires: it never follows the latest version.

use kms_aead::backends::AwsLc;
use kms_aead::formats::PublicKeyFormat;
use kms_aead::providers::{AzureKmsSigningKeyRef, AzureKmsSigningProvider, KmsKeyVersion};
use kms_aead::signing::Signer;

async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let key_ref = AzureKmsSigningKeyRef::new(
    "https://my-vault.vault.azure.net".to_string(),
    "my-signing-key".to_string(),
    KmsKeyVersion::try_from("4387e9f3d6e14c459867679a90fd0f79".to_string())?,
);
let credential = azure_identity::DeveloperToolsCredential::new(None)?;

let provider = AzureKmsSigningProvider::new(&key_ref, credential)?;
let signer = Signer::<_, AwsLc>::new(provider).await?;

// The public key to publish for the verifiers
let jwk = signer.verifying_key().encode(PublicKeyFormat::Jwk)?;
let _ = jwk;
Ok(())
}

AzureKmsSigningProvider::with_options takes AzureKmsSigningProviderOptions, whose client_options are the settings of the Azure SDK, such as a custom HTTP transport or retry policy, as AzureKmsProviderOptions has them. Creating the provider sends no request and fails with AZURE_KEY_NAME or AZURE_VAULT_URL as AzureKmsProvider does; Signer::new sends the first request.

  • sign calls the sign operation with ES256, the SHA-256 of the pre-image (the exact bytes a signature covers, see Signature and MAC formats) as value and the version in the request path. The result is r || s (the two 32-byte integers of an ECDSA signature, one after the other) as RFC 7518 defines it, 64 bytes; another length fails with SIGNATURE_ENCODING;
  • a response whose kid is not the configured vault, key and version, or has none, fails with SIGNING_KEY_MISMATCH;
  • verifying_key calls get_key with the version and reads the crv, x and y of the JSON Web Key. A key that is not EC or EC-HSM on P-256 fails with SIGNING_ALGORITHM_MISMATCH;
  • the principal needs the sign and get key operations: the data actions Microsoft.KeyVault/vaults/keys/sign/action and Microsoft.KeyVault/vaults/keys/read, which “Key Vault Crypto User” grants.

A rotation is a new key version that a new signer names, see Key ids and rotation.

Limits

  • Encrypted DEKs do not record the algorithm, so it stays fixed for the life of the key, see Options;
  • Key Vault deletes a key with all its versions and never one version alone, so an old version is disabled and not destroyed, see Key versions and rotation;
  • no Tink client exists for Azure, so Tink does not read the values of this provider, see Encrypted DEKs, and BigQuery does not read them either;
  • Key Vault signs no Ed25519, so the signing provider’s algorithm is EcdsaP256Sha256, see Signing.

Errors

A failed request carries Key Vault’s error code, such as Forbidden or KeyNotFound, or AZURE_STATUS_<status> when the response has none. Which statuses are a NetworkError and which an EncryptionError is in Retries. AzureKmsSigningProvider returns the same codes, with a SignatureError where the encryption provider returns an EncryptionError. A decryption of an encrypted DEK in another layout fails with AZURE_ENCRYPTED_DEK_FORMAT, before any request.

HashiCorp Vault Transit

Feature hashicorp-vault-transit-kms-encryption, or one root store and one crypto provider variant, see Cargo features.

The provider encrypts DEKs with a key of the Vault Transit secrets engine. HcVaultTransitKeyRef names the key, and the mount is transit unless set with with_mount.

This page specifies HcVaultTransitProvider. To compare it with the other KMS providers, read Choose a provider and a backend. For the rights the applications and the administration need, read Permissions: applications and administration. For rotating the KEK, read Rotate keys and re-encrypt values.

use kms_aead::backends::AwsLc;
use kms_aead::providers::{HcVaultTransitKeyRef, HcVaultTransitProvider};
use kms_aead::KmsAeadEnvelope;
use secret_vault_value::SecretValue;

async fn example() -> kms_aead::KmsAeadResult<()> {
// VAULT_ADDR, VAULT_TOKEN, VAULT_NAMESPACE, VAULT_CACERT and VAULT_CLIENT_TIMEOUT are read by
// the provider
let key_ref = HcVaultTransitKeyRef::new("orders".to_string());

let provider = HcVaultTransitProvider::new(&key_ref)?;
let envelope = KmsAeadEnvelope::<HcVaultTransitProvider, AwsLc>::new(provider)?;

let cipher_text = envelope
    .encrypt(b"orders/1042", &SecretValue::from("secret"))
    .await?;
let _ = cipher_text;
Ok(())
}

Full example available here.

Configuration, authentication and permissions

The provider reads the address, the token and the namespace from the variables of the Vault CLI, or takes them as options. The token needs update on <mount>/encrypt/<key> and <mount>/decrypt/<key>.

Options

HcVaultTransitProvider::new reads its options from the variables the Vault CLI reads, with HcVaultTransitProviderOptions::from_env: VAULT_ADDR (required), VAULT_TOKEN, VAULT_NAMESPACE, VAULT_CACERT and VAULT_CLIENT_TIMEOUT. An empty variable counts as unset. VAULT_CLIENT_TIMEOUT takes the formats the Vault CLI takes: whole seconds (30), whole days (2d) or a Go duration (30s, 1h30m). Zero, which the Vault CLI reads as no time limit, is refused, as is a value in any other format. HcVaultTransitProvider::with_options takes them from the application:

use kms_aead::providers::{
    HcVaultTransitKeyRef, HcVaultTransitProvider, HcVaultTransitProviderOptions,
    HcVaultTransitToken,
};
use secret_vault_value::SecretValue;
use std::time::Duration;

fn example() -> kms_aead::KmsAeadResult<()> {
let options = HcVaultTransitProviderOptions::new("https://vault.example.com:8200".to_string())
    .with_token(HcVaultTransitToken::try_from(SecretValue::from("hvs.example"))?)
    .with_namespace("team-a".to_string())
    .with_timeout(Duration::from_secs(10));

let provider = HcVaultTransitProvider::with_options(
    &HcVaultTransitKeyRef::new("orders".to_string()).with_mount("transit-eu".to_string()),
    options,
)?;
let _ = provider;
Ok(())
}

The options are:

  • address: the Vault server, such as https://vault.example.com:8200;
  • token: sent with every request. Without one the requests carry no token, which is what a Vault Agent or Vault Proxy with use_auto_auth_token expects;
  • namespace: the Vault Enterprise namespace of the mount;
  • ca_certificate: a PEM file with CA certificates for a server whose certificate comes from a private CA. The file adds to the root store and does not replace it, unlike VAULT_CACERT in the Vault CLI, so a server with a certificate from any public CA in the root store is trusted as well;
  • timeout: the time limit for one request, from opening the connection to the last byte of the response, 60 seconds by default.

The provider sends no request when it is created, so a wrong token or an unreachable server fail the first encryption or decryption. An http address to a host other than localhost or a loopback address logs a WARN event at creation, since the token and the DEKs then cross the network unencrypted.

Key versions and rotation

The encrypted DEK is the Transit ciphertext, such as vault:v1:.... It names the key version, so it still decrypts after the key is rotated. The KMS spans record that version as kek_version, and so does the kek_version() of the encrypted DEK an encryption returns: the N of vault:vN:, as min_decryption_version counts it.

The decrypt names the configured key in its URL, so Vault refuses a ciphertext of another key.

A rotation is <mount>/keys/<key>/rotate, and the new version encrypts every DEK after it. Once the sweep has reached every value, see Re-encrypt DEKs after a KEK rotation, disable the old versions by setting min_decryption_version in the key’s configuration to the new version: Vault then refuses to decrypt under older versions, with VAULT_STATUS_400, and lowering it again restores them. Once nothing needs them, the backups included, min_available_version and a trim of the key delete the older versions for good.

Rolling back a rotation

Vault Transit encrypts under the latest version of the key, since the provider names no version in its request, and no older version becomes the latest again: a rotation is undone by rotating once more and sweeping to that third version. Keep the new version enabled until then, since every swept value and every value written since the rotation is under it only. See Rolling back a rotation.

Asymmetric KEKs

A Transit key of the type rsa-2048, rsa-3072 or rsa-4096 is an asymmetric KEK, see Asymmetric KEKs:

  • HcVaultTransitProvider::public_key(None) reads <mount>/keys/<key> for the latest version, and public_key(Some(&version)) for one, and returns the PEM public key of that version, for the producers. It fails with ASYMMETRIC_KEK_PUBLIC_KEY for a key of another type or a version the key does not list;
  • a decryption of a 0x02 encrypted DEK sends <mount>/decrypt/<key> with the ciphertext vault:v<version>: and the standard base64 of the RSA block, padding_scheme oaep and hash_algorithm sha2-256. Both are always set and never left to the server’s defaults;
  • the token of a reader needs update on <mount>/decrypt/<key>, and the administration also read on <mount>/keys/<key> or on <mount>/export/public-key/<key>. Nobody needs update on <mount>/encrypt/<key>.

Signing

HcVaultTransitSigningProvider signs with one version of a Transit key of the type ed25519 or ecdsa-p256, see Signatures and MACs. HcVaultTransitSigningKeyRef names the key and the mount, transit unless set with with_mount, and adds the version and the algorithm: Ed25519 for an ed25519 key and EcdsaP256Sha256 for ecdsa-p256. The version is required and never zero, so a signer never signs with the latest version.

use std::num::NonZeroU32;

use kms_aead::backends::AwsLc;
use kms_aead::formats::PublicKeyFormat;
use kms_aead::providers::{HcVaultTransitSigningKeyRef, HcVaultTransitSigningProvider};
use kms_aead::signing::{Signer, SigningAlgorithm};

async fn example() -> kms_aead::KmsAeadResult<()> {
// VAULT_ADDR, VAULT_TOKEN, VAULT_NAMESPACE, VAULT_CACERT and VAULT_CLIENT_TIMEOUT are read by
// the provider
let key_ref = HcVaultTransitSigningKeyRef::new(
    "invoices".to_string(),
    NonZeroU32::MIN,
    SigningAlgorithm::Ed25519,
);

let provider = HcVaultTransitSigningProvider::new(&key_ref)?;
let signer = Signer::<_, AwsLc>::new(provider).await?;

// The public key to publish for the verifiers
let jwk = signer.verifying_key().encode(PublicKeyFormat::Jwk)?;
let _ = jwk;
Ok(())
}

HcVaultTransitSigningProvider::with_options takes the options of HcVaultTransitProviderOptions. Creating the provider sends no request; Signer::new sends the first one.

  • sign posts to <mount>/sign/<key> with input, key_version, hash_algorithm sha2-256 and marshaling_algorithm jws. The input is the base64 of the pre-image (the exact bytes a signature covers, see Signature and MAC formats) for Ed25519, and for P-256 the base64 of its SHA-256 with prehashed set;
  • Vault answers vault:vN:<base64url> with the 64-byte Ed25519 signature, or r || s (the two 32-byte integers of an ECDSA signature, one after the other) for P-256. An N other than the configured version fails with SIGNING_KEY_MISMATCH, and a signature that is not base64url without padding or not 64 bytes with SIGNATURE_ENCODING;
  • verifying_key reads <mount>/keys/<key> and takes the public_key of the configured version: base64 of the raw key for Ed25519, PEM for P-256. A key of another type fails with SIGNING_ALGORITHM_MISMATCH, and a version the key does not list with INVALID_PUBLIC_KEY;
  • the token needs update on <mount>/sign/<key> and read on <mount>/keys/<key>.

A rotation is <mount>/keys/<key>/rotate, and a new signer names the new version, see Key ids and rotation.

Limits

  • The latest version of the key always encrypts, and no older version becomes the latest again, see Key versions and rotation;
  • min_decryption_version disables every version below it at once;
  • DEKs always come from the backend’s CSPRNG: Vault Transit has no KMS random generator in the provider, see KMS random generators;
  • BigQuery does not read Vault Transit values, and Tink reads a keyring’s keysets with Tink for Go only, see Choose a provider and a backend.

Errors

A response with an error status is VAULT_STATUS_<status>. VAULT_HTTP and VAULT_TIMEOUT are for a request that got no complete response, and VAULT_RESPONSE, VAULT_RESPONSE_TOO_LARGE and VAULT_CIPHERTEXT for a response or an encrypted DEK that cannot be read. Which codes are a NetworkError and which an EncryptionError is in Retries. HcVaultTransitSigningProvider returns the same codes, with a SignatureError where the encryption provider returns an EncryptionError. Invalid options fail at creation with VAULT_INVALID_OPTIONS, or VAULT_TLS when the TLS configuration cannot be built. A request body that cannot be serialised fails with VAULT_REQUEST, a SystemError, before any request is sent.

Local KMS

No Cargo feature: the local providers are in every build, see Cargo features.

LocalKmsProvider encrypts DEKs with a key encryption key the process holds, with AES-256-GCM on the backend it is built with. It is for:

  • development and tests without a cloud KMS;
  • single-host installs where the operator protects the KEK.

kms-aead builds one only when the application calls one of its constructors; no provider falls back to it. Each constructor logs one INFO event naming the KEK id, its versions and where each version came from (ephemeral, file, env or secret), never the key.

This page specifies LocalKmsProvider and the local signing and asymmetric providers. To compare them with the cloud KMS providers, read Choose a provider and a backend. To run an application and its tests without a cloud account, read Develop and test without a cloud. The first example is in Tests and development.

Configuration, authentication and permissions

No credentials and no permissions apply: the process holds the KEK, and protecting it is the operator’s job, see Limits.

KEK ids and versions

A LocalKekId names the KEK: 1 to 255 bytes of ASCII alphanumerics, -, _ and .. Every encrypted DEK records it, and a decryption refuses a DEK encrypted under another id. The id is also the key of the DEK cache, see DEK caching and reuse, so one id must name one set of KEK material: two providers with the same id and different keys share cache entries.

A provider holds one or more LocalKek versions of 32 bytes each. The highest version encrypts new DEKs unless with_encrypting_version names another, and every version it holds decrypts. Each encrypted DEK records its version, so adding a new version keeps the DEKs encrypted under older ones readable.

A KEK comes from one of three loaders, each taking the SymmetricKeyFormat the material is in: Raw, the 32 bytes themselves, Base64, their standard base64 with trailing whitespace allowed, or Jwk, an oct JSON Web Key. The format is always named and never guessed from the bytes:

  • LocalKek::from_secret(version, material, format): bytes the application already holds, such as a key an operator unseals with their own tool (systemd-creds, a TPM, sops, age);
  • LocalKek::from_file(version, path, format): the material in a file. The file must be a regular file of at most 32 KiB. No permission or ownership check runs: restricting who can read or replace the file is the operator’s job;
  • LocalKek::from_env(version, variable, format): the material in an environment variable. Raw takes the variable’s bytes as the key, which an environment holds only when none of them is 0x00. Be aware the variable stays in the process environment for the life of the process: the same user can read it through /proc/<pid>/environ, and every child process inherits it.

Jwk reads the JSON object of RFC 7518 section 6.4, where k is the 32 key bytes in base64url without padding:

{"kty": "oct", "k": "QkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkI"}

kty must be oct. alg is optional and must be A256GCM or A256KW when present; kid, use, key_ops and any other member are ignored. A k in padded or standard base64, or one that does not decode to 32 bytes, is refused. There is no PEM form of a symmetric key, since no standard gives it a label.

use std::num::NonZeroU32;

use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{LocalKek, LocalKekVersion};
use secret_vault_value::SecretValue;

fn example() -> kms_aead::KmsAeadResult<()> {
let jwk = r#"{"kty": "oct", "k": "QkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkJCQkI"}"#;
let kek = LocalKek::from_secret(
    LocalKekVersion::from(NonZeroU32::MIN),
    SecretValue::from(jwk),
    SymmetricKeyFormat::Jwk,
)?;
let _ = kek;
Ok(())
}

Errors name the file or the variable, never its content. For the format an older release assumed in each loader, see Loading a local KEK.

Tests and development

An ephemeral provider has one random version-1 KEK that lives as long as the provider, so the DEKs it encrypts cannot be decrypted once the process exits. It suits tests:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::KmsAeadEnvelope;
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tests".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

let encrypted = envelope
    .encrypt(b"orders/1042", &SecretValue::from("secret"))
    .await?;
let decrypted: SecretValue = envelope.decrypt(b"orders/1042", &encrypted).await?;
assert_eq!(decrypted, SecretValue::from("secret"));
Ok(())
}

For a development environment whose data outlives a run, keep a KEK in a variable or a file. Generate one with:

openssl rand -base64 32
use std::num::NonZeroU32;

use kms_aead::backends::Ring;
use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{LocalKek, LocalKekId, LocalKekVersion, LocalKmsProvider};

fn example() -> kms_aead::KmsAeadResult<()> {
let version = LocalKekVersion::from(NonZeroU32::MIN);
let provider = LocalKmsProvider::<Ring>::new(
    LocalKekId::try_from("dev".to_string())?,
    vec![LocalKek::from_env(version, "APP_DEV_KEK", SymmetricKeyFormat::Base64)?],
)?;
let _ = provider;
Ok(())
}

A VM or a single host

On a host, keep the KEK out of the environment. With systemd, encrypt it with systemd-creds, bound to the host’s TPM where it has one, and let systemd pass it to the service as a credential:

openssl rand -base64 32 | systemd-creds encrypt --name=kek-v1 - /etc/credstore.encrypted/kek-v1
[Service]
LoadCredentialEncrypted=kek-v1:/etc/credstore.encrypted/kek-v1

systemd decrypts it into $CREDENTIALS_DIRECTORY, readable only by the service:

use std::num::NonZeroU32;
use std::path::PathBuf;

use kms_aead::backends::AwsLc;
use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{LocalKek, LocalKekId, LocalKekVersion, LocalKmsProvider};

fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let credentials = PathBuf::from(std::env::var("CREDENTIALS_DIRECTORY")?);
let version = LocalKekVersion::from(NonZeroU32::MIN);

let provider = LocalKmsProvider::<AwsLc>::new(
    LocalKekId::try_from("orders-host-1".to_string())?,
    vec![LocalKek::from_file(version, &credentials.join("kek-v1"), SymmetricKeyFormat::Base64)?],
)?;
let _ = provider;
Ok(())
}

To rotate, add kek-v2 the same way and list both versions, as the next section describes.

Key versions and rotation

Every version in the provider’s list decrypts, and the highest one encrypts unless with_encrypting_version names another. The kek_version() of the encrypted DEK an encryption returns is the version that encrypted, in decimal. A process that does not list a version fails on a DEK under it with LOCAL_KEK_UNKNOWN_VERSION, so a rotation without downtime takes two deploys:

  1. list the new version in every process, with with_encrypting_version keeping the current one encrypting;
  2. once every process lists the new version, drop with_encrypting_version, or point it at the new version, so the new version encrypts.
use std::num::NonZeroU32;

use kms_aead::backends::Ring;
use kms_aead::formats::SymmetricKeyFormat;
use kms_aead::providers::{LocalKek, LocalKekId, LocalKekVersion, LocalKmsProvider};
use secret_vault_value::SecretValue;

fn example(
    kek_v1: SecretValue,
    kek_v2: SecretValue,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let v1 = LocalKekVersion::from(NonZeroU32::try_from(1)?);
let v2 = LocalKekVersion::from(NonZeroU32::try_from(2)?);

// The first deploy: version 2 decrypts, version 1 still encrypts
let provider = LocalKmsProvider::<Ring>::new(
    LocalKekId::try_from("orders".to_string())?,
    vec![
        LocalKek::from_secret(v1, kek_v1, SymmetricKeyFormat::Raw)?,
        LocalKek::from_secret(v2, kek_v2, SymmetricKeyFormat::Raw)?,
    ],
)?
.with_encrypting_version(v1)?;
let _ = provider;
Ok(())
}

A version that is not in the list fails with_encrypting_version with LOCAL_KEK_VERSIONS.

Then sweep, see Re-encrypt DEKs after a KEK rotation, and check with a provider that lists the new version alone, before the deploy that drops the old version, so that a DEK the sweep missed fails the check and no read in the application. Dropping the old version from the list disables it, and listing it again restores it. Destroying it means destroying every copy of its material, backups included.

Rolling back a rotation

Point with_encrypting_version at the old version, and keep the new version in the list: every swept value and every value written since the rotation is under the new version only, and dropping it makes them unreadable until it is listed again. See Rolling back a rotation.

Asymmetric KEKs

LocalAsymmetricKmsProvider is the local KMS with an RSA key pair per version, for the same uses as LocalKmsProvider, see Asymmetric KEKs. A LocalAsymmetricKek is one version: an RSA private key of 2048, 3072 or 4096 bits in PKCS#8, zeroised on drop. 2048 bits is deprecated and stays for the keys that exist. The loaders have the names of LocalKek’s and take a PrivateKeyFormat from kms_aead::formats: Pkcs8Der, the DER bytes, or Pkcs8Pem, a PRIVATE KEY PEM block, as openssl genpkey writes it. The format is never guessed from the bytes, and a file is at most 32 KiB. from_env reads the PEM text for Pkcs8Pem, and for Pkcs8Der the standard base64 of the DER, since a variable holds text.

let version = LocalKekVersion::from(NonZeroU32::MIN);
let provider = LocalAsymmetricKmsProvider::<AwsLc>::new(
    LocalKekId::try_from("dev".to_string())?,
    AsymmetricKekAlgorithm::RsaOaepSha256,
    vec![LocalAsymmetricKek::from_file(version, &path, PrivateKeyFormat::Pkcs8Pem)?],
)?;

// The public half of the encrypting version, for the producers
let public_key = provider.public_key(None)?;
  • the KEK id names one KEK, symmetric or asymmetric, never both, and the version list, the encrypting version and the rotation work as for the symmetric KEK;
  • an encrypted DEK is the 0x02 layout with the KEK id and the decimal version. A decryption fails with ASYMMETRIC_ENCRYPTED_DEK_FORMAT, LOCAL_KEK_ID_MISMATCH, LOCAL_KEK_UNKNOWN_VERSION or DECRYPT;
  • LocalAsymmetricKmsProvider::ephemeral has one generated version-1 key of 2048 bits, for tests;
  • it needs a backend with RSA: aws-lc-rs or RustCrypto. On ring it fails at construction with UNSUPPORTED_ALGORITHM. On RustCrypto the private half decrypts DEKs from trusted sources only, see RustCrypto.

Signing

LocalSigningProvider signs with a private key the process holds, on the backend it is built with, as LocalKmsProvider does for KEKs, see Signatures and MACs. LocalSigningKeyName names the key: 1 to 255 bytes of ASCII alphanumerics, -, _ and .. A LocalSigningKey is one version of it, numbered by a LocalSigningKeyVersion: a PKCS#8 private key, either an Ed25519 key or a P-256 key, and the PKCS#8 names the algorithm. The loaders are those of an asymmetric KEK above, with the same PrivateKeyFormat, see Key formats.

use std::num::NonZeroU32;

use kms_aead::backends::AwsLc;
use kms_aead::formats::{PrivateKeyFormat, PublicKeyFormat};
use kms_aead::providers::{
    LocalSigningKey, LocalSigningKeyName, LocalSigningKeyVersion, LocalSigningProvider,
};
use kms_aead::signing::Signer;

async fn example() -> kms_aead::KmsAeadResult<()> {
let key = LocalSigningKey::from_env(
    LocalSigningKeyVersion::from(NonZeroU32::MIN),
    "APP_SIGNING_KEY",
    PrivateKeyFormat::Pkcs8Pem,
)?;
let provider = LocalSigningProvider::<AwsLc>::new(
    LocalSigningKeyName::try_from("invoices".to_string())?,
    vec![key],
)?;
let signer = Signer::<_, AwsLc>::new(provider).await?;

// The public key to publish for the verifiers
let jwk = signer.verifying_key().encode(PublicKeyFormat::Jwk)?;
let _ = jwk;
Ok(())
}
  • the highest version signs, or the one with_signing_version names, and verifying_keys returns the public keys of every version as a VerifyingKeySet for the published set. A rotation is two deploys: list the new version while the current one signs and publish the new public key, then let the new version sign. Dropping a version from the list stops its export, see Key ids and rotation;
  • sign never fails with a network error, and verifying_key makes no call;
  • LocalSigningProvider::ephemeral has one random version-1 key of the algorithm it names, for tests. Its signatures verify only against a set that holds its verifying key, so a test builds the verifier from the provider.

Limits

  • No IAM, no audit log and no HSM. Protecting the KEK, at rest and in backups, is the operator’s job;
  • Every DEK encryption is one AES-256-GCM encryption with a random 96-bit nonce, so a KEK version is safe for about 2^32 encryptions, see Nonces. With the per-call envelope every value costs one encryption: a host encrypting 1,000 values per second spends 2^32 encryptions in 50 days. Use DEK caching and reuse so that one encryption serves many values, and add a new KEK version before the budget is spent;
  • Crypto-shredding means destroying every copy of the KEK, backups included;
  • DEKs encrypted by a local KEK cannot be exported to BigQuery, which decrypts with Cloud KMS;
  • A LocalSigningProvider keeps its private key in process memory for its life: whoever reads that memory, a core dump or a swap file included, signs as the application does. Removing the key from every verifier’s set revokes a compromised key.

Errors

An encryption fails with RANDOM_GENERATOR when the backend’s CSPRNG (its cryptographically secure random number generator) fails. A decryption fails with LOCAL_ENCRYPTED_DEK_FORMAT when the encrypted DEK is not in the local layout, LOCAL_KEK_ID_MISMATCH when it was encrypted under another KEK id, LOCAL_KEK_UNKNOWN_VERSION when the provider does not hold its version, and DECRYPT when it is not authentic under that version.

Creating a provider fails with INVALID_LOCAL_KEK_ID for an invalid id, LOCAL_KEK_VERSIONS when the versions are empty or list one version twice, and LOCAL_KEK_SOURCE or LOCAL_KEK_LENGTH when a KEK cannot be read or is not 32 bytes. An asymmetric provider fails with ASYMMETRIC_KEK_PRIVATE_KEY for private key bytes that are not in the named format or not an RSA key of 2048, 3072 or 4096 bits.

A LocalSigningProvider fails at creation with LOCAL_SIGNING_KEY_VERSIONS when the versions are empty or list one twice, LOCAL_SIGNING_KEY_FORMAT when the backend refuses a key, and DUPLICATE_KEY_ID when two versions share a key id. A loader fails with LOCAL_SIGNING_KEY_SOURCE when a file or a variable cannot be read, and with LOCAL_SIGNING_KEY_FORMAT for bytes that are not the named format. A name that is not valid fails with INVALID_LOCAL_SIGNING_KEY_NAME, and sign fails with SIGN, a SignatureError, when the backend fails to sign.

Asymmetric KEKs

An asymmetric KEK is a KMS key pair whose public half encrypts data encryption keys and whose private half decrypts them. A producer holding the public key encrypts DEKs in its own process, with no KMS right and no KMS call, and encrypts values under them. A reader decrypts the DEKs through the KMS, which checks its permission and logs the call.

Use one for producers that may encrypt and must never decrypt: a service that writes records it does not read back, a batch job that fills a table, a process outside the KMS’s reach. The library encrypts DEKs with RSA-OAEP (RSA encryption with Optimal Asymmetric Encryption Padding, RFC 8017), SHA-256 and an empty label, AsymmetricKekAlgorithm::RsaOaepSha256, on RSA keys of 3072 bits for a new key; 2048 and 4096 are accepted, and 2048 is deprecated. Cloud KMS, AWS KMS, Azure Key Vault, Vault Transit and the local KMS decrypt it.

This page specifies the keys, the three sides of a deployment, the public key and what the compile-time guarantee covers. To build a deployment that accepts data from producers that cannot read it back, read Accept data from partners and devices that cannot read it back first. A keyring under an asymmetric KEK needs signed records, see Protect the keyring record.

Which way the keys go

With an asymmetric KEK the public key encrypts and the private key decrypts, as in every public-key encryption. The other direction is a signature, see Signatures and MACs:

SignatureAsymmetric KEKSymmetric KEK
Public keyverifies; anyone holding it checks the bytesencrypts DEKs; producers hold it, with no KMS rightnone
Private keysigns, inside the KMSdecrypts DEKs, inside the KMS, for the readersthe one key, inside the KMS
Who may producethe holder of the private key onlyanyone holding the public keyprincipals with the KMS encrypt right
Givesorigin and integrityconfidentialityconfidentiality

Any holder of the public key can produce a value that the readers decrypt, so an asymmetric KEK gives no origin. Data that must be both confidential and attributable is encrypted and then signed.

Producers and readers

A deployment has three sides:

SideHoldsKMS rightCalls
Producerthe public key, pinned in its configurationnoneKmsAeadEnvelope::encrypt over a PublicKeyKekProvider
Application, or any readera KMS providerasymmetric decrypt on the keyKmsAeadEnvelope::decrypt, or a Keyring
Administrationthe public key and a KMS provider, in an AsymmetricKekProviderasymmetric decrypt, and read of the public keythe KeyringAdmin calls and the re-encryptions

The readers keep the providers they have. A provider tells a DEK that a public key encrypted from one the KMS encrypted by its first byte, and decrypts both. The producer is an envelope writer and encrypts randomised values only: a beacon and a deterministic value both need a key’s plaintext, which only a reader decrypts. A keyring never has a producer, since encrypting under a keyring version needs the version’s plaintext DEK. What an asymmetric KEK changes in a keyring is who encrypts new versions’ DEKs, the administration with the public key.

use kms_aead::backends::AwsLc;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalAsymmetricKmsProvider, LocalKekId, PublicKeyKekProvider};
use kms_aead::{AsymmetricKekAlgorithm, AsymmetricKekPublicKey, Encrypted, KmsAeadEnvelope};
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
// The reader's provider: a cloud KMS provider in production
let reader_provider = LocalAsymmetricKmsProvider::<AwsLc>::ephemeral(
    LocalKekId::try_from("orders".to_string())?,
    AsymmetricKekAlgorithm::RsaOaepSha256,
)?;

// The administration hands the public key to the producers as a JSON document
let document = reader_provider.public_key(None)?.to_json()?;

// The producer: no KMS client, and no call that decrypts
let public_key = AsymmetricKekPublicKey::try_from_json(&document)?;
let producer = KmsAeadEnvelope::<PublicKeyKekProvider<AwsLc>, AwsLc>::new(
    PublicKeyKekProvider::new(public_key)?,
)?;
let encrypted: Encrypted<SecretValue, Envelope> = producer
    .encrypt(b"orders/1042", &SecretValue::from("4111 1111 1111 1111"))
    .await?;

// The reader decrypts the DEK through its KMS
let reader =
    KmsAeadEnvelope::<LocalAsymmetricKmsProvider<AwsLc>, AwsLc>::new(reader_provider)?;
let decrypted: SecretValue = reader.decrypt(b"orders/1042", &encrypted).await?;
assert_eq!(decrypted, SecretValue::from("4111 1111 1111 1111"));
Ok(())
}

Full example available here.

The KMS rights per provider are in Under an asymmetric KEK. No side needs a KMS encrypt right. Be aware the KMS audit log does not show who encrypted a DEK: the encryption is a local operation. The decrypt log stays.

The public key

An AsymmetricKekPublicKey holds the key and what a reader needs to decrypt:

  • the KEK, a KekRef: the KMS and the key’s name there, as the reader’s provider names it;
  • the KEK version, where the KMS decrypts with a named one: the CryptoKeyVersion number on Cloud KMS, the 32-character version on Key Vault, the Transit version, the local version. AWS KMS has no versions, and AsymmetricKekPublicKey::new refuses a version there, or none where one is needed, with ASYMMETRIC_KEK_PUBLIC_KEY;
  • the algorithm;
  • the key, in a named PublicKeyFormat: SpkiDer as AWS KMS returns it, SpkiPem as openssl, Cloud KMS and Transit write it, or Jwk as Key Vault returns it. Raw has no meaning for an RSA key.

The administration fetches it with the read right of the public key, on the provider it holds: GcpKmsProvider::public_key(&version), AwsKmsProvider::public_key(), AzureKmsProvider::public_key(None) for the latest version, HcVaultTransitProvider::public_key(None) and LocalAsymmetricKmsProvider::public_key(None). Each reads the version from the KMS’s response, so the key and the version belong together.

The public key reaches a producer as the rest of its configuration does. A producer that takes it from an unauthenticated place encrypts for whoever supplied it, and the reader’s KMS decrypts nothing. Every provider that holds the key logs its fingerprint, the SHA-256 of the SubjectPublicKeyInfo, at INFO, and PublicKeyKekProvider::pinned fails with ASYMMETRIC_KEK_MISMATCH when the key has another fingerprint than the operator expects. Encrypt one test value and decrypt it with a reader before a new producer writes anything that matters.

What each backend does

RingAwsLcRustCrypto
Encrypt with a public keyno: UNSUPPORTED_ALGORITHM at constructionyesyes
Decrypt through a cloud KMSyesyesyes
Local KMS private halfnoyesyes

A producer or a local private half on Ring fails at construction with KmsAeadError::UnsupportedAlgorithm. A reader on Ring needs nothing of RSA. The rsa crate that the rustcrypto feature adds, and why a local KMS on RustCrypto decrypts DEKs from trusted sources only, are in Crypto backends.

The compile-time guarantee

PublicKeyKekProvider implements KmsAeadEncryptionProvider and not KmsAeadDecryptionProvider. Every call that decrypts a DEK or a value requires the second: decrypt, the *_with_encrypted_dek calls, beacon, reencrypt_dek, DekCache::with_dek and every keyring. Over a producer none of them compiles, so an encrypt-only deployment holds whatever its IAM policy says.

The guarantee covers the producer’s calls into the library. A DEK that generate_encrypted_dek returns is in the producer’s hands, and it decrypts its own writes with it through AeadCipher::decrypt_bare. Other code in the process is outside the guarantee: a type of the application’s own that implements KmsAeadDecryptionProvider under the producer’s KekRef is served from the producer’s DEK cache, and whoever reads the process’s memory reads the cached keys. A process that writes and reads holds a KMS provider, and is a reader.

Keyrings under an asymmetric KEK

The administration opens its registry with an AsymmetricKekProvider; the applications open theirs with the plain KMS provider. create, rotate, change_algorithm and mark_compromised encrypt the new version’s DEK with the public key, and reencrypt_deks decrypts every DEK through the KMS and encrypts it again with the public key. The record does not change.

Be aware that whoever holds the public key can encrypt a DEK of their own and file it in the record. A store writer who does so makes every application decrypt it, and the values encrypted under that version are the writer’s to read. The control is a signed record, see Signing the keyring record. Run every keyring under an asymmetric KEK with RecordSignaturePolicy::Required on every application, and turn it on before the first DEK a public key encrypts. Under any other mode a registry that loads a record holding a DEK encrypted with a public key logs a WARN and decrypts it, and so does a NoRecordSigner admin whose provider is asymmetric when it is built.

A keyring under an asymmetric KEK exports no BigQuery and no Tink keyset, since both readers decrypt the keyset with their KMS client’s symmetric decryption. export_bigquery_keyset, export_tink_keyset and an Encryptor on a field with an Interop fail with INTEROP.

An asymmetric decryption is a heavier KMS operation than a symmetric one: quotas and prices per request are higher for RSA on every KMS. A producer reuses DEKs, with a store-less envelope and a DekReusePolicy, and a keyring holds one DEK per version.

A KEK rotation moves new encryptions to a new version, and every stored DEK keeps decrypting under its own version. The producers hold the version they encrypt under in the public key, so a rotation is also a configuration change of every producer. AWS KMS has no versions: a rotation is a new key, and a keyring stays under the key it was created with.

Migrating an Azure or Transit RSA deployment

An envelope or a keyring on an Azure Key Vault RSA key or a Transit rsa-* key is under an asymmetric KEK already: Key Vault’s wrapKey operation, which encrypts a DEK, is the RSA-OAEP encryption its public key would make. Nothing stored has to be re-encrypted:

  1. upgrade every reader first to a version that reads a DEK encrypted with a public key, see Readers before producers;
  2. for a keyring, turn record signing on before any DEK is encrypted with a public key: give the administration a record signer, run sign_record on every keyring, then set RecordSignaturePolicy::Required on every application;
  3. fetch the public key on the administration’s provider and build the AsymmetricKekProvider from it and the KMS provider. Every DEK the administration encrypts from then on is encrypted with the public key; reencrypt_deks moves the existing versions at the administration’s choice;
  4. hand the public key to the producers, which switch from a KMS provider to a PublicKeyKekProvider and drop their KMS rights;
  5. take keys/wrap/action, or update on transit/encrypt/<key>, out of the administration’s grant once no administration that encrypts through the KMS remains.

A keyring on a Cloud KMS or AWS symmetric key cannot move to an asymmetric key: a keyring stays under the KEK it was created with. A new asymmetric key is a new keyring, filled by a sweep.

Threat model and limits

The threat model of Security considerations holds, with these changes:

  • a holder of the public key produces values that decrypt, and plants a DEK in a keyring record unless the applications require signed records;
  • encrypting with the public key leaves no KMS audit log. Who encrypted which DEK is recorded nowhere unless the producer logs it;
  • a producer with a wrong public key encrypts for someone else. Authenticate the channel the key arrives through, pin the fingerprint and test one value;
  • anyone with the public key makes the readers pay for decryptions: a made-up encrypted DEK costs the reader one asymmetric KMS decryption;
  • the header of the encrypted DEK is not authenticated. A change makes the decryption fail and makes no value decrypt;
  • RSA is not quantum-safe. An encrypted DEK kept in a record, a value or a backup decrypts for whoever later runs a cryptographically relevant quantum computer against the public key. Data whose confidentiality must outlast RSA stays under a symmetric KEK until a supported KMS decapsulates a post-quantum KEM (key encapsulation mechanism, the public-key way to agree on a key) in general availability;
  • the producer’s DEK cache holds plaintext DEKs, as every store-less writer’s does;
  • the local KMS’s private half is in process memory, with no IAM, no audit log and no HSM.

The bytes of the encrypted DEK are in Formats, and the codes this chapter mentions are in Error handling.

Keyring and field encryption

The kms-aead-keyring crate encrypts fields of application records under a keyring: the record of one scope’s key versions, such as a tenant’s, kept in a keyring store. Each key version is a data encryption key (DEK) encrypted by a KEK in the KMS, with a lifecycle state.

This page covers what a keyring is, how the registry opens one and hands out handles, and how it shuts down. Read it before the pages below, which hold one topic each.

Compared to an envelope, a keyring value carries a 4-byte key id instead of its encrypted DEK:

  • no KMS encryption on write, and one KMS decryption per key version per DEK cache TTL, on write and read;
  • a fixed framing overhead per value, smaller than an envelope value’s, see Formats of Encrypted;
  • central staged rotation, retirement, destruction and a compromised flag, for every process that uses the keyring;
  • deterministic fields that a data store finds by equality, across rotations;
  • beacons, blind indexes that a data store matches by equality beside randomised fields;
  • values in Tink’s wire format, which Tink and BigQuery read too.

The price is one more piece of infrastructure, the keyring store, which holds one small JSON document per keyring. See Choosing a mode for the comparison with the envelope modes of kms-aead.

Pages in this section

PageRead it to
Key versions and lifecycleread the record, the version states, staged rotation, compromised versions and shredding
Keyring storeschoose, configure and operate a store, or write your own
Record cachetune how fast processes see a change, and know what a process does when the store fails
Encrypted fields and AADencrypt the fields of a record with a structured AAD
Deterministic fieldsfind rows by equality on an encrypted field
Beaconsfind rows by equality beside randomised fields
BigQuery and Tink interopread values in BigQuery SQL or with Tink, and export keysets

Which credentials and permissions an application and an administrative job need is in Permissions: applications and administration.

The registry and its handles

A first keyring, on the memory store with a local KEK, is in With a keyring.

KeyringRegistry::create creates the record, with one active version of each purpose its KeyringAlgorithms name, and fails with RecordExists when there is one already. open_or_create creates it on the first start and opens it on every later one, and admin only opens it. The three return a KeyringAdmin. KeyringRegistry::open returns a Keyring, and fails with RecordMissing when there is no record; it is the application’s call:

use firestore::FirestoreDb;
use kms_aead::backends::Ring;
use kms_aead::providers::{GcpKmsKeyRef, GcpKmsProvider};
use kms_aead_keyring::store::FirestoreKeyringStore;
use kms_aead_keyring::{Keyring, KeyringId, KeyringRegistry, KeyringRegistryOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let key_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);
let registry = KeyringRegistry::<FirestoreKeyringStore, Ring>::new(
    FirestoreKeyringStore::new(FirestoreDb::new("my-project").await?),
    KeyringRegistryOptions::new(),
)?;
let keyring: Keyring<FirestoreKeyringStore, GcpKmsProvider, Ring> = registry
    .open(GcpKmsProvider::new(&key_ref).await?, KeyringId::from_static("tenant-42"))
    .await?;
registry.shutdown(None).await;
Ok(())
}

The registry takes the store and the backend as the type parameters of KeyringRegistry<S, B>, and each call takes the provider, so that the handles are Keyring<S, P, B> and KeyringAdmin<S, P, B>.

A Keyring and a KeyringAdmin of one keyring in one registry share its cached record and its watch, so a write through the KeyringAdmin is seen by every Keyring at once. KeyringAdmin::keyring() returns the Keyring it holds, for id, record, reload, encryption and sweeps inside an administrative job. The example in With a keyring takes its Keyring there too, since the ephemeral local KEK has no second copy to open the keyring with: LocalKmsProvider is not Clone.

Keyring::encryptor takes the cached record, and the Encryptor encrypts under that record’s active versions; decrypt uses the version the value names. A write takes one encryptor and encrypts every encrypted field of the record through it, so that the encryption marker it stores beside them names the versions they are under, see The encryption marker. Neither calls the store while the cached record is fresh, nor the KMS while the version’s DEK is in the DEK cache, see Record cache.

Shutdown

A keyring stays open until the registry shuts down. Where the store has push, the registry follows the change signals of each open keyring with a task on the current tokio runtime. registry.shutdown(None) stops those tasks and the store’s listener and waits for them:

  • a revalidation read in flight finishes and is taken; waits, retry delays and connection attempts stop at once;
  • the open keyrings’ keys are evicted from the DEK cache, and no other key is;
  • the handles keep serving from their cached records, which their TTL revalidates without push, and later opens work too, with no watch.

Await it before the last clone of the registry is dropped: a registry dropped while its tasks run aborts them and logs a WARN. shutdown(Some(timeout)) aborts what still runs after timeout, with a WARN that counts the aborted tasks, and an abort leaves no half-written state.

The bytes of values, key ids and records are in Formats.

Key versions and lifecycle

This page covers the keyring record, the states of a key version, staged rotation, compromised versions and shredding. Read it before building an administrative job or interpreting a version’s state; the step-by-step procedures are in Rotate keys and re-encrypt values.

The record

A keyring record holds:

  • the keyring id, the scope it encrypts for: 1 to 128 ASCII alphanumerics, -, _ and ., except . and .. and ids that start and end with __. Such an id is a Firestore document id, a PostgreSQL key, a part of a GCS object name or an S3 object key, and a BigQuery string without escaping. It is an identifier, not a secret, and appears in spans and errors;
  • the KEK of the provider the keyring was created with;
  • the algorithms new versions use, one per purpose;
  • the re-encryption epoch, which every write that makes a version active moves on by one, and which the application stores beside its records as an EncryptionMarker, see Sweeps;
  • every key version ever created, in creation order, each with its encrypted DEK, its state and, once it was active, its re-encryption range: the markers of the records encrypted under it, see Records under a version.

Every store keeps it as the same JSON document, see Keyring records for the document and the rules every read checks. A record that breaks one fails with RecordInvalid, naming the rule and never the bytes.

The kek field is informational: it catches a keyring opened with the wrong provider, with KekMismatch, and is no security control, since a writer of the record sets it as freely as any other field. What refuses a DEK encrypted under another KEK is the KMS, since every decryption names the configured KEK.

Keyring::record() returns the cached record, to inspect versions and states, such as record.pending(Purpose::Randomized) for the version a rotation staged. An administrative job reads it as admin.keyring().record().

Key ids

Every value carries the key id of the version that encrypted it, and the id names the version’s purpose: randomised, deterministic, beacon or MAC. So a value of one purpose never decrypts under a version of another, and the purpose of a value is known from its bytes. The keyring numbers the versions of each purpose in its own range, in creation order; the ranges are in Keyring key ids. Ids are never reused: a destroyed version keeps its id in the record.

A key id is a kms_aead::KeyId, which the keyring re-exports. value.key_id() reads the key id of a stored value, and version.algorithm().purpose() the purpose of a version. An operation that names a reserved key id fails with ReservedKeyId before any store call.

States

                       promote                          retire           destroy
  rotate ──▶ Pending ──────────▶ Active ──▶ DecryptOnly ──────▶ Retired ─────────▶ Destroyed
                │                   ▲            ▲                 │                   ▲
                │       create ─────┘            └────reinstate────┘                   │
                └───────────────────────────────destroy────────────────────────────────┘
  • Pending: staged by a rotation. Decrypts, and never encrypts until it is promoted. At most one per purpose;
  • Active: encrypts new values and decrypts. At most one per purpose;
  • DecryptOnly: decrypts only. Every version a promotion replaced;
  • Retired: refused on read with KeyVersionRetired. The encrypted DEK stays in the record, so reinstate can undo it;
  • Destroyed: the encrypted DEK is removed from the record, and reads fail with KeyVersionDestroyed.

A promotion moves the previous active version to DecryptOnly, and so does mark_compromised on an active version. Any state right of Active may also be compromised. The flag is set by mark_compromised, with a time and an optional note, and never clears. Pending and Active are never compromised: a compromised active version moves to DecryptOnly in the same write that flags it.

KeyringRegistry::create starts each purpose with an active version. Every later version starts as pending, except the replacement mark_compromised adds for an active version, which is active at once.

The calls that change a version’s state are on a KeyringAdmin, with the admin feature, see Permissions: applications and administration. The other calls of KeyringAdmin are in its rustdoc. The state-changing ones:

CallDoes
rotate(purpose)stages a pending version with the record’s algorithm for the purpose, and returns its key id
promote(key_id)makes the pending version active; the previous active one becomes DecryptOnly. Returns a Rotation with both ids. Refuses with PromotionTooEarly until record_ttl has passed since the version was staged
promote_now(key_id)as promote, without the wait
change_algorithm(algorithm)makes algorithm the one new versions of its purpose use, and stages a version of it as rotate does
mark_compromised(key_id, note)flags the version; for the active version also adds an active replacement in the same write
retire(key_id)DecryptOnly to Retired, once a sweep found no value left under it
reinstate(key_id)Retired back to DecryptOnly, for a value that turned up after all; a compromised flag stays
destroy(key_id)Retired or Pending to Destroyed
dangerously_destroy_all_versions()every version of every purpose to Destroyed, in any state, in one write; the record stays in the store, see below the table
dangerously_shred()destroys every version in one write, as the call above, then deletes the record from the store with the earlier versions the store keeps, see Shredding a keyring

reencrypt_deks() changes no state: it re-encrypts the DEKs under the KEK’s current version, see Re-encrypt DEKs after a KEK rotation.

After dangerously_destroy_all_versions() the keyring encrypts and decrypts nothing, except through a stream encryptor or decryptor already made, see Shredding a tenant with dangerously_shred().

A call that does not apply to the version’s state fails with InvalidTransition, which names the version, its state and the Transition:

  • rotate and change_algorithm while the purpose has a pending version fail with Transition::Rotate, naming that version. Promote or destroy it first;
  • retire, mark_compromised and reinstate refuse a pending version, which never encrypted a value. destroy it instead.

Each call reads the record, applies the change and writes it with a compare-and-swap, a write that succeeds only if the record is still at the revision the call read, reading again after a conflict up to KeyringOptions::cas_retries times, KeyringOptions::DEFAULT_CAS_RETRIES by default, before RecordConflict.

States move forward only: nothing returns to Pending, and Pending moves only to Active or Destroyed. A running process refuses a record that moves a version or the re-encryption epoch backwards, see Record cache.

Staged rotation

A rotation is two calls, so that no process meets a value under a version it does not know yet:

  1. rotate(purpose) stages the version. Every process decrypts under it once its record refreshes, and none encrypts under it;
  2. after a wait, promote(key_id) makes it active. Processes encrypt under it from their next refresh, and every process that reads those values already has the version.

Promote only after the longest time any process may run without a successful refresh of its record, counted from KeyVersion::staged_at(). For a healthy process that time is at most record_ttl, KeyringRegistryOptions::DEFAULT_RECORD_TTL by default. A process whose revalidations fail keeps its cached record for as long as they fail, and logs a WARN on each failure. A deployment whose instances can take hours to update or to reach the store waits as long. Alert on that WARN, see Keyring events: an instance that logs it is one a promotion can leave behind.

promote holds the promotion back for the registry’s record_ttl from staged_at(): before that it fails with PromotionTooEarly, whose remaining is the time left, so the job can sleep that long and call it again. The guard covers healthy processes only. promote_now skips it, for a fleet known to have refreshed since the rotation, such as one restarted since, and for a compromise that cannot wait.

The guard waits the record_ttl of the registry the KeyringAdmin was opened from. Nothing in the record carries the TTL the other processes run with, so the administrative job’s registry needs the longest record_ttl in the fleet. The guard also compares this host’s clock with the staged_at() the staging host’s clock wrote, and a skew between the two clocks shortens or lengthens the wait by as much.

An instance that has not seen the version when it reads a value under it treats the key id as unknown and reloads its record once, at most once per reload_min_interval. When the store answers, the read succeeds after the reload; when it does not, the read fails with KeyVersionUnknown. The wait before promote is what keeps that path rare.

use std::sync::Arc;

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    KeyId, KeyVersionState, KeyringAdmin, KeyringAlgorithms, KeyringError, KeyringId,
    KeyringRecord, KeyringRegistry, KeyringRegistryOptions, Purpose, Rotation,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .open_or_create(provider, KeyringId::from_static("tenant-42"), KeyringAlgorithms::new())
    .await?;

// The administrative job stages the version
let staged: KeyId = admin.rotate(Purpose::Randomized).await?;
let record: Arc<KeyringRecord> = admin.keyring().record();
let pending = record
    .pending(Purpose::Randomized)
    .ok_or("no pending version")?;
assert_eq!(pending.state(), KeyVersionState::Pending);

// Inside the record TTL from `pending.staged_at()`, `promote` refuses and says how long is left
assert!(matches!(
    admin.promote(staged).await,
    Err(KeyringError::PromotionTooEarly(error))
        if error.remaining <= KeyringRegistryOptions::DEFAULT_RECORD_TTL
));

// The job waits that long and promotes it; `promote_now` stands in for the wait here
let rotation: Rotation = admin.promote_now(staged).await?;
assert_eq!(rotation.current, staged);
assert_eq!(rotation.previous, Some(KeyId::new(1)));
registry.shutdown(None).await;
Ok(())
}

Compromised versions

mark_compromised on the active version replaces it with a version that is active at once, not pending. Encrypting under a compromised key has to stop at each process’s next refresh, and a wait before the replacement takes over would leave the leaked key encrypting new values for that long. The cost is the one staged rotation avoids: a process that has not seen the replacement yet reloads its record once, rate-limited, when it meets a value under it. A pending version of the purpose stays pending, to be promoted or destroyed as planned.

The replacement needs a new DEK encrypted. When the KMS cannot encrypt it, in an outage or without the encrypt right, the flag is written alone, a WARN is logged, and the call returns Ok(None): the purpose then has no active version, and encrypt fails with NoActiveVersion until a version is promoted. Once the KMS answers, rotate and promote_now restore one, or promote_now on the pending version if the purpose has one: promote would refuse with PromotionTooEarly for up to record_ttl from the staging. A compromised flag is never held back by the KMS.

destroy and dangerously_destroy_all_versions remove encrypted DEKs from this record only. A backup of the record still holds them, and a keyset exported while the version decrypted holds its key under the same KEK. The KMS decrypts both as long as the KEK version that encrypted them exists, see What survives a shred.

Shredding a keyring

dangerously_shred() is the call for a keyring whose values must become unreadable under a KEK that other keyrings share. It destroys every version in one write, as dangerously_destroy_all_versions does, signed as every lifecycle write is, then deletes the record from the store at the revision that write left. The rules of the two steps, the retry of a shred that failed, and the copies a store keeps beyond its API are in Shredding a tenant with dangerously_shred().

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    KeyringAlgorithms, KeyringError, KeyringId, KeyringRegistry, KeyringRegistryOptions,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let id = KeyringId::from_static("tenant-42");
let admin = registry
    .open_or_create(provider, id.clone(), KeyringAlgorithms::new())
    .await?;
admin.dangerously_shred().await?;

// The id is free: the registry reads the store again and finds no record
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
assert!(matches!(
    registry.open(provider, id).await,
    Err(KeyringError::RecordMissing(_))
));
Ok(())
}

A keyring already gone makes KeyringRegistry::admin fail with RecordMissing, which a job that erases a tenant treats as done. The handles opened before the shred stay on a record with every version destroyed, and the registry’s create makes a new keyring under the id, with key ids from 1.

dangerously_shred() never calls the KMS and leaves every KMS key version as it was. Values encrypted under the keyring stay where they are and decrypt under nothing. Every process that holds the keyring takes the deletion at its next revalidation, see A record gone from the store. A stream decryptor made before the shred keeps decrypting until it is dropped, so a service builds one per request, see Shredding a keyring.

Reading a compromised version

KeyringOptions::compromised_reads decides what decrypt does with a value under a compromised version:

  • CompromisedReadPolicy::Block, KeyringOptions::DEFAULT_COMPROMISED_READS: fails with KeyVersionCompromised, decided on the cached record before any decryption;
  • CompromisedReadPolicy::Allow: decrypts, with one WARN event per value. Use it for the time of a sweep when availability matters more, and be aware the leaked DEK can forge values under that id meanwhile.

decrypt_with_trust decrypts the value whatever the policy, and returns a Decrypted with the value, the key id of the version that decrypted it and its KeyTrust, Trusted or Compromised. It is the call for a sweep. A compromised version’s DEK is decrypted by the provider for that call only and never returns to the DEK cache.

Keyring stores

This page covers the stores the library provides, what a delete removes from each, and how to implement your own. Read it to choose, configure and operate a store; the rights it needs are in Store rights.

A keyring store keeps one record per keyring id, with a compare-and-swap and a delete on each, and optionally signals changes to it. A compare-and-swap is a write that succeeds only when the record is still at the revision the writer read. The library provides:

StoreTypeFeatureRevisionPush
Memorytesting::MemoryKeyringStorenonea write counterevery write
Firestorestore::FirestoreKeyringStorefirestorethe document’s update timea listener on the document
PostgreSQLstore::PostgresKeyringStorepostgresa revision columnNOTIFY
Cloud Storagestore::GcsKeyringStoregcsthe object’s generationnone
S3store::S3KeyringStores3the object’s ETagnone

Each production store below has the same sections: its feature and client, its storage layout, its setup, how a change reaches the other processes, its rights, backups and deletion, and its caveats where it has any.

Every store keeps the record as the same JSON document, and every read checks it. A store with push makes a change reach the other processes within seconds; without push, the record TTL bounds it, see Record cache.

Back the store up, or keep its history, since values cannot be read without the encrypted DEKs in the record, see the runbook. A backup is also a copy of the record that KeyringAdmin::dangerously_shred() does not reach, see What a delete removes.

Memory

MemoryKeyringStore loses its records when the process exits, and with them the encrypted DEK of every version: a value encrypted under a keyring in it, and kept anywhere that outlives the process, never decrypts again. Use it for tests, or for values that never outlive the process.

It lives in kms_aead_keyring::testing for that reason, and is compiled in every build. Clone shares the same records. It keeps each record as its JSON document, as the other stores do, and signals a watch on every write. A delete removes the entry.

Firestore

Feature and client

The firestore feature is the store on firestore-rs without its default features, so it has no TLS root store and no crypto provider, and needs a firestore-rs or gcloud-sdk root store feature from the application, or one of:

  • firestore-tls-roots: the system’s native roots, firestore-rs’s tls-roots, which brings native-tls and so OpenSSL on Linux;
  • firestore-tls-webpki: rustls, with the bundled WebPKI roots for the gRPC connection to Firestore, and no native TLS;

each with firestore-rs’s auth-default-crypto.

FirestoreDb is the firestore crate’s own client: the application builds it with the project, database and credentials it chooses. The version of the firestore crate is part of this crate’s API under the Firestore features.

Storage layout

The record of a keyring is the document kms_keyrings/<keyring id>, whose fields are those of the record’s JSON. A null member is a field of Firestore’s null type, so that the document reads back with the canonical digest that the record’s signature covers. with_collection takes another collection than FirestoreKeyringStore::DEFAULT_COLLECTION, as firestore-rs’s FirestoreCollectionId. A create fails when the document exists, and an update carries the update time it read as its precondition.

Setup

use firestore::FirestoreDb;
use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::store::FirestoreKeyringStore;
use kms_aead_keyring::{Keyring, KeyringId, KeyringRegistry, KeyringRegistryOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let db = FirestoreDb::new("my-project").await?;
let store = FirestoreKeyringStore::new(db);

let registry = KeyringRegistry::<FirestoreKeyringStore, Ring>::new(
    store,
    KeyringRegistryOptions::new(),
)?;
let keyring: Keyring<FirestoreKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .open(provider, KeyringId::try_from("tenant-42".to_string())?)
    .await?;
let _ = keyring;
registry.shutdown(None).await;
Ok(())
}

Change propagation

Each store holds one listen stream, with a target on the document of each keyring it watches.

Rights, backups and deletion

The rights of the application and the administration on the keyring documents are in Store rights. Firestore’s point-in-time recovery restores an earlier record, and what a delete leaves behind is in What a delete removes.

Caveats

Be aware the firestore crate logs every listen event at trace level on its firestore target, documents included, so that level writes encrypted DEKs to the log. Keep it off where the log leaves the administration’s reach.

PostgreSQL

Feature and client

The postgres feature connects through tokio-postgres, with a tokio_postgres::Config and a TLS connector the application chooses. It also enables kms-aead’s postgres feature, which gives Encrypted tokio-postgres’s ToSql and FromSql as BYTEA, see Encrypted fields.

Storage layout

One row per keyring, in a table the operator creates. The library runs no migrations. The table, kms_keyrings unless with_table names another:

CREATE TABLE kms_keyrings (
    id         TEXT PRIMARY KEY,
    record     JSONB NOT NULL,
    revision   BIGINT NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
  • the table name is unqualified, so the connection’s search_path selects the schema;
  • the revision of a row is the server’s clock in microseconds when the row is created, and the larger of that and the previous revision plus one at each write. A row deleted and created again therefore never repeats a revision of the id, which a running process that missed the deletion would take for an unchanged record.

Setup

NoTls for a local database:

use kms_aead_keyring::store::{PostgresKeyringStore, PostgresTable};
use tokio_postgres::{Config, NoTls};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let config: Config = "postgres://app@localhost/app".parse()?;
let store: PostgresKeyringStore<NoTls> = PostgresKeyringStore::new(config, NoTls)
    .with_table(PostgresTable::try_from("tenant_keyrings".to_string())?);
let _ = store;
Ok(())
}

tokio-postgres-rustls’s MakeRustlsConnect for production, here with the platform’s root certificates:

use kms_aead_keyring::store::PostgresKeyringStore;
use rustls::{ClientConfig, RootCertStore};
use tokio_postgres::Config;
use tokio_postgres_rustls::MakeRustlsConnect;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut roots = RootCertStore::empty();
roots.add_parsable_certificates(rustls_native_certs::load_native_certs().certs);
let tls = MakeRustlsConnect::new(
    ClientConfig::builder()
        .with_root_certificates(roots)
        .with_no_client_auth(),
);
let config: Config = "postgres://app@db.internal/app?sslmode=require".parse()?;
let store: PostgresKeyringStore<MakeRustlsConnect> = PostgresKeyringStore::new(config, tls);
let _ = store;
Ok(())
}

postgres-native-tls’s MakeTlsConnector works the same way for the platform TLS library.

Change propagation

Every write sends NOTIFY <table>, '<keyring id>' when it commits, through pg_notify in the same statement, and so does a delete, which removes the row at its revision.

The store opens at most two connections, whatever the number of keyrings on it:

  • the query connection, on the first read or write. When it is lost, the call that finds it lost fails, and the next call connects again. Concurrent calls wait for one attempt;
  • the listener connection, on the first watch, shared by every keyring that watches. It closes when the last watch is dropped. When it is lost, every keyring hears of it, the store reconnects after a delay that doubles from 0.5 to 30 seconds, and the keyrings revalidate.

Clones of the store share both connections. Set connect_timeout on the Config to bound each attempt: calls wait for the attempt in progress.

Rights, backups and deletion

The rights of the application and the administration on the table are in Store rights, and what a delete leaves behind is in What a delete removes.

Caveats

PostgreSQL lets any session notify any channel. A keyring revalidates at most once per reload_min_interval however many signals arrive, so a stray NOTIFY costs one read.

Cloud Storage

Feature and client

The client is gcloud-sdk’s, built with the credentials, endpoint and TLS stack the application chooses. The gcs feature has no TLS root store, so it needs one of gcloud-sdk’s root store features from the application, or one of:

  • gcs-tls-roots: the system’s native roots;
  • gcs-tls-webpki: the bundled WebPKI roots.

Storage layout

Each record is the object kms-keyrings/<keyring id>.json in a bucket, through the google.storage.v2 gRPC API. with_prefix sets another ObjectPrefix than GcsKeyringStore::DEFAULT_PREFIX; one that should read as a folder ends with /. A write is conditional on the generation the writer read, and a revalidation reads the object only when its generation changed.

Setup

use gcloud_sdk::google::storage::v2::storage_client::StorageClient;
use gcloud_sdk::GoogleApi;
use kms_aead_keyring::store::{GcsBucketName, GcsKeyringStore};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client =
    GoogleApi::from_function(StorageClient::new, "https://storage.googleapis.com", None).await?;
let store = GcsKeyringStore::new(client, GcsBucketName::try_from("my-keyrings".to_string())?)?;
let _ = store;
Ok(())
}

Change propagation

Cloud Storage has no change notification the store listens to, so a process sees a change once its record is older than record_ttl, see Record cache.

Rights, backups and deletion

  • the rights of the application and the administration on the bucket are in Store rights;
  • turn on object versioning on the bucket: every record written is then kept as a noncurrent version, to restore from;
  • a delete removes every generation of the object, the noncurrent ones included, so versioning does not keep a shredded record. Soft delete keeps what a delete removes, see What a delete removes.

S3

Feature and client

The client is aws-sdk-s3’s, built with the credentials, region, endpoint and HTTP client the application chooses. The s3 feature enables the SDK’s default HTTPS client, rustls on aws-lc-rs, as kms-aead’s AWS KMS provider does.

Storage layout

Each record is the object kms-keyrings/<keyring id>.json in a bucket of Amazon S3 or of an S3-compatible server. with_prefix sets another ObjectPrefix than S3KeyringStore::DEFAULT_PREFIX; one that should read as a folder ends with /. A create is conditional on no object existing (If-None-Match: *), an update on the ETag the writer read (If-Match), and a revalidation reads the object only when its ETag changed (If-None-Match on the read).

Setup

use aws_config::BehaviorVersion;
use kms_aead_keyring::store::{S3BucketName, S3KeyringStore};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = aws_config::load_defaults(BehaviorVersion::latest()).await;
let store = S3KeyringStore::new(
    aws_sdk_s3::Client::new(&config),
    S3BucketName::try_from("my-keyrings".to_string())?,
);
let _ = store;
Ok(())
}

Change propagation

S3 has no change notification the store listens to, so a process sees a change once its record is older than record_ttl, see Record cache.

Rights, backups and deletion

  • the rights of the application and the administration on the objects are in Store rights;
  • turn on versioning on the bucket: every record written is then kept as a noncurrent version, to restore from;
  • a delete removes every version and delete marker of the object, so versioning does not keep a shredded record, see What a delete removes.

Caveats

S3-compatible servers

A server is S3-compatible for this store when it passes the store conformance suite, kms-aead-keyring/tests/store_conformance.rs. Its checks include the ones a compare-and-swap needs from the server: it refuses a create over an existing object, an update at a stale ETag, and an update of an object that does not exist. A server that writes the object in the last case, as some MinIO releases do, recreates a deleted record on the next administrative write. To run the suite against a server, with the credentials of the environment:

KEYRING_S3_ENDPOINT=http://minio:9000 KEYRING_S3_BUCKET=my-keyrings \
  cargo test -p kms-aead-keyring --features s3 --test store_conformance s3:: -- --ignored

Set the server’s endpoint on the client, and force_path_style(true) when it serves buckets by path, as MinIO does by default. aws-sdk-s3 adds a CRC checksum to every upload by default, which some S3-compatible servers do not accept, and every write of the record then fails there. request_checksum_calculation(RequestChecksumCalculation::WhenRequired) sends a checksum only where the operation requires one, which the store’s PutObject does not:

use aws_config::BehaviorVersion;
use aws_sdk_s3::config::RequestChecksumCalculation;
use kms_aead_keyring::store::{S3BucketName, S3KeyringStore};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = aws_config::defaults(BehaviorVersion::latest())
    .endpoint_url("http://minio:9000")
    .load()
    .await;
let client = aws_sdk_s3::Client::from_conf(
    aws_sdk_s3::config::Builder::from(&config)
        .force_path_style(true)
        .request_checksum_calculation(RequestChecksumCalculation::WhenRequired)
        .build(),
);
let store = S3KeyringStore::new(client, S3BucketName::try_from("my-keyrings".to_string())?);
let _ = store;
Ok(())
}

What a delete removes

KeyringStore::delete is the call KeyringAdmin::dangerously_shred() makes once every version of the record is destroyed, see Shredding a tenant with dangerously_shred(). It removes the record with the copies the store itself keeps. A copy the store keeps outside the reach of its API is the operator’s to delete:

StoreA delete removesThe operator’s
Memorythe entrynothing
Firestorethe document, with its update time as the preconditionthe document served to reads at an earlier time for one hour, and for seven days with point-in-time recovery on; backups and exports
PostgreSQLthe row at its revision, and sends the NOTIFY as a write doesthe row’s earlier versions until a vacuum reclaims them; backups, WAL archives and replicas
Cloud Storageevery generation of the object, noncurrent ones included: the noncurrent generations first, then the live object, conditional on the generation read, then that generationthe bucket’s soft delete keeps every deleted generation restorable for its retention, 7 days by default
S3every version and delete marker of the object: the noncurrent ones first, then the live object with If-Match on its ETag, then the live version, then the delete marker that leftreplication and backups

Point-in-time recovery is Firestore’s retention of every version of a document for up to seven days. Soft delete is Cloud Storage’s retention of a deleted object, which can be restored until the retention ends. A bucket of keyring records turns soft delete off, or counts the retention into the time a shred takes. The WAL is PostgreSQL’s write-ahead log of committed changes.

A lifecycle rule of the bucket that deletes live objects, such as a Cloud Storage Delete rule on age or an S3 expiration of current versions, shreds the keyrings it removes: every running process that holds one takes the deletion at its next revalidation. A rule on noncurrent versions only leaves the live records alone. The condition of the S3 delete holds only on a server that honours If-Match on DeleteObject, as S3 does for general purpose buckets. Community MinIO releases ignore it. The conformance suite checks whether a server honours it.

A delete needs rights a write does not: the administration’s permissions per store are in Store rights.

Your own store

KeyringStore is a trait with five methods, load, revalidate, compare_and_swap, delete and watch, which returns None for a store without push, a Revision type and a KIND, such as StoreKind::Other("spanner"), for spans and errors. When implementing it:

  • write each method as an async fn whose future is Send;
  • implement delete(id, expected), which has no default:
    • on a match, it deletes the record when its stored revision is expected, with every earlier version of it the store keeps, and returns Deletion::Deleted once the store holds no record of the id, also when it held none;
    • on a mismatch, it leaves the record and returns Deletion::Conflict;
    • it returns errors as load does, as KeyringError::Store with StoreOperation::Delete;
    • a delete that fails may have removed part of the earlier versions already, and so may one that conflicts; the caller repeats it with the same expected. This is safe because the keyring deletes a record only in a shred, once every version of it is destroyed, so those versions hold only keys the shred destroys;
    • a store that cannot delete the earlier versions in one step with the live record removes them first, since a record gone from the store reads as shredded and no shred deletes it again;
    • it never gives an id the same revision twice, across a delete too: a revision that restarts at 1 for a record created again lets a process that missed the deletion keep the deleted record;
    • a store with push signals the deletion as a change;
  • read a stored document with KeyringRecord::from_json and write one with KeyringRecord::to_json, so the document is the one every store keeps and every read checks it;
  • keep every member of the document as written, null ones included. A record’s signature covers its canonical digest, and a store that maps the document into fields of its own can drop a null member, as firestore-rs does with a JSON null, which makes every signed record it holds fail with RecordSignatureInvalid. The conformance check a_loaded_record_keeps_the_written_digest holds every store to it, on a create and on an update;
  • build the Stored that load and revalidate return with Stored::new(record, revision), since the struct is #[non_exhaustive];
  • return the client’s errors as KeyringError::Store, with the client’s error as the root cause. Never format the record or the request into an error and never log either, since both carry encrypted DEKs.

MemoryKeyringStore is the reference implementation, see its source, and the conformance suite holds the checks every store passes.

Record cache

Each Keyring keeps its record in the process, and the decrypted DEKs of its versions in kms-aead’s DEK cache. encrypt, decrypt and beacon read both, so the hot path calls neither the store nor the KMS.

This page covers the options of the record cache, when a record is refreshed, and what a process does when the store fails, misbehaves or loses the record. Read it to set how fast a running process sees a change, and to know what an alert on the keyring’s log lines means.

Options

KeyringRegistryOptions configures the record cache of every keyring a registry opens, and its keyring field holds the KeyringOptions of the handles it returns. Each default is a public constant of the type that holds the option:

OptionDefaultWhat it does
record_ttlDEFAULT_RECORD_TTL, 5 minuteshow long the cached record serves without a store call
reload_min_intervalDEFAULT_RELOAD_MIN_INTERVAL, 5 secondsthe least time between two store reads that an unknown key id, a re-encryption under a pending version or a change signal causes
watchDEFAULT_WATCH, truewhether to follow the store’s change signals, where it has them
dek_cacheNone, a new cachethe cache of decrypted DEKs; a new one has kms-aead’s DekCacheOptions::DEFAULT_TTL and DekCacheOptions::DEFAULT_MAX_ENTRIES
keyring.cas_retriesKeyringOptions::DEFAULT_CAS_RETRIES, 5the conflicts a write of a KeyringAdmin retries before RecordConflict
keyring.compromised_readsKeyringOptions::DEFAULT_COMPROMISED_READS, Blockwhat decrypt does with a value under a compromised version, see Lifecycle
use std::time::Duration;

use kms_aead::cache::{DekCache, DekCacheOptions};
use kms_aead_keyring::{KeyringOptions, KeyringRegistryOptions};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let options: KeyringRegistryOptions = KeyringRegistryOptions::new()
    .with_record_ttl(Duration::from_secs(60))
    .with_dek_cache(DekCache::new(
        DekCacheOptions::new().with_ttl(Duration::from_secs(5 * 60)),
    )?);
assert_eq!(options.keyring.cas_retries, KeyringOptions::DEFAULT_CAS_RETRIES);
Ok(())
}

A DekCache may be shared with other keyrings and envelopes.

How the record is refreshed

  • Age: the first call that finds the record older than record_ttl revalidates it with a conditional read, while the other calls keep using it;
  • Change signals: on a store with push, a signal causes a revalidation, at most once per reload_min_interval. Signals inside the interval collapse into the next one;
  • Unknown key ids: a value with a key id the record does not have causes one reload, which concurrent misses share, at most once per reload_min_interval. Values with random key ids then cost at most one store read per interval. A re-encryption of a value under a version the record holds as pending reloads the same way, and shares the same interval: another process encrypted it, so it saw the version active;
  • Own writes: a KeyringAdmin call takes the record it wrote. Every Keyring of the same keyring in the registry shares that cached record, so the process that promotes a version encrypts under it at once.

Keyring::reload reads the record now, past the TTL and the rate limit, for operators and tests.

How late a change is seen

A change written by another process, such as a staged version, a promotion or a compromised flag, reaches a running process:

  • with push: within reload_min_interval of the signal;
  • without push, on Cloud Storage and S3, with watch off, or while the listener is disconnected: once the cached record is older than record_ttl;
  • not until the store answers again, while its revalidations fail: it keeps its cached record, see below.

So record_ttl is the bound to set for how long a compromised version may keep being read somewhere in the fleet, and the least wait between staging a version and promoting it, see Staged rotation. Writers on the old record keep encrypting under the previous version until their record refreshes, and those values decrypt, since the previous version is DecryptOnly.

When the store fails or misbehaves

  • A failed revalidation keeps the cached record in use, logs a WARN and is retried after reload_min_interval. A process that logs it is one that misses every change until the store answers again, so alert on it, see Keyring events;

  • a record gone from the store is taken as a shredded keyring, see A record gone from the store;

  • a refreshed record is taken only if it moves every version forward from the cached one. The process refuses a record with any of these:

    • a version missing;
    • a changed algorithm or creation time;
    • a compromised flag cleared;
    • a state moved back against the lifecycle, such as a version back to Pending;
    • a re-encryption epoch below the cached one, which would give records encrypted under different versions one marker;
    • a re-encryption range moved back, or started or ended at or below the cached epoch, which would leave the records this process encrypted under a version outside its range.

    The process then keeps its record and logs an ERROR naming the first rule broken. reload and a write of a KeyringAdmin return RecordRegressed in that case.

The last rule is the detection of a rewritten or restored record in a running process. A process that starts after such a write has no record to compare with and takes it.

A record gone from the store

A revalidation (by age or change signal), a forced reload, the read before an administrative write and a dangerously_shred() can each find that the store holds no record of the keyring. The process takes it as a shredded keyring:

  • it destroys every version of its cached record in memory, and writes nothing. That evicts the keyring’s keys from the DEK cache, and no other keys;
  • it logs a WARN, or an INFO when the record it held had every version destroyed already, as a shred leaves it, and sets the changed field of the Keyring load span to deleted, see Keyring events. The process that ran the shred logs nothing and sets no field;
  • it stops revalidating and watching the keyring;
  • the keyring’s handles fail before any KMS call: encrypting with NoActiveVersion, reading with KeyVersionDestroyed, and reload with RecordMissing.

The registry’s next open of the id reads the store again. It fails with RecordMissing, or takes a record created since. Handles opened before stay on the destroyed record, and a handle on the destroyed record reads the store no more, also for an administrative call: dangerously_shred() repeated on it returns Ok, and every other call RecordMissing.

How late the process sees the deletion is the bound of how late a change is seen: within reload_min_interval of the signal with push, and once the cached record is older than record_ttl at the next call without. A process that makes no call keeps the plaintext DEK until the DEK cache drops it, see DEK eviction.

The deleted record stays the baseline of the id in the registry, for the checks of a held record: the next record under the id must be signed if the deleted one was, and must not revive a version the deleted record holds destroyed. A keyring created again has other versions and opens; a copy of the record from before the deletion fails with RecordRegressed, so a record restored after an accidental deletion is taken by a new process, not by the one that took the deletion. See Signing the keyring record. The deletion is what KeyringAdmin::dangerously_shred() ends with, see Shredding a tenant with dangerously_shred(), and a deletion by anyone else has the same effect on the process.

DEK eviction

Taking a refreshed record evicts from the DEK cache every key it takes out of use: versions retired, destroyed or newly compromised, and the old bytes of a re-encrypted one. mark_compromised evicts the key from its own process before it returns. A record gone from the store evicts every key of the keyring, and no key of another keyring.

A stream decryptor holds the key derived for its value, never the DEK, until it is dropped. Taking a record that destroys its version, or flags it compromised, does not stop it, see Streaming encryption.

The DEK cache drops expired keys only when it is called. A process that can sit idle while it holds keys calls keyring.dek_cache().purge_expired() on a timer of its own, so the cache’s TTL bounds how long a key stays in memory, see Key lifetime.

Encrypted fields and AAD

This page covers the encrypted value a keyring produces, how to keep it in an application record, and how the keyring builds the additional authenticated data (AAD) that binds a value to its field and row. Read it when you model the encrypted fields of an application; the end-to-end walkthrough is Encrypt personal data and secrets in your database.

Encrypted values

A keyring value is kms-aead’s Encrypted<T, Randomized>, re-exported by the keyring: the bytes to store, which decrypt to a T. T is any type that implements Plaintext, usually an application newtype such as Email, so a field names what it holds. Its layout is in Formats of Encrypted. The keyring encrypts and decrypts it with kms-aead’s AeadCipher::encrypt and decrypt under the key of the version, the calls an application with one fixed key makes itself.

  • value() and into_value() return the bytes;
  • key_id() returns the key id of the version that encrypted it;
  • Encrypted::try_from(bytes), serde and tokio-postgres check stored bytes against the layout when the value is made, and fail on bytes that are no keyring value before any decryption;
  • decrypt checks the key id first, and fails with ReservedKeyId on a reserved id and with KeyPurposeMismatch on a deterministic one, before any store or KMS call;
  • Debug shows the length only. A randomised value has no ==: two values of one plaintext differ.

The plaintext types and their encodings are in Stored values.

In application records

Encrypted is stored as bytes, with serde and the postgres and sqlx features, see Storing. A field of a serde record:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::KmsAeadResult;
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldName, FieldSpec, Keyring, KeyringAlgorithms, KeyringId,
    KeyringRegistry, KeyringRegistryOptions, Plaintext,
};
use secret_vault_value::SecretValue;
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);

#[derive(Serialize, Deserialize)]
struct User {
    id: String,
    email: Encrypted<Email, Randomized>,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
use kms_aead_keyring::KeyringAdmin;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(provider, KeyringId::from_static("tenant-42"), KeyringAlgorithms::new())
    .await?;
let keyring: &Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = admin.keyring();
let id = EntityId::try_from("42")?;
let alice = Email("alice@example.com".to_string());
let user = User {
    id: "42".to_string(),
    email: keyring.encryptor().await.encrypt(&EMAIL.aad(&id), &alice).await?,
};
let stored: Vec<u8> = serde_json::to_vec(&user)?;

let read: User = serde_json::from_slice(&stored)?;
let email: Email = keyring.decrypt(&EMAIL.aad(&id), &read.email).await?;
assert_eq!(email, alice);
registry.shutdown(None).await;
Ok(())
}

PostgreSQL

A BYTEA column, with tokio-postgres:

use kms_aead::backends::Ring;
use kms_aead::providers::LocalKmsProvider;
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::store::PostgresKeyringStore;
use kms_aead_keyring::{Encrypted, EntityId, FieldSpec, Keyring};
use tokio_postgres::{Client, NoTls};
use kms_aead::KmsAeadResult;
use kms_aead_keyring::Plaintext;
use secret_vault_value::SecretValue;
#[derive(Clone)]
struct Email(String);
impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> { self.0.to_plaintext() }
    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

type TenantKeyring = Keyring<PostgresKeyringStore<NoTls>, LocalKmsProvider<Ring>, Ring>;

async fn store_email(
    client: &Client,
    keyring: &TenantKeyring,
    field: &FieldSpec,
    id: &str,
    email: &Email,
) -> Result<(), Box<dyn std::error::Error>> {
    let value: Encrypted<Email, Randomized> = keyring
        .encryptor()
        .await
        .encrypt(&field.aad(&EntityId::try_from(id)?), email)
        .await?;
    client
        .execute("UPDATE users SET email = $1 WHERE id = $2", &[&value, &id])
        .await?;
    Ok(())
}

async fn email_of(
    client: &Client,
    keyring: &TenantKeyring,
    field: &FieldSpec,
    id: &str,
) -> Result<Email, Box<dyn std::error::Error>> {
    let row = client
        .query_one("SELECT email FROM users WHERE id = $1", &[&id])
        .await?;
    let value: Encrypted<Email, Randomized> = row.try_get("email")?;
    Ok(keyring.decrypt(&field.aad(&EntityId::try_from(id)?), &value).await?)
}
fn main() {}

A column holding a value that is no keyring value fails in the decode, before any decryption. The keyring’s sqlx feature binds Encrypted and EncryptionMarker in sqlx the same way, as BYTEA on PostgreSQL, and turns on kms-aead’s sqlx feature, so the application needs no kms-aead dependency line for it, see Stored values.

AAD

The default AAD of a value is its place in the application’s model, <kind>/<id>/<field>, such as user/42/email:

  • EntityKind, such as user;
  • EntityId, the row’s id, which binds the value to its row;
  • FieldName, such as email.

Each part is 1 to 255 bytes of UTF-8 without /, NUL or another ASCII control character. An id that holds / is encoded by the application first, with percent-encoding for example.

A FieldSpec names the kind and the field once, as a constant, and FieldSpec::aad(&id) builds the AAD of one row. from_static checks a kind or field name at compile time when it initialises a constant.

So a value decrypts only in its own row and field. A value copied into another row fails with KeyringError::KmsAead with code DECRYPT. And since the AAD names the logical place, not the physical one, a value moves between tables and data stores without being encrypted again.

An EntityId can be personal data, so no span, event or error of the crate carries it.

Deterministic fields have an AAD without the entity id, see Deterministic fields, and beacons a context without it, see Beacons.

Why the AAD is structured

kms-aead’s AeadCipher and KmsAeadEnvelope take the AAD as any impl AsRef<[u8]>: the application chooses the bytes and rebuilds them itself on every read. The keyring’s encrypt and decrypt take a FieldAad instead, which only a FieldSpec builds:

  • field binding: the default AAD names the kind and the field, so a value copied into another field of the same row fails to decrypt;
  • row binding: it names the entity id, so a value copied into another row fails to decrypt. The application’s own id, such as a user id, is the EntityId;
  • deterministic fields: a deterministic AAD must not hold the row id, or equal plaintexts in different rows give different values and equality lookups never match. DeterministicAad is a separate type, with no entity id and no constructor from arbitrary bytes, see Deterministic fields;
  • BigQuery: BigQuery decrypts in SQL, so the AAD has to be one SQL can rebuild from the row. <kind>/<id>/<field> is this crate’s convention, which CONCAT('user/', u.id, '/email') rebuilds; BigQuery itself prescribes no format;
  • Tink: Tink takes any AAD bytes. The requirements of a Tink field are on the algorithm and the KEK, not on the AAD;
  • the interop requirement: a FieldAad carries the Interop of its FieldSpec, so encrypting checks the field’s requirements whichever way the AAD was built. Free bytes would name no field and skip that check.
AADBuilt byField bindingRow bindingBigQuery reads itInterop checked
Free byteskms-aead’s AeadCipher, KmsAeadEnvelopeif the bytes name the fieldif the bytes name the rowif SQL rebuilds the bytesno
Defaultspec.aad(&id)yesyesyesyes
With a contextspec.aad(&id).with_context(bytes)yesyesyes, with the same bytes appended in SQLyes
Customspec.custom_aad(bytes)if the bytes name the fieldif the bytes name the rowno, refusedyes
Deterministicspec.deterministic_aad()yesno, so that equal values matchyesyes

The application’s own context

There are three ways to put the application’s own data, such as a user id or a tenant, into the AAD:

  • spec.aad(&id) with the application’s id as the EntityId, which follows the rules of AAD and is treated as personal data and never logged;
  • FieldAad::with_context(bytes) appends / and any bytes, such as a tenant or a schema version. A value encrypted with a context decrypts only with the same one. The context may itself hold /, so keep the contexts of one field apart yourself. A BigQuery reader appends the same bytes in SQL, CONCAT('user/', u.id, '/email/tenant-7');
  • FieldSpec::custom_aad(bytes) takes any bytes, with no structure, in place of the default AAD. It gives up field binding and row binding, unless the bytes name the field and the row themselves, and BigQuery readability: on a field declared with Interop::BigQuery it fails with KeyringError::CustomAadUnsupported, since SQL cannot rebuild such bytes. On a Tink field or a field without interop it keeps the field’s algorithm and KEK checks.
use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldAad, FieldName, FieldSpec, Interop, Keyring,
    KeyringAlgorithms, KeyringError, KeyringId, KeyringRegistry, KeyringRegistryOptions,
};

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
use kms_aead_keyring::KeyringAdmin;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(provider, KeyringId::from_static("tenant-42"), KeyringAlgorithms::new())
    .await?;
let keyring: &Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = admin.keyring();
let user_id: u64 = 4711;
let id: EntityId = EntityId::try_from(user_id.to_string())?;
let email: String = "alice@example.com".to_string();

// user/4711/email
let default_aad: FieldAad = EMAIL.aad(&id);
// user/4711/email/tenant-7
let with_context: FieldAad = EMAIL.aad(&id).with_context(b"tenant-7");
// signup/4711, bound to neither the field nor the kind
let custom: FieldAad = EMAIL.custom_aad(format!("signup/{user_id}").as_bytes())?;

for aad in [default_aad, with_context, custom] {
    let value: Encrypted<String, Randomized> = keyring.encryptor().await.encrypt(&aad, &email).await?;
    assert_eq!(keyring.decrypt(&aad, &value).await?, email);
}

let bigquery_email: FieldSpec = EMAIL.with_interop(Interop::BigQuery);
assert!(matches!(
    bigquery_email.custom_aad(b"signup/4711"),
    Err(KeyringError::CustomAadUnsupported(Interop::BigQuery))
));
registry.shutdown(None).await;
Ok(())
}

Deterministic fields

This page covers how a keyring encrypts, queries and rotates deterministic fields. Feature deterministic, to create deterministic key versions. The deterministic types exist in every build, so values pass through a process without the feature.

The generic Deterministic encryption page owns the AES-SIV primitive and what it leaks. Deterministic fields fit exact-match lookups where the leak of equality is acceptable; to choose between them and a beacon, read Find a user by an encrypted email.

What they leak

What a deterministic column and a leaked deterministic DEK allow is in What it leaks. The keyring adds one rule: the AAD of a deterministic field names its kind and field and no entity, see AAD, so a deterministic value also decrypts in any row of the same kind and field, and a deterministic field never decides identity or authorisation on its own.

Usage

A keyring with deterministic versions names their algorithm in its KeyringAlgorithms: AES-SIV, the one DeterministicAlgorithm has:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{DeterministicAlgorithm, KmsAeadResult};
use kms_aead_keyring::formats::Deterministic;
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    DeterministicAad, Encrypted, EntityKind, FieldName, FieldSpec, Keyring, KeyringAdmin,
    KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions, Plaintext,
};
use secret_vault_value::SecretValue;

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(
        provider,
        KeyringId::from_static("tenant-42"),
        KeyringAlgorithms::new().with_deterministic(DeterministicAlgorithm::Aes256Siv),
    )
    .await?;
let keyring: &Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = admin.keyring();

let aad: DeterministicAad = EMAIL.deterministic_aad();
let alice = Email("alice@example.com".to_string());
let first: Encrypted<Email, Deterministic> =
    keyring.encryptor().await.encrypt_deterministic(&aad, &alice).await?;
let second: Encrypted<Email, Deterministic> =
    keyring.encryptor().await.encrypt_deterministic(&aad, &alice).await?;

// Equal plaintexts give equal values under one version
assert_eq!(first, second);
assert_eq!(keyring.decrypt_deterministic(&aad, &first).await?, alice);
registry.shutdown(None).await;
Ok(())
}

A deterministic value is an Encrypted<T, Deterministic>, a type of its own, so it is never handed to decrypt by mistake. Unlike a randomised value it has == and Hash, which compare the bytes. AES-SIV runs on the RustCrypto aes-siv crate whatever the keyring’s AEAD backend.

decrypt_deterministic applies the compromised read policy, and decrypt_deterministic_with_trust reports the version’s trust, as their randomised counterparts do.

AAD

The AAD of a deterministic value is <kind>/<field>, such as user/email, built by FieldSpec::deterministic_aad(). It holds no entity id, otherwise equal plaintexts in different rows would give different values and an equality query would find nothing.

DeterministicAad::with_context(bytes) appends / and a context, such as a tenant id, to keep the values of two scopes apart. A context that differs per row defeats equality across rows, so it is a constant for the field. There is no constructor from arbitrary bytes: a deterministic value exists to be queried, and the query rebuilds its AAD.

Queries across rotations

A value encrypted under one deterministic version and the same plaintext under the next one differ. So an equality query matches against every version that still decrypts, with deterministic_probes:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{DeterministicAlgorithm, KmsAeadResult};
use kms_aead_keyring::formats::Deterministic;
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    DeterministicAad, Encrypted, EntityKind, FieldName, FieldSpec, KeyId, Keyring, KeyringAdmin,
    KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions, Plaintext, Purpose,
};
use secret_vault_value::SecretValue;
#[derive(Debug, Clone, PartialEq)]
struct Email(String);
impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> { self.0.to_plaintext() }
    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}
const EMAIL: FieldSpec = FieldSpec::new(EntityKind::from_static("user"), FieldName::from_static("email"));
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(
        provider,
        KeyringId::from_static("tenant-42"),
        KeyringAlgorithms::new().with_deterministic(DeterministicAlgorithm::Aes256Siv),
    )
    .await?;
let keyring: &Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = admin.keyring();
let aad: DeterministicAad = EMAIL.deterministic_aad();
let alice = Email("alice@example.com".to_string());
let before: Encrypted<Email, Deterministic> =
    keyring.encryptor().await.encrypt_deterministic(&aad, &alice).await?;

let staged: KeyId = admin.rotate(Purpose::Deterministic).await?;
admin.promote_now(staged).await?;

// One probe per version that still decrypts, newest first
let probes: Vec<Encrypted<Email, Deterministic>> = keyring.deterministic_probes(&aad, &alice).await?;
assert_eq!(probes.len(), 2);
assert!(probes.contains(&before));
registry.shutdown(None).await;
Ok(())
}

deterministic_probes returns one probe per pending, active or decrypt-only deterministic version, compromised ones included, so a query finds the rows encrypted under any of them, and a sweep the rows encrypted under a compromised one. A staged version is probed before its promotion, so a process that has not seen the promotion yet finds the values of the processes that have. Retired and destroyed versions give no probe. The probes go into the query:

StoreQuery
PostgreSQLWHERE email_det = ANY($1), with the probes bound as a BYTEA[]
Firestorean in filter on the field, which takes up to 30 values
BigQueryIN over one DETERMINISTIC_ENCRYPT per version, each with that version’s Single keyset, see Queries

After a promotion the list has two probes until a sweep re-encrypts every row and the old version is retired. That is why deterministic versions are rotated rarely, and every rotation is followed by a full sweep, see Rotation cadence.

Be aware a query with several probes puts the values of one plaintext under each version side by side, so a reader of the query log links a value’s history across a rotation.

A sweep re-encrypts a deterministic field with reencrypt_deterministic, as it re-encrypts a randomised one with reencrypt, see Re-encrypting a value.

BigQuery

BigQuery reads deterministic values with the keysets of export_bigquery_keyset, and a query encrypts its probes in SQL with a Single keyset per version, see Exporting a keyset to BigQuery.

Beacons

This page covers how a keyring computes, probes and rotates beacons. Beacons need no Cargo feature. The generic Beacons page owns the primitive, Beacon<T> and BeaconBits, what a beacon leaks, its bits and its normalisation; Formats has its bytes. To choose between a beacon and a deterministic field, read Find a user by an encrypted email.

A beacon, or blind index, finds rows by a field’s value without decrypting the column: a truncated HMAC-SHA256 of the value, stored beside the field’s randomised value, which a data store matches by equality. The keyring computes beacons under its beacon versions, of the purpose Purpose::Beacon, which rotate like any other.

What a beacon leaks

What a beacon leaks, and what a leaked beacon key allows, is in What a beacon leaks. The keyring computes a beacon in a field’s context, <kind>/<field> such as user/email, with no entity id: equal values in different rows give equal beacons, which is what a lookup matches. A beacon of one field never matches a beacon of another.

Usage

A keyring with beacon versions names their algorithm in its KeyringAlgorithms: HMAC-SHA256, the one BeaconAlgorithm has. An encryptor’s beacon computes the beacon of a value under the active beacon version, in the same write as the field’s value, and Keyring::beacon_probes the beacons of a value under every beacon version a lookup matches:

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Beacon, BeaconAlgorithm, BeaconBits, KmsAeadResult};
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldName, FieldSpec, Keyring, KeyringAdmin, KeyringAlgorithms,
    KeyringId, KeyringRegistry, KeyringRegistryOptions, Plaintext,
};
use secret_vault_value::SecretValue;

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

impl Email {
    // Beacons of one address match regardless of case
    fn new(email: &str) -> Self {
        Email(email.to_lowercase())
    }
}

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
)
.with_beacon_bits(BeaconBits::DEFAULT);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(
        provider,
        KeyringId::from_static("tenant-42"),
        KeyringAlgorithms::new().with_beacon(BeaconAlgorithm::HmacSha256),
    )
    .await?;
let keyring: &Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = admin.keyring();

// On every write: the field and its beacon, through one encryptor
let aad = EMAIL.aad(&EntityId::try_from("42")?);
let email = Email::new("Alice@Example.com");
let encryptor = keyring.encryptor().await;
let encrypted: Encrypted<Email, Randomized> = encryptor.encrypt(&aad, &email).await?;
let beacon: Beacon<Email> = encryptor.beacon(&EMAIL, &email).await?;

// A lookup: the probes of the value looked for, then a decryption of each matching row
let probes: Vec<Beacon<Email>> = keyring
    .beacon_probes(&EMAIL, &Email::new("alice@example.com"))
    .await?;
assert!(probes.contains(&beacon));
assert_eq!(keyring.decrypt(&aad, &encrypted).await?, email);
registry.shutdown(None).await;
Ok(())
}

The probes go into the query as the probes of a deterministic field do, see the table of queries, with the beacon column in place of the deterministic one. It has no BigQuery row: the keyring never exports beacon keys.

Beacon is stored as Encrypted is, see Stored values.

Bits

FieldSpec::with_beacon_bits sets how many bits of the HMAC the field’s beacons keep, BeaconBits::DEFAULT, 16, unless set; what the bits trade is in Bits. The bits enter the HMAC, so after a change of a field’s bits, its stored beacons match no probe until a re-index computes them again. A beacon is the HMAC of the bytes the Plaintext type encodes, so the field’s newtype normalises the value, as Email::new lowercases above, see Normalisation.

BigQuery

The keyring never exports beacon keys to BigQuery: export_bigquery_keyset of the beacon purpose fails with ExportAlgorithmUnsupported, see Exporting a keyset to BigQuery. A BigQuery query matches beacons the application computed, see BigQuery in kms-aead.

Rotating beacon versions

A beacon version rotates as the other purposes do, see Staged rotation, and a column holds beacons of several versions while it is re-indexed. What differs for beacons:

  • lookups use beacon_probes throughout: one probe per pending, active or decrypt-only beacon version, compromised ones included, newest first. A probe under a staged version is returned from the next refresh of each process, so lookups find the beacons computed under it before every process has seen the promotion;
  • a beacon cannot be re-encrypted, since it is a MAC of the plaintext. The promotion moves the keyring’s re-encryption epoch on, so every row written before it has an EncryptionMarker below the current one and a re-index sweep visits it, see Sweeps. It reads the value, computes the beacon again under the active version and writes the encryptor’s marker; a row without a beacon gets the marker alone;
  • once the sweep reports no failure and the version’s range query returns nothing, retire the old version, and its probe drops out of every lookup, see Retiring the old version.

beacon.key_id() reads the key id of a stored beacon, so that the sweep recomputes only the beacons under an older version. In the re-encryption of the sweep, see Running a sweep, reindex handles one row: a beacon under the active version keeps its bytes and only the value is re-encrypted; any other gives both again from the plaintext. The caller writes the returned row back, conditional on the row as it was read:

use kms_aead::backends::Ring;
use kms_aead::providers::LocalKmsProvider;
use kms_aead::{Beacon, BeaconBits};
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::sweep::{ReencryptOutcome, EncryptionMarker};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    Decrypted, Encrypted, EntityId, EntityKind, FieldName, FieldSpec, KeyTrust, Keyring,
    KeyringResult, Purpose,
};
use kms_aead::providers::LocalKekId;
use kms_aead::{BeaconAlgorithm, KmsAeadResult};
use kms_aead_keyring::{
    KeyId, KeyringAdmin, KeyringAlgorithms, KeyringId, KeyringRegistry, KeyringRegistryOptions,
    Plaintext,
};
use secret_vault_value::SecretValue;

type UsersKeyring = Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring>;

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
)
.with_beacon_bits(BeaconBits::DEFAULT);

#[derive(Debug, Clone, PartialEq)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

#[derive(Clone)]
struct UserRow {
    email: Encrypted<Email, Randomized>,
    email_beacon: Beacon<Email>,
    encryption_marker: EncryptionMarker,
}

/// Computes the beacon of the row of `user` again under the active beacon version, and re-encrypts
/// its value under the active randomised version, with the marker of the encryptor's record.
async fn reindex(
    keyring: &UsersKeyring,
    user: &str,
    row: UserRow,
) -> KeyringResult<(UserRow, ReencryptOutcome)> {
    let encryptor = keyring.encryptor().await;
    let aad = EMAIL.aad(&EntityId::try_from(user)?);
    let (email, email_beacon, outcome) = if encryptor.is_current(row.email_beacon.key_id()).await? {
        let reencrypted = encryptor.reencrypt(&aad, &row.email).await?;
        let outcome = ReencryptOutcome::from(&reencrypted);
        let email = reencrypted.map_or(row.email, |reencrypted| reencrypted.value);
        (email, row.email_beacon, outcome)
    } else {
        let decrypted: Decrypted<Email> = keyring.decrypt_with_trust(&aad, &row.email).await?;
        let from_compromised = decrypted.trust != KeyTrust::Trusted;
        let email = encryptor.encrypt(&aad, &decrypted.value).await?;
        let email_beacon = encryptor.beacon(&EMAIL, &decrypted.value).await?;
        (email, email_beacon, ReencryptOutcome::Reencrypted { from_compromised })
    };
    let encryption_marker: EncryptionMarker = encryptor.record().encryption_marker();
    Ok((UserRow { email, email_beacon, encryption_marker }, outcome))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(
        provider,
        KeyringId::from_static("tenant-42"),
        KeyringAlgorithms::new().with_beacon(BeaconAlgorithm::HmacSha256),
    )
    .await?;
let keyring: &UsersKeyring = admin.keyring();
let encryptor = keyring.encryptor().await;
let email = Email("alice@example.com".to_string());
let row = UserRow {
    email: encryptor.encrypt(&EMAIL.aad(&EntityId::try_from("42")?), &email).await?,
    email_beacon: encryptor.beacon(&EMAIL, &email).await?,
    encryption_marker: encryptor.record().encryption_marker(),
};
let staged: KeyId = admin.rotate(Purpose::Beacon).await?;
admin.promote_now(staged).await?;
let (reindexed, outcome) = reindex(keyring, "42", row).await?;
assert_eq!(outcome, ReencryptOutcome::Reencrypted { from_compromised: false });
assert_eq!(reindexed.email_beacon.key_id(), staged);
registry.shutdown(None).await;
Ok(())
}

Beacon versions are rotated by policy and on compromise only: each one adds a probe to every lookup until the re-index is done.

BigQuery and Tink interop

Keyring values are in Tink’s wire format, so Tink and BigQuery’s AEAD functions read the values the keyring writes, and the keyring reads theirs, given the same keys under the same key ids.

This page is the keyring reference for Interop::BigQuery, Interop::Tink and the keyset exports: the wire format, the interop checks and the contract of the export calls. For an end-to-end walkthrough with the queries and a Tink reader, read Decrypt columns in BigQuery SQL or with Tink.

Wire format

Every value starts with Tink’s 5-byte TINK prefix, a version byte 0x01 and the key id, followed by what the version’s algorithm writes, see Formats of Encrypted. These are the layouts of Tink’s AEAD and deterministic AEAD primitives, and of BigQuery’s AEAD.ENCRYPT and DETERMINISTIC_ENCRYPT. A randomised version with another algorithm, such as ChaCha20-Poly1305, writes the same prefix before its own body, which only kms-aead reads.

The prefix is not authenticated. A value relabelled with another key id selects another version, whose key the body does not decrypt under.

AAD in SQL

Both default AADs are UTF-8 text, so SQL rebuilds them from the row with no byte escaping:

-- Randomised: <kind>/<id>/<field>
AEAD.DECRYPT_STRING(keyset, u.email_enc, CONCAT('user/', u.id, '/email'))

-- Deterministic: <kind>/<field>
DETERMINISTIC_DECRYPT_STRING(keyset, u.email_det, 'user/email')

keyset is KEYS.KEYSET_CHAIN(@kms_key, @keyset) over an export of the keyring’s versions, see Exporting a keyset to BigQuery. SQL cannot rebuild an AAD of the application’s own bytes, so FieldSpec::custom_aad fails on a field declared with Interop::BigQuery, see Why the AAD is structured.

The plaintext encodings are the ones SQL reads: String and JsonEncoded<T> with AEAD.DECRYPT_STRING, the integers with a CAST of it, and Vec<u8> with AEAD.DECRYPT_BYTES. An application type reads as the type it encodes as, such as Email as a String.

Fields BigQuery reads

BigQuery decrypts through KEYS.KEYSET_CHAIN, which implements AES-256-GCM and AES-SIV only and decrypts with Cloud KMS only. A field BigQuery also decrypts is declared with FieldSpec::with_interop(Interop::BigQuery), and the keyring then refuses to encrypt it unless:

  • a randomised value is encrypted under an AES-256-GCM version, the default of a new keyring;
  • a deterministic value is encrypted under an AES-SIV version;
  • the KEK is in Google Cloud KMS.

The check runs on an encryptor’s encrypt and encrypt_deterministic, before encrypting, and fails with KeyringError::Interop naming the first requirement broken. Values already written always decrypt: only encrypting checks. So a change_algorithm away from AES-256-GCM, or a keyring on another KMS, fails the next write of the field instead of silently writing values BigQuery cannot read.

use kms_aead::backends::Ring;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::KmsAeadResult;
use kms_aead_keyring::errors::{InteropError, InteropRequirement};
use kms_aead_keyring::formats::Randomized;
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    Encrypted, EntityId, EntityKind, FieldName, FieldSpec, Interop, Keyring, KeyringAdmin,
    KeyringAlgorithms, KeyringError, KeyringId, KeyringRegistry, KeyringRegistryOptions,
    KeyringResult, Plaintext,
};
use secret_vault_value::SecretValue;

#[derive(Clone)]
struct Email(String);

impl Plaintext for Email {
    fn to_plaintext(&self) -> KmsAeadResult<SecretValue> {
        self.0.to_plaintext()
    }

    fn from_plaintext(plaintext: SecretValue) -> KmsAeadResult<Self> {
        String::from_plaintext(plaintext).map(Email)
    }
}

const EMAIL: FieldSpec = FieldSpec::new(
    EntityKind::from_static("user"),
    FieldName::from_static("email"),
)
.with_interop(Interop::BigQuery);

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// A local KEK, which BigQuery cannot decrypt with
let provider =
    LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("tenant-kek".to_string())?)?;
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = registry
    .create(provider, KeyringId::from_static("tenant-42"), KeyringAlgorithms::new())
    .await?;
let keyring: &Keyring<MemoryKeyringStore, LocalKmsProvider<Ring>, Ring> = admin.keyring();

let aad = EMAIL.aad(&EntityId::try_from("42")?);
let alice = Email("alice@example.com".to_string());
let refused: KeyringResult<Encrypted<Email, Randomized>> =
    keyring.encryptor().await.encrypt(&aad, &alice).await;
assert!(matches!(
    refused,
    Err(KeyringError::Interop(InteropError {
        requirement: InteropRequirement::Kek(_),
        ..
    }))
));
registry.shutdown(None).await;
Ok(())
}

Fields Tink reads

A field that Tink also decrypts, with the keyset of export_tink_keyset, is declared with FieldSpec::with_interop(Interop::Tink). The keyring then refuses to encrypt it unless:

  • a randomised value is encrypted under an AES-128-GCM, AES-256-GCM or AES-256-GCM-SIV version;
  • a deterministic value is encrypted under an AES-SIV version;
  • the KEK has a Tink key URI: a Cloud KMS key, an AWS KMS key named by its ARN, or a Vault Transit key.

ChaCha20-Poly1305 is left out, since Tink for Python and C++ do not read it in a keyset. The check and its errors are the ones of Interop::BigQuery, with Interop::Tink in the error.

Exporting a keyset to BigQuery

Feature bigquery-export. It builds on kms-aead’s GCP provider with no TLS root store, so the application also enables kms-aead’s gcp-kms-encryption, or another root store feature of kms-aead’s GCP provider.

BigQuery reads keyring values through KEYS.KEYSET_CHAIN, which takes a Tink keyset encrypted by a Cloud KMS key. KeyringAdmin::export_bigquery_keyset builds that keyset from the keyring’s versions, on a keyring whose provider is GcpKmsProvider, under the bigquery-export feature, which implies admin. The bytes it returns are the Cloud KMS ciphertext of Tink’s serialised Keyset message, encrypted with no associated data, without the EncryptedKeyset message Tink’s own keyset readers take, see Exporting a keyset to Tink:

use kms_aead::backends::Ring;
use kms_aead::providers::{GcpKmsKeyRef, GcpKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    encodings, EncryptedKeyset, KeyringAdmin, KeyringId, KeyringRegistry, KeyringRegistryOptions,
    KeysetSelection, Purpose,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let key_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, GcpKmsProvider, Ring> = registry
    .admin(GcpKmsProvider::new(&key_ref).await?, KeyringId::try_from("tenant-42".to_string())?)
    .await?;

let keyset: EncryptedKeyset<encodings::BigQuery> = admin
    .export_bigquery_keyset(KeysetSelection::Readable(Purpose::Randomized))
    .await?;
// The query parameters of `KEYS.KEYSET_CHAIN(@kms_key, @keyset)`: a `STRING` and a `BYTES`
let kms_key: &str = keyset.key_uri();
let keyset_bytes: &[u8] = keyset.value();
let _ = (kms_key, keyset_bytes);
registry.shutdown(None).await;
Ok(())
}

The selection:

  • KeysetSelection::Readable(purpose): every version of the purpose that decrypts and is not compromised, the pending one included, with the active version as the primary. BigQuery decrypts a value under the key its prefix names, so one keyset reads a column written across rotations. It fails with NoActiveVersion when the purpose has none;
  • KeysetSelection::Single(key_id): the one version as the primary, also when it is compromised. It is the keyset of DETERMINISTIC_ENCRYPT, which encrypts under the primary, for the probe of one version, and of a read through a compromised version. A retired, destroyed or unknown version fails as a read under it does, and a pending one with KeyVersionPending, since BigQuery would encrypt under it.

Beacon versions are never exported: a selection of the beacon purpose fails with ExportAlgorithmUnsupported. BigQuery’s SQL cannot compute a beacon either, see BigQuery in kms-aead.

The type parameter of an EncryptedKeyset is its encoding, from the encodings module, which names the reader of its bytes. The EncryptedKeyset<encodings::BigQuery> this export returns:

  • value() and into_value(): the encrypted keyset, as a BYTES column or query parameter holds it;
  • key_uri(): Tink’s key URI of the Cloud KMS key, gcp-kms://projects/…/cryptoKeys/…, the first argument of KEYS.KEYSET_CHAIN, as a STRING query parameter;
  • key_ids(): the key ids of the versions inside, in ascending order.

The export selects its versions from the record in the store, read at the time of the call, not from the record the process has cached. A version another process flagged compromised is therefore left out of a Readable keyset, even before this process’s cached record refreshes. The read is checked as a revalidation is: a stored record that moves a version backwards fails the export with RecordRegressed, and a missing one with RecordMissing.

A keyset is a copy of the record at the time of the export. A Readable keyset exported while a version is pending already holds it, so the order of a rotation is: rotate, export the Readable keysets again, wait, promote. Values encrypted under the new version then read in BigQuery from the first one. After mark_compromised, whose replacement is active at once, the replacement’s values do not read, and the compromised version stays in a keyset exported before it, until the keyset is exported again.

A KEK rotation changes no key inside a keyset and leaves the keyset under the KEK version that encrypted it at the export, so KEYS.KEYSET_CHAIN fails once that version is disabled. Export every keyset again after reencrypt_deks, once the new primary version has propagated, and replace the old bytes in every query and column that holds them before the old version is disabled, see Encrypted keysets.

Queries

Every value reaches a query as a parameter: @kms_key is the export’s key_uri() and each keyset parameter its value(). The queries are in Query keyring values in BigQuery.

The probes in BigQuery are those of the active and decrypt-only versions. A pending version has no Single keyset, and no value is encrypted under it before its promotion.

The requirements:

  • the keyring’s KEK is a Cloud KMS key, and the query runs in the KMS key’s location;
  • the exported versions are AES-256-GCM or AES-SIV. Any other algorithm fails with ExportAlgorithmUnsupported, before any KMS call;
  • the field is declared with Interop::BigQuery, so that the keyring never encrypts it under a version the keyset could not hold, see Fields BigQuery reads;
  • the principal that queries has decrypt on the KMS key, and the one that exports has encrypt and decrypt on it. The export is a KeyringAdmin call, see KMS rights.

Runtime behaviour and limits

  • a value whose key id is not in the keyset fails to decrypt, and reads as NULL under SAFE.AEAD.DECRYPT_STRING;
  • the keyset is encrypted with no associated data, since KEYS.KEYSET_CHAIN decrypts with none. What the KMS decrypts from it is a serialised Tink keyset, which is no serialised Tink key, so copied into a record as a version’s encrypted DEK it decrypts nothing and fails with INVALID_KEY_FORMAT;
  • the export decrypts each selected version through the provider and never through the DEK cache, so the keys stay in the process for the call only. Its span records dek_cache as bypassed.

Cloud KMS encrypts at most 64 KiB of plaintext, which a keyset reaches at several hundred versions.

Exporting a keyset to Tink

export_tink_keyset exports the same versions as Tink’s encrypted keyset, which Tink for Java, Go and Python decrypt with KeysetHandle.read and their own KMS client. It is a KeyringAdmin call, needs the admin feature only, and runs on a keyring with any provider whose KEK has a Tink key URI. The bytes are a google.crypto.tink.EncryptedKeyset around the KMS ciphertext of the serialised keyset, see Tink keysets and the TINK prefix.

key_uri() is the URI of Tink’s KMS client:

  • gcp-kms://projects/…/cryptoKeys/… for a Cloud KMS key;
  • aws-kms://arn:aws:kms:… for an AWS KMS key named by its ARN;
  • hcvault://<host>/…/keys/<name> for a Vault Transit key, which Tink for Go reads. Tink for Java and Python have no Vault Transit client.

An Azure Key Vault key, a local or an application’s own KEK, and an AWS key named without its ARN have no Tink client. The export fails on them with KeyringError::Interop, Interop::Tink and InteropRequirement::Kek, before any store or KMS call.

After a KEK rotation, a Tink keyset is exported again and replaces the old one wherever a Tink reader decrypts it, as a BigQuery keyset does, see Encrypted keysets.

use kms_aead::backends::Ring;
use kms_aead::providers::{GcpKmsKeyRef, GcpKmsProvider};
use kms_aead_keyring::testing::MemoryKeyringStore;
use kms_aead_keyring::{
    encodings, EncryptedKeyset, KeyringAdmin, KeyringId, KeyringRegistry, KeyringRegistryOptions,
    KeysetSelection, Purpose,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let key_ref = GcpKmsKeyRef::new(
    "my-project".to_string(),
    "europe-north1".to_string(),
    "my-key-ring".to_string(),
    "my-key".to_string(),
);
let registry = KeyringRegistry::<MemoryKeyringStore, Ring>::new(
    MemoryKeyringStore::new(),
    KeyringRegistryOptions::new(),
)?;
let admin: KeyringAdmin<MemoryKeyringStore, GcpKmsProvider, Ring> = registry
    .admin(GcpKmsProvider::new(&key_ref).await?, KeyringId::try_from("tenant-42".to_string())?)
    .await?;

let keyset: EncryptedKeyset<encodings::Tink> = admin
    .export_tink_keyset(KeysetSelection::Readable(Purpose::Randomized))
    .await?;
std::fs::write("tenant-42.keyset", keyset.value())?;
println!("{}", keyset.key_uri());
registry.shutdown(None).await;
Ok(())
}

A Tink reader decrypts a randomised value with the value’s default AAD as UTF-8, see Read a keyring export with Tink for Python.

The selection, the fresh read of the record and the rights are those of the BigQuery export. The algorithms are those of Fields Tink reads: a selected ChaCha20-Poly1305 or beacon version fails with ExportAlgorithmUnsupported, before any KMS call.

Full example available here: it exports a keyset for each Cloud KMS or AWS KMS key whose variables are set, and Tink for Python decrypts a value encrypted before the rotation with it, through tests/tink_interop.py read-keysets.

Cargo features

Both crates enable no default features. This page lists every feature of kms-aead and kms-aead-keyring. Pick one crypto backend, the KMS providers you use and, for kms-aead-keyring, your keyring store and optional modes; the choice of a provider and a backend is in Choose a provider and a backend.

kms-aead

The crate has no default features.

FeatureWhat it adds
gcp-kms-encryptionGoogle Cloud KMS, with the native TLS roots of the system, and the crc32c crate for the checksums of its requests, see the notes below
gcp-kms-encryption-webpkiGoogle Cloud KMS with the bundled WebPKI roots, and the crc32c crate
gcp-kms-encryption-baseGoogle Cloud KMS without a TLS root store or crypto provider, and the crc32c crate, see the notes below
aws-kms-encryptionAWS KMS, with the credentials of an aws login session among others, see AWS KMS
azure-kms-encryptionAzure Key Vault and Managed HSM, with rustls and the aws-lc-rs crypto provider
azure-kms-encryption-tls-aws-lc-rsthe same as azure-kms-encryption
azure-kms-encryption-tls-no-providerAzure with rustls and the crypto provider the application installs, see the notes below
azure-kms-encryption-native-tlsAzure with the platform TLS library
hashicorp-vault-transit-kms-encryptionHashiCorp Vault Transit, with the system root certificates and the aws-lc-rs crypto provider
hashicorp-vault-transit-kms-encryption-baseVault Transit without a root store or crypto provider, to combine with one of each below
hashicorp-vault-transit-kms-encryption-tls-rootsVault Transit with the system root certificates
hashicorp-vault-transit-kms-encryption-tls-webpkiVault Transit with the bundled WebPKI roots
hashicorp-vault-transit-kms-encryption-tls-aws-lc-rsVault Transit with the aws-lc-rs crypto provider
hashicorp-vault-transit-kms-encryption-tls-ringVault Transit with the ring crypto provider
ringthe ring backend, see Crypto backends
aws-lcthe aws-lc-rs backend
aws-lc-fipsthe aws-lc-rs backend on the AWS-LC FIPS module. Needs CMake and Go to build
rustcryptothe backend on the pure Rust RustCrypto crates, no C compiler needed. Adds p256 and ed25519-dalek for signatures, and rsa for RSA-OAEP, see Asymmetric KEKs
deterministicdeterministic encryption with AES-SIV, see Deterministic encryption
streamstreaming encryption of values of any length, see the notes below. Turns on tokio’s io-util and brings in bytes and futures-core
postgresToSql and FromSql of postgres-types for Encrypted, as BYTEA, for tokio-postgres
sqlxsqlx’s PostgreSQL traits for Encrypted, as BYTEA, without a sqlx runtime or TLS stack
opentelemetryOpenTelemetry metrics on the API crate only (no SDK), see the notes below and Metrics

Notes on the rows:

  • gcp-kms-encryption also turns on native-tls in reqwest, so in the same build the Azure provider uses native-tls whatever its TLS feature;
  • gcp-kms-encryption-base: the application enables a root store and a crypto provider with its own gcloud-sdk features, such as tls-roots or tls-webpki-roots, and the crate does not build without one;
  • azure-kms-encryption-tls-no-provider: the application must install a process-default rustls CryptoProvider before creating the provider, otherwise rustls panics;
  • stream adds StreamEncryptor and StreamDecryptor, the tokio adapters EncryptingWriter and DecryptingReader, the Stream adapters EncryptingStream and DecryptingStream, the stream_encryptor and stream_decryptor calls of AeadCipher and KmsAeadEnvelope, with their bare forms, and KmsAeadEnvelope::decrypting_stream and decrypting_reader, which read the header from the whole stored value;
  • opentelemetry records the plaintext size of each value encrypted and decrypted, and the time each call, KMS request and keyring store read takes.

The local KMS provider, LocalKmsProvider, is in every build and needs no feature.

Every build adds serde, serde_bytes, serde_json, secret-vault-value’s serde feature, sha2, base64ct and the RustCrypto crates der, spki, pkcs8, sec1 and pem-rfc7468:

  • sha2 computes the thumbprint of a public key and, in kms-aead-keyring, the canonical digest of a record, where no backend is named;
  • the RustCrypto crates parse and write the framing of keys and signatures: PEM, the text armour around base64 bytes; SubjectPublicKeyInfo, the DER structure of a public key, DER being a binary encoding; PKCS#8, the DER structure of a private key; and the DER encoding of an ECDSA signature;
  • serde_json reads and writes JSON Web Keys (JWK), the JSON form of a key, so PublicKeyFormat::Jwk, encode(Jwk) and the JWK Set functions of VerifyingKeySet are in every build, as are JsonEncoded<T> and the serde implementations of the library’s types.

Feature rules

The crate refuses some feature combinations at compile time with compile_error!:

  • a provider feature without a backend feature fails: enable ring, aws-lc, aws-lc-fips or rustcrypto beside it;
  • HashiCorp Vault Transit needs exactly one of -tls-roots and -tls-webpki, and exactly one of -tls-aws-lc-rs and -tls-ring. hashicorp-vault-transit-kms-encryption already enables -tls-roots and -tls-aws-lc-rs, so combine the other variants with hashicorp-vault-transit-kms-encryption-base instead;
  • Azure needs exactly one of azure-kms-encryption-tls-aws-lc-rs (or azure-kms-encryption), azure-kms-encryption-tls-no-provider and azure-kms-encryption-native-tls.

The aws-lc-rs feature that aws-lc and aws-lc-fips enable is not a backend choice: enabled alone, the aws-lc-rs build fails. Use aws-lc or aws-lc-fips.

A build without any backend feature compiles, and LocalKmsProvider is in it, but nothing that encrypts can be constructed, since no type implements AeadBackend.

kms-aead-keyring

The crate has no default features.

FeatureWhat it adds
ring, aws-lc, aws-lc-fips, rustcryptothe crypto backends of kms-aead, see Crypto backends. A keyring names its backend as a type parameter, such as kms_aead::backends::Ring
adminKeyringAdmin, the registry’s create, open_or_create and admin, and the types of the administrative calls, see Permissions: applications and administration
deterministicdeterministic key versions and every call on them, see the notes below and Deterministic fields
firestorethe Firestore keyring store, on firestore-rs without its default features: no TLS root store and no crypto provider. Enable one of the two below, or a root store feature of firestore-rs or gcloud-sdk, see Keyring stores
firestore-tls-rootsfirestore with the system’s native roots, firestore-rs’s tls-roots, which brings native-tls and so OpenSSL on Linux, and firestore-rs’s auth-default-crypto
firestore-tls-webpkifirestore on rustls, with the bundled WebPKI roots for the gRPC connection to Firestore and no native TLS, and firestore-rs’s auth-default-crypto
postgresthe PostgreSQL keyring store, and Encrypted and EncryptionMarker in tokio-postgres, as BYTEA
gcsthe Cloud Storage keyring store, on gcloud-sdk without a TLS root store or crypto provider. Enable one of the two below, or a root store feature of gcloud-sdk, see Keyring stores
gcs-tls-rootsgcs with the system’s native roots, gcloud-sdk’s tls-roots, which brings native-tls and so OpenSSL on Linux, and gcloud-sdk’s auth-default-crypto
gcs-tls-webpkigcs on rustls, with the bundled WebPKI roots for the gRPC connection to Cloud Storage and no native TLS, and gcloud-sdk’s auth-default-crypto
s3the S3 keyring store
sqlxEncrypted and EncryptionMarker in sqlx on PostgreSQL, as BYTEA
streamkms-aead’s stream, Encryptor::stream_encryptor, Keyring::stream_decryptor, decrypting_stream and decrypting_reader, and the stream module re-exported. Needs a backend feature, see Streaming encryption
bigquery-exportadmin, and export_bigquery_keyset, see Exporting a keyset to BigQuery
opentelemetrykms-aead’s opentelemetry, with the keyring’s calls recorded per keyring and key version, see Metrics

Notes on the rows:

  • admin also adds the types Rotation, EncryptedKeyset, KeysetSelection and the encodings module;
  • deterministic adds encrypt_deterministic and reencrypt_deterministic on an Encryptor, and decrypt_deterministic, decrypt_deterministic_with_trust and deterministic_probes on a Keyring. The deterministic types exist in every build, so a process without the feature keeps a record’s deterministic versions intact.

Beacons need no feature, and export_tink_keyset needs admin only. The KMS providers come from kms-aead and its provider features, and secret-vault-value’s SecretValue is what an application type’s Plaintext encodes to.

Formats

Every byte layout the library reads or writes is listed on this page and described on the pages below it. Read it to find the layout of a stored value, to tell two layouts apart, or to decide which pages to read to parse a value outside the library:

  • Values and DEKs: Encrypted<T, F> and its formats, Tink’s KMS envelope, encrypted DEKs and the serialised DEKs inside them, DEKs encrypted with a public key, and beacons;
  • Streamed values: the header and chunks of streamed values, in the prefixed, bare and envelope forms, and how a range read maps to chunks;
  • Signature and MAC formats: detached and attached signatures and MACs, what they are computed over, the key ids of signing keys and the test vectors;
  • Keyring records and keysets: the key ids of a keyring, the JSON record every store keeps, encryption markers, and Tink keysets.

The library writes one envelope format for every provider, Tink’s KMS envelope. A value encrypted by KmsAeadEnvelope::encrypt decrypts with Tink’s KmsEnvelopeAead on the same KMS key and algorithm, and a value Tink encrypts decrypts with KmsAeadEnvelope::decrypt.

LayoutTypeBytesRead byStatus
Tink KMS envelopeEncrypted<T, Envelope>[w: u32 BE][encrypted DEK: w][nonce: 12][ciphertext][tag: 16]kms-aead, Tinkcurrent
Bare valueEncrypted<T, Bare>[nonce: 12][ciphertext][tag: 16]kms-aead, Tinkcurrent
Encrypted DEKEncryptedDataEncryptionKeythe provider’s byteskms-aead, Tink for GCP and AWS keyscurrent
Serialised DEKthe plaintext of an encrypted DEK, but Azure’sTink’s key messagekms-aead, Tinkcurrent
TINK-prefixed valueEncrypted<T, Randomized>, Encrypted<T, Deterministic>, named by a KeyId[0x01][key id: u32 BE][value]kms-aead, Tink, BigQuery; kms-aead-keyring writes it toocurrent
Streamed valueStreamEncryptor and StreamDecryptor of AeadCipher::stream_encryptor and stream_decryptor, and of the keyring’s Encryptor::stream_encryptor and Keyring::stream_decryptorsee its pagekms-aead with stream; a C2SP chunked-encryption reader from byte 5; kms-aead-keyring writes it toocurrent
Envelope streamed valueStreamEncryptor and StreamDecryptor of KmsAeadEnvelope::stream_encryptor and stream_decryptorsee its pagekms-aead with stream; a C2SP chunked-encryption reader from byte 4 + wcurrent
Bare streamed valueStreamEncryptor and StreamDecryptor of the stream_encryptor_bare and stream_decryptor_bare calls of AeadCipher and KmsAeadEnvelopesee its pagekms-aead with stream, any C2SP chunked-encryption readercurrent
Detached signatureSignature<T>[0x01][key id: u32 BE][signature]kms-aeadcurrent
Attached signatureSigned<T>[0x01][key id: u32 BE][w: u16 BE][signature: w][payload]kms-aeadcurrent
Detached MACMac<T>[0x01][key id: u32 BE][tag]kms-aead, and kms-aead-keyring for its MAC versionscurrent
Attached MACWithMac<T>[0x01][key id: u32 BE][w: u16 BE][tag: w][payload]kms-aead, and kms-aead-keyring for its MAC versionscurrent
Tink keysetTinkKeysetgoogle.crypto.tink.KeysetTink, BigQuery; kms-aead-keyring writes it toocurrent
Tink encrypted keysetTinkKeyset::into_encrypted_bytesgoogle.crypto.tink.EncryptedKeyset, [0x12][w: varint][encrypted keyset: w]Tink with a GCP, AWS or Vault Transit key; kms-aead-keyring writes it toocurrent
Envelope layout v1none[0x01][k: u8][key version: k][w: u16 BE][encrypted DEK: w][cipher text]kms-aead 0.33 and earlierlegacy
Encrypted DEK layout v1none[0xFF][0x01][k: u8][key version: k][encrypted DEK]kms-aead 0.33 and earlierlegacy
Length-prefixed envelopenone[w: u64 BE][encrypted DEK: w][cipher text], and [w: u32 BE] from 32-bit targets in early releaseskms-aead 0.33 and earlierlegacy
Raw encrypted DEKEncryptedDataEncryptionKeythe KMS ciphertext of the DEK’s 16 or 32 raw byteskms-aead 0.33 and earlier, and kms-aead under Azurelegacy, except under Azure, which still writes it

k = 0 records no key version. A key version is 1 to 255 ASCII alphanumeric characters. The Azure provider encrypts the raw DEK, see Encrypted DEKs.

The library refuses the legacy layouts with LEGACY_FORMAT. How kms-aead 0.33 rewrites stored values in them is in Migrating from 0.29.

Telling layouts apart

The first bytes of a stored value:

First bytesLayout
00 00 00 00the legacy length-prefixed envelope
00, then a length of 1 to 4,096Tink’s KMS envelope, an envelope streamed value, or the 4-byte length prefix of the legacy envelope on 32-bit targets
01the legacy envelope layout v1, or a TINK-prefixed value
02a DEK encrypted with the public half of an asymmetric KEK
FF 01the legacy encrypted DEK layout v1

Only the decrypted DEK tells a Tink envelope from the legacy 32-bit layout: a raw key of 16 or 32 bytes against a serialised Tink key, whose lengths differ. An encrypted DEK of AWS, Azure or the local KMS also starts with 0x01, and Tink’s LEGACY and CRUNCHY output prefixes with 0x00.

A column that holds two layouts:

  • Tink envelopes and TINK-prefixed values: the first byte, 0x00 or 0x01;
  • Tink envelopes and legacy envelopes of layout v1: the first byte, 0x00 or 0x01;
  • Tink envelopes and legacy length-prefixed envelopes: the first four bytes;
  • legacy envelopes of layout v1 and TINK-prefixed values: no byte tells them apart, so the layout is recorded outside the value, such as in another column;
  • bare values and any other layout: a bare value has no framing, and its random nonce can start with any byte, so a column of bare values holds no other layout;
  • streamed values and bare streamed values: no byte tells them apart, since a bare one starts with its random salt, so the call names the form, as decrypt_bare does for a bare value, see Streamed values;
  • envelope streamed values and Tink envelopes: both start with [w][encrypted DEK], so the layout is recorded outside the value, as for bare values;
  • legacy encrypted DEKs of layout v1 and current ones: 0xFF 0x01 starts no encrypted DEK of a built-in provider, so the library tells them apart for those and refuses the legacy ones before the KMS call. It never inspects the bytes of an application’s own provider.

Values and DEKs

This page has the bytes of the values an application stores and of the DEKs that go with them: read it to parse, store or interoperate with an Encrypted value, an encrypted DEK or a beacon. The layouts of every kind of value are listed on Formats.

Formats of Encrypted

Every value the library encrypts is an Encrypted<T, F>: the bytes of one layout, named by its format F from kms_aead::formats. Encrypted::try_from and Encrypted::try_from_hex_string check stored bytes against it:

FormatLayoutShortest valuekey_id()Written by
EnvelopeTink’s KMS envelopean encrypted DEK of 1 to 4,096 bytes, then 28 bytesnoneKmsAeadEnvelope::encrypt, Encrypted::join
Bare[nonce: 12][ciphertext][tag: 16]28 bytesnoneAeadCipher::encrypt_bare, KmsAeadEnvelope::encrypt_with_dek and encrypt_with_encrypted_dek, Encrypted::separate
Randomized[0x01][key id: u32 BE][nonce: 12][ciphertext][tag: 16]33 bytesKeyIdAeadCipher::encrypt, and kms-aead-keyring through it
Deterministic[0x01][key id: u32 BE][synthetic IV: 16][ciphertext]21 bytesKeyIdDeterministicCipher::encrypt, and kms-aead-keyring through it

A Bare value is Tink’s AEAD output under a key with the output prefix RAW, and the part of every Envelope value after the encrypted DEK. It names no key: the application keeps track of the key that decrypts it.

The check reads the framing only, and whether the bytes are authentic is known when they are decrypted. Encrypted::try_from refuses the legacy envelope layout v1 and the legacy length-prefixed envelope with LEGACY_FORMAT. A legacy layout that early releases wrote on 32-bit targets has Tink’s framing, so it reads as an Envelope value, and KmsAeadEnvelope::decrypt refuses it with LEGACY_FORMAT once its DEK decrypts to a raw key, see Migrating from 0.29.

The plaintext inside is the encoding of the value’s Plaintext type: UTF-8 for String, the bytes themselves for Vec<u8> and SecretValue, decimal ASCII for the integers, and compact JSON for JsonEncoded<T>. See Stored values.

Tink’s KMS envelope

KmsAeadEnvelope::encrypt writes Tink’s KMS envelope, and Encrypted::join writes it from a bare value and an encrypted DEK. separate reads it back:

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, KmsAeadEnvelope};
use secret_vault_value::SecretValue;

#[tokio::main(flavor = "current_thread")]
async fn main() -> kms_aead::KmsAeadResult<()> {
let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;
let encrypted: Encrypted<SecretValue, Envelope> =
    envelope.encrypt(b"aad", &SecretValue::from("secret")).await?;

let (bare, encrypted_dek) = encrypted.separate()?;
let joined = Encrypted::<SecretValue, Envelope>::join(&bare, &encrypted_dek)?;
assert_eq!(joined.value(), encrypted.value());
Ok(())
}
  • w is 1 to 4,096 bytes, the limit of every Tink implementation, on write and on read;
  • the encrypted DEK is the provider’s EncryptedDataEncryptionKey, the KMS ciphertext of the serialised DEK, or of the raw DEK for Azure;
  • the AAD goes to the DEK’s AEAD only. The KMS encryption of the DEK has no AAD, as in Tink, so Tink’s AWS client sends no encryption context and its GCP client no additional authenticated data;
  • the rest is a Bare value.

The envelope records neither the algorithm nor the KEK version, so the writer and the reader, kms-aead or Tink, are configured with the same algorithm. Tink calls it the DEK template:

AlgorithmTink key typeTink for Java and GoTink for C++ and Python
ChaCha20-Poly1305ChaCha20Poly1305Keyreads and writesno
AES-128-GCM, AES-256-GCMAesGcmKeyreads and writesreads and writes
AES-256-GCM-SIVAesGcmSivKeyreads and writesreads and writes

AES-256-GCM is the default of KmsAeadEnvelope::new, so every Tink implementation reads the values of an envelope that names no algorithm. Legacy values default to ChaCha20-Poly1305, see Migrating from 0.29.

Tink for Python reads a kms-aead value with the key URI of the provider’s key:

from tink import aead
from tink.integration import gcpkms

aead.register()
key_uri = 'gcp-kms://projects/p/locations/l/keyRings/r/cryptoKeys/k'
remote = gcpkms.GcpKmsClient(key_uri).get_aead(key_uri)
envelope = aead.KmsEnvelopeAead(aead.aead_key_templates.AES256_GCM, remote)
plain_text = envelope.decrypt(value, aad)

tests/tink_interop.py and examples/tink_interop.rs run the Python read against a Cloud KMS key and an AWS KMS key, for AES-128-GCM, AES-256-GCM and AES-256-GCM-SIV.

Encrypted DEKs

EncryptedDataEncryptionKey is the bytes the provider returned from an encryption, which are also the bytes to store and the bytes it decrypts. Each provider’s bytes name the KEK version that encrypted the DEK where the KMS needs one to decrypt:

ProviderBytesKey version
GCPthe Cloud KMS ciphertext, starting with 0x0ainside the ciphertext
AWSthe AWS KMS ciphertext blob, starting with 0x01not exposed
Azure[0x01][k: u8][key version: k][Key Vault encrypted DEK]in the layout
Vault Transitthe Transit ciphertext, vault:vN:…the N
local[0x01][i: u8][KEK id: i][KEK version: u32 BE][nonce: 12][encrypted DEK][tag: 16]in the layout
any, encrypted with a public key[0x02][a: u8][i: u8][KEK id: i][k: u8][KEK version: k][RSA block], see DEKs encrypted with a public keyin the layout
an application’s ownwhatever it returns

The Azure layout is the library’s own: Key Vault decrypts only with the key version that encrypted, and no Tink client exists for Azure. For the same reason, the Key Vault encrypted DEK is the KMS ciphertext of the raw DEK of 16, 32 or 64 bytes, as the legacy layouts have it, not of the serialised DEK: AES key wrap, A128KW to A256KW, takes only multiples of 8 bytes, which no serialised DEK is. The local KMS encrypts the DEK with AES-256-GCM under the KEK version, with its header up to the version as the AAD, so neither the id nor the version can be changed without the decryption failing.

The 0x02 layout is the same for every KMS: a producer holding the public half of an RSA key encrypts the DEK in its own process, and the provider of the KMS that holds the private half decrypts it. The providers read it beside their own bytes, and a release that predates asymmetric KEKs cannot read it, see DEKs encrypted with a public key, Asymmetric KEKs and Readers before producers.

Store value() or to_hex_string(), and read them back with EncryptedDataEncryptionKey::from or try_from_hex_string. Neither holds the KEK version of kek_version(), see Storing encrypted DEKs.

Serialised DEKs

The plaintext a provider encrypts is the DEK serialised as Tink serialises a key, the message of its Tink key type with version 0, which protobuf leaves out. The Azure provider encrypts the raw DEK instead, see Encrypted DEKs.

The messages are protobuf. A field starts with a tag byte, the field number shifted left by three bits and the wire type 2 of a length-delimited field, so 0x12 is field 2, 0x1a is field 3, and the length of the bytes follows:

AlgorithmMessageBytes
ChaCha20-Poly1305ChaCha20Poly1305Key[0x12][0x20][key: 32]
AES-128-GCMAesGcmKey[0x1a][0x10][key: 16]
AES-256-GCMAesGcmKey[0x1a][0x20][key: 32]
AES-256-GCM-SIVAesGcmSivKey[0x1a][0x20][key: 32]
AES-256-SIV, deterministicAesSivKey[0x12][0x40][key: 64]
HMAC-SHA256, MAC keyHmacKey[0x1a][0x20][key: 32]
HMAC-SHA512, MAC keyHmacKey[0x1a][0x40][key: 64]

A beacon key of HMAC-SHA256 is serialised as [0x1a][0x20][key: 32], its 32 bytes in key_value, field 3 (tag 0x1a), as in Tink’s HmacPrfKey without its parameters: the bytes of a 32-byte AesGcmKey. It is encrypted as a DEK is, raw under an Azure key. A MAC key of a keyring is serialised the same way, in field 3 and never in field 2 (tag 0x12), since [0x12][0x40][key: 64] is byte for byte an AES-SIV key, see MACs in a keyring.

KmsAeadEnvelope::generate_encrypted_dek, generate_encrypted_deterministic_dek and the generate_encrypted_dek of both ciphers and of BeaconMac encrypt their keys the same way. The message does not name its type, and AES-256-GCM and AES-256-GCM-SIV keys are written alike, so the algorithm of the reader decides how the key is used, as in Tink.

A decrypted DEK that is no serialised Tink key, or under an Azure key no raw DEK, fails with INVALID_KEY_FORMAT. An encrypted Tink keyset decrypts under the same KEK too, and this is what keeps it out of the DEK cache.

DEKs encrypted with a public key

An encrypted DEK that a public key encrypted has one layout for every KMS:

[0x02][a: u8][i: u8][KEK id: i bytes][k: u8][KEK version: k ASCII alphanumerics][RSA block]
  • 0x02 marks the layout. No other encrypted DEK of a built-in provider starts with it, see Telling layouts apart;
  • a is the algorithm: 0x01 for RSA-OAEP with SHA-256 as the OAEP hash and the MGF1 hash, and an empty label. A later algorithm is another value;
  • i and the KEK id are the local KEK’s LocalKekId. i is 0 for a cloud KEK;
  • k and the KEK version are the version the public key carried, as the reader names it to its KMS: 1 to 255 ASCII alphanumerics. k is 0 under AWS KMS, which has no versions, and the version is the decimal LocalKekVersion under the local KMS;
  • the RSA block is as long as the modulus: 256, 384 or 512 bytes for a key of 2048, 3072 or 4096 bits. The encrypted DEK is the header and the block, 260 bytes under AWS KMS with a 2048-bit key.

The block is the OAEP encryption of the DEK in the form its KEK’s provider encrypts it: the serialised DEK, or the raw DEK under Key Vault. The seed of OAEP is random, so two encryptions of one DEK differ.

A reader checks the header against its own shape before any KMS call, and refuses the encrypted DEK with ASYMMETRIC_ENCRYPTED_DEK_FORMAT otherwise: a known algorithm byte; a header within the bytes; i of 0 for a cloud KEK; k of 0 under AWS KMS and 1 or more elsewhere; a block of 256, 384 or 512 bytes. Nothing in the header is authenticated: a changed version or KEK id names a key that fails to decrypt the block, and no change decrypts a value.

How each KMS decrypts the block:

KMSRequest
Google Cloud KMSAsymmetricDecrypt on <key>/cryptoKeyVersions/<version>, ciphertext the block
AWS KMSDecrypt with KeyId the key, EncryptionAlgorithm RSAES_OAEP_SHA_256 and CiphertextBlob the block
Azure Key VaultunwrapKey on the key and the version with alg RSA-OAEP-256
Vault Transitdecrypt on the key with ciphertext vault:v<version>: and the standard base64 of the block, padding_scheme oaep and hash_algorithm sha2-256
Local KMSRSA-OAEP decryption with the version’s private key

None of the four KMS decryptions takes a label or an AAD. What binds a value to its place is its own AAD.

Beacons

A Beacon<T> is a prefix and a truncated HMAC-SHA256:

[0x01][key id: u32 BE][HMAC-SHA256: the first ceil(bits / 8) bytes]
  • 0x01 is the version of the beacon layout. A later layout takes another first byte, so that beacons of both layouts can share a column during a re-index;
  • the key id names the beacon key that calculated the beacon;
  • the HMAC keeps its first bits bits, and the unused low bits of the last byte are zero. A beacon is 6 to 37 bytes.

The HMAC covers the bits, the context and the plaintext, as the Plaintext type encodes it:

HMAC-SHA256(key, [bits: u16 BE][context length: u32 BE][context][plaintext])

so that beacons of two fields, or of two bit counts, never match. Beacon::try_from checks the prefix and that 1 to 32 bytes of HMAC follow, and fails with INVALID_BEACON_FORMAT otherwise.

Streamed values

This page has the layouts written by the stream encryptors of kms-aead and kms-aead-keyring, and the arithmetic of a range read. Read it to parse a streamed value without the library, or to fetch a byte range of one from a store. The layouts of every kind of value are listed on Formats.

A streamed value is a header and chunks. Every length is in bytes and integers are big-endian. The prefixed form, the one of AeadCipher::stream_encryptor and of the keyring:

offset          len     field
     0            1     0x01, Tink's output prefix of type TINK
     1            4     key id, u32: the keyring version that encrypted the value, or the caller's KeyId
     5           24     salt, random per value
    29           32     key commitment
    61       16,400     chunk 0: 16,384 bytes of ciphertext and a 16-byte tag
    61 + k × 16,400     chunk k

The bare form is a Cobblestone-256 message, the chunked AES-256-GCM format with a key commitment that C2SP chunked encryption specifies, with the caller’s AAD as its context and the DEK as its input key:

offset          len     field
     0           24     salt
    24           32     key commitment
    56       16,400     chunk 0
    56 + k × 16,400     chunk k

The envelope form, the one KmsAeadEnvelope::stream_encryptor writes, puts the encrypted DEK in front of the bare form, as Tink’s KMS envelope puts it in front of a bare value:

offset          len     field
     0            4     w, u32: the length of the encrypted DEK, 1 to 4,096
     4            w     encrypted DEK, the provider's EncryptedDataEncryptionKey
 4 + w           24     salt
28 + w           32     key commitment
60 + w       16,400     chunk 0
60 + w + k × 16,400     chunk k
  • the header H is 61 bytes in the prefixed form, 56 in the bare form and 60 + w in the envelope form. From the Cobblestone header on, the forms are the same;
  • every chunk but the last is 16,400 bytes as stored. The last chunk is 16 to 16,399 bytes, the tag and 0 to 16,383 bytes of ciphertext, so a plaintext of a multiple of 16,384 bytes ends with a tag alone. An empty plaintext is the header and one tag, 77 bytes prefixed, 72 bare and 76 + w in the envelope form. There is one chunking for each length;
  • only the first byte of a prefixed header is checked when it is read. The key id is not authenticated: it names the key that decrypts the value;
  • a reader of the envelope form reads w from the first 4 bytes, refuses a w outside 1 to 4,096 before it fetches or allocates anything, then reads the 60 + w bytes of the header. The encrypted DEK is not authenticated either: another value’s encrypted DEK decrypts to another DEK, which fails the key commitment;
  • no byte tells the bare form from the others, since a bare value starts with its random salt. The call names the form.

The keys come from the DEK K of 32 bytes, the salt and the AAD A:

HKDF-Expand is the key derivation step of HKDF that turns a pseudorandom key (PRK) into output keys, and the DEK is the PRK here:

key || base nonce || commitment = HKDF-Expand(SHA-512, PRK = K,
    info = "c2sp.org/chunked-encryption@v1+" || "AEAD_AES_256_GCM" || 0x00 || salt || A,
    length = 32 + 12 + 32)

With a 32-byte PRK, HKDF-Expand is two HMAC-SHA-512 calls: T1 = HMAC(K, info || 0x01) gives the key (T1[0..32]), the base nonce (T1[32..44]) and commitment[0..20] (T1[44..64]), and T2 = HMAC(K, T1 || info || 0x02) gives commitment[20..32] (T2[0..12]). A reader derives all three and compares the commitment in constant time before it decrypts a chunk. The AAD is bound here and nowhere else: each chunk’s GCM associated data is empty.

Chunk k holds plaintext bytes [k × 16,384, (k + 1) × 16,384) and is AES-256-GCM(key, N_k, aad = "", M_k), with the nonce N_k = base nonce XOR k, k as a 96-bit big-endian integer. There is no final flag: the final chunk is the one that is shorter than a full one.

For a plaintext of L bytes the stored length is Z = H + L + 16 × n with n = L div 16,384 + 1 chunks. From a stored length Z, with body = Z - H:

Z < H + 16          refused: shorter than the header and one tag
n = body div 16,400 + 1
r = body - (n - 1) × 16,400     the final chunk as stored
r < 16              refused: r = 0 is a value cut at a chunk boundary, 1 to 15 no encryptor writes
n > 2^38            refused
L = body - 16 × n

A value holds at most 2^38 chunks, 4 PiB less one byte of plaintext. The refusals are STREAM_LENGTH. Z is what the store reports: until the final chunk has been decrypted, L is the store’s word. A reader that reads the value to its end needs no Z: the bytes after the last full chunk are the final chunk, and the rules above hold for the length it read.

For a plaintext range [a, b) with a <= b <= L, the chunks to decrypt and the bytes to fetch are below. A range open at the start has a = 0 and one open at the end has b = L, so .. is [0, L):

first = a div 16,384
end   = n                      if b == L: the final chunk, even when it holds no plaintext
        first                  if a == b < L
        (b - 1) div 16,384 + 1 otherwise
ciphertext = [H + first × 16,400, min(Z, H + end × 16,400))

The reader cuts the decrypted plaintext to [a - first × 16,384, b - first × 16,384). For a = 1,000,000 and b = 1,064,512 the chunks are 61..65 and the bytes [1,000,461, 1,066,061) prefixed or [1,000,456, 1,066,056) bare, and 4 + w bytes further in the envelope form.

The two shortest vectors of the C2SP test file as prefixed values under key id 7, with the key 59454c4c4f57205355424d4152494e452059454c4c4f57205355424d4152494e and an empty AAD:

vector 1, an empty plaintext, 77 bytes:
0100000007 43a2e39431cbae0389d3fc86adf46f7c3a24de88d9311617
e53f3164cc1d5dc738a66b97f0bf786565c31799c2f463d50a7e10046011dc6f
c3c939e3a5db7affb6191551669554fb

vector 2, a plaintext of 7 bytes, 84 bytes:
0100000007 a1a1b56f6db58cd1ede0c5c9db62aef20d3f96a6c594bb92
52bb38122de91236502b42a1d7fcab820ffa292940d2f86add212cfa42c38df1
9d3cc9139ee61a5990d3db57433514229beea49a8a72bd

The lines are the prefix and the salt, the commitment, and the final chunk. In the bare form the vectors’ ct are the stored values as they are.

Vector 2 in the envelope form, with the 7 bytes wrapped as the encrypted DEK, 90 bytes:

0000000777726170706564 a1a1b56f6db58cd1ede0c5c9db62aef20d3f96a6c594bb92
52bb38122de91236502b42a1d7fcab820ffa292940d2f86add212cfa42c38df1
9d3cc9139ee61a5990d3db57433514229beea49a8a72bd

The first line is w, the encrypted DEK and the salt. A real encrypted DEK is the provider’s, see Encrypted DEKs. Its bytes play no part in the key derivation, which takes the DEK.

Signature and MAC formats

This page has the layouts of signatures and MACs, what they are computed over, the key ids of signing keys and the test vectors. Read it to verify a signature or a MAC outside the library. The layouts of every kind of value are listed on Formats.

Detached and attached signatures and MACs are Tink-prefixed values:

LayoutTypeBytes
Detached signatureSignature<T>[0x01][key id: u32 BE][signature]
Attached signatureSigned<T>[0x01][key id: u32 BE][w: u16 BE][signature: w][payload]
Detached MACMac<T>[0x01][key id: u32 BE][tag]
Attached MACWithMac<T>[0x01][key id: u32 BE][w: u16 BE][tag: w][payload]
  • 0x01 is the version of the layout. A later layout takes another first byte;
  • the key id names the key that signed or computed the tag. It is not authenticated and is a hint only: a value whose id is changed verifies under no key;
  • the signature is the raw signature of the key’s algorithm: 64 bytes for Ed25519 (RFC 8032) and r || s with each scalar left-padded to 32 bytes for P-256. The algorithm is not in the value: the verifying key fixes it;
  • the tag is the full HMAC output, never truncated: 32 bytes under HMAC-SHA256, 64 under HMAC-SHA512. The key version’s algorithm fixes the length;
  • w is the signature or tag length of an attached value, 1 to 65,535, so a reader finds the payload at offset 7 + w without knowing the key.

TryFrom<Vec<u8>> checks a value against its layout and fails with INVALID_SIGNATURE_FORMAT or INVALID_MAC_FORMAT.

Every signature and every MAC is computed over the pre-image, never over the payload itself. It is the Pre-Authentication Encoding (PAE) of DSSE, the Dead Simple Signing Envelope, with the SHA-256 of the payload as its body:

pre-image = "DSSEv1" SP DEC(len(type)) SP type SP "32" SP SHA-256(payload)
  • SP is one byte 0x20;
  • DEC(n) is n in ASCII decimal with no leading zeros;
  • type is the payload type: 1 to 255 bytes of visible ASCII, 0x21 to 0x7E, such as application/vnd.example.invoice+json;
  • SHA-256(payload) is the 32-byte digest of the payload bytes.

The pre-image is 46 to 302 bytes long. Ed25519 signs it as it is, and ECDSA P-256 signs its SHA-256. A MAC is the HMAC of the pre-image. The payload is the bytes Signable::to_payload returns, which the library neither parses nor re-serialises.

The key id of a signing key is derived from its public key:

thumbprint input = {"crv":"Ed25519","kty":"OKP","x":"<base64url of the 32 bytes>"}
                 | {"crv":"P-256","kty":"EC","x":"<base64url of x>","y":"<base64url of y>"}
digest           = SHA-256(thumbprint input)
kid              = base64url(digest), without padding, 43 characters
key id           = the first four bytes of digest, as a big-endian u32

The thumbprint input is the JWK thumbprint of RFC 7638: the required members of the key in lexicographic order, with no whitespace. A publisher with a numbering of its own sets the id instead, and the published key carries it as the integer member kms_aead_key_id. The key id of a MAC key is the keyring’s id of the version, see Keyring key ids.

A set of public keys is a JWK Set (RFC 7517). Each key has kty, crv, x (and y), kid the full thumbprint, use sig and alg EdDSA or ES256, and kms_aead_key_id where the publisher set the id:

{"keys":[
  {"kty":"OKP","crv":"Ed25519","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo",
   "kid":"kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k","use":"sig","alg":"EdDSA"},
  {"kty":"EC","crv":"P-256","x":"YP7UuiVanTHJYet0xjVtaMBJuJI7Yfps5mliLmDyn7Y",
   "y":"eQP-EAi4vJmkGunpVii8ZPLxsgwtfp9Rd6PClNRGIpk",
   "kid":"DOvxvJiAdIqVWIkFt5hDtCunXLF0BV4-JGv4f-ALSm0","use":"sig","alg":"ES256"}
]}

The signed keyring record

A keyring record carries its signature as the top-level member signature, the standard base64 of a detached Signature over the record’s canonical document:

canonical = JCS(record document without its "signature" member)
pre-image = PAE("application/vnd.kms-aead.keyring-record+json", SHA-256(canonical))

JCS is the JSON Canonicalization Scheme of RFC 8785: members sorted by name, no whitespace, standard string escaping with non-ASCII kept as UTF-8 and control characters as \u00XX. It is computed over the parsed JSON document with every member kept, including members the reader does not know, so a newer release may add members and sign records that carry them. A record holds strings, integers, booleans, null, arrays and objects; a fraction, an exponent or an integer beyond 2^53 anywhere in it is RECORD_INVALID. The canonical document of a record with a null, a nested compromised, a note holding é and the control character 0x07, and a member future the reader does not define, on one line of 579 bytes without the line breaks shown here:

{"algorithms":{"beacon":null,"deterministic":null,"mac":null,"randomized":"aes-256-gcm"},
"created_at":"2026-10-25T09:00:00Z","future":{"a":[true,null],"b":1},"id":"tenant-42",
"kek":{"key":"tenant-kek","provider":"local"},"schema":1,"seal_epoch":1,
"updated_at":"2026-10-25T09:00:00Z","versions":[{"algorithm":"aes-256-gcm",
"compromised":{"at":"2026-10-25T09:00:00Z","note":"clé \u0007"},
"created_at":"2026-10-25T09:00:00Z","encrypted_dek":"AQ==","kek_version":"1","key_id":1,
"seal_epochs":{"end":null,"start":1},"state":"decrypt_only",
"state_changed_at":"2026-10-25T09:00:00Z"}]}

Its SHA-256 is 195ad529d5ec1beec7f6d806169d598723bf067c6abd6b522ab330310f2d79d2, with é as the two bytes c3 a9. The pre-image is DSSEv1 44 application/vnd.kms-aead.keyring-record+json 32 and that digest, 90 bytes. Under the Ed25519 key of the vectors below the stored member is "signature": "AZD6yv6RAlxJsp1uzsdIQxlvyawlD282Dfrtg3QthYeSPnQ02B6jbpOBFA65Y2Zq5lILiXyyTCxj9bv36JGSWC2H2UAG".

Signature and MAC test vectors

Generated with Python’s cryptography package from published keys, so that nothing in them is secret. Payload type application/vnd.example.invoice+json, payload {"number":"INV-1042","customer":"Northwind Traders","currency":"EUR","total_cents":12500}:

SHA-256(payload)       7b43154b748a12c6909cba38acd83fff12a11b6345effb807b21c7ce465e4cd1
pre-image (82 bytes)   445353457631203336206170706c69636174696f6e2f766e642e6578616d706c652e
                       696e766f6963652b6a736f6e203332207b43154b748a12c6909cba38acd83fff12a1
                       1b6345effb807b21c7ce465e4cd1
SHA-256(pre-image)     4617fb02679fc4831b071fb2a064a33c2999e5f6a3c2fb65a96474d5663950be

Ed25519, the RFC 8032 section 7.1 test 1 key, seed 9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60:

public key             d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a
SubjectPublicKeyInfo   302a300506032b6570032100 || public key
PKCS#8                 302e020100300506032b657004220420 || seed
thumbprint input       {"crv":"Ed25519","kty":"OKP","x":"11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo"}
kid                    kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k
key id                 90facafe = 2432355070
signature              21c5f4d55977b19640f25f0e248d4c9765aa0d210f9c781b61b46dece74d4dec
                       b950acf3947659a9fff322b88ad8562e2c9ee4392440a4da901b7fec385f1102
detached (69 bytes)    0190facafe || signature
attached (160 bytes)   0190facafe0040 || signature || payload

ECDSA P-256, the RFC 6979 A.2.5 key, private scalar c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721. ECDSA signing is randomised, so the signature verifies and is not reproduced:

x                      60fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6
y                      7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299
SubjectPublicKeyInfo   3059301306072a8648ce3d020106082a8648ce3d030107034200 || 04 || x || y
thumbprint input       {"crv":"P-256","kty":"EC","x":"YP7UuiVanTHJYet0xjVtaMBJuJI7Yfps5mliLmDyn7Y","y":"eQP-EAi4vJmkGunpVii8ZPLxsgwtfp9Rd6PClNRGIpk"}
kid                    DOvxvJiAdIqVWIkFt5hDtCunXLF0BV4-JGv4f-ALSm0
key id                 0cebf1bc = 216789436
signature as DER       30450220409b9927a7f27d61f6d7360b9b91941fa6dd14db553a55d0dd573fc9db7fccb7
                       022100af3a4aaab89c0684256afe5db6aa53e4569286bc2c2f6435fe7563db215b5976
r || s                 409b9927a7f27d61f6d7360b9b91941fa6dd14db553a55d0dd573fc9db7fccb7
                       af3a4aaab89c0684256afe5db6aa53e4569286bc2c2f6435fe7563db215b5976
detached (69 bytes)    010cebf1bc || r || s

HMAC-SHA256 under the key of 32 bytes 0x42, key id 3221225473, the first MAC version of a keyring:

tag                    a2ca416600c31c19620b0b021986b1116ef1186318b32d819659093c125737f9
detached (37 bytes)    01c0000001 || tag
attached (128 bytes)   01c00000010020 || tag || payload

HMAC-SHA512 under the key of 64 bytes 0x42, key id 3221225474, the second MAC version:

tag                    620e50560d4f30c943664d8671c2788db8a1165c742ab379afaf9047dfa3610a
                       ca85a98e462c791f19d966e04b90748ce397755de7dc86a49f511a9021331ac3
detached (69 bytes)    01c0000002 || tag
attached (160 bytes)   01c00000020040 || tag || payload

The primitives are checked against Wycheproof on every backend, and these vectors on ring, aws-lc-rs, RustCrypto and, with tests/webcrypto_vectors.mjs, WebCrypto under Node.

Keyring records and keysets

This page has the key ids, the stored record and the encryption markers of kms-aead-keyring, and the Tink keysets that carry keys to Tink and BigQuery. Read it to write a keyring store, to read a record outside the library, or to query encryption markers. The layouts of every kind of value are listed on Formats.

Tink keysets and the TINK prefix

Two items describe the TINK-prefixed values:

  • kms_aead::KeyId: the key id of Tink’s output prefix of type TINK, [0x01][key id: u32 BE], the start of every Randomized and Deterministic value and of every beacon. It picks the key that decrypts the value, and Tink and BigQuery pick the key of a keyset by it. It is not authenticated;
  • kms_aead::formats::TinkKeyset: a serialised google.crypto.tink.Keyset of enabled, symmetric, TINK-prefixed keys, the bytes tinkey writes for the same keys. Encrypted by a Cloud KMS key, it is the keyset of BigQuery’s KEYS.KEYSET_CHAIN: an application writes it for its one key, see One fixed key, and a keyring exports it for its versions.

TinkKeyset::into_encrypted_bytes writes the keyset encrypted by a KMS key, as Tink writes an encrypted keyset: a google.crypto.tink.EncryptedKeyset whose encrypted_keyset, field 2, is the KMS ciphertext of the serialised keyset, encrypted with no associated data. Tink’s binary keyset writers leave out keyset_info, field 3, and so does the library. Tink’s KeysetHandle.read reads it with the KMS client of KekRef::tink_key_uri, which Tink has for GCP and AWS keys, and Tink for Go for Vault Transit keys too. A keyring exports it for its versions, see Exporting a keyset to Tink.

Keyring key ids

kms-aead-keyring writes the key id of a version into the TINK prefix of every value and beacon under it. The two high bits of the id are the purpose, and bits 0 to 23 are the ordinal:

BitsMeaning
31set for deterministic versions, alone
30set for beacon versions, alone
31 and 30set for MAC versions
24 to 29reserved: clear in the id of every version
0 to 23the ordinal, from 1, counted per purpose

So the ids of each purpose are:

  • randomised: 1, 2, 3, …;
  • deterministic: 2147483649, 2147483650, …;
  • beacon: 1073741825, 1073741826, …;
  • MAC: 3221225473, 3221225474, ….

Two kinds of id are reserved, and no version has one:

  • an id whose ordinal is 0: 0, 2^30, 2^31 and 2^31 + 2^30;
  • an id with any of bits 24 to 29 set. These bits are kept for purposes a later release may add, so a reader refuses such an id rather than take it for a version of one of the four purposes.

A value that carries a reserved id fails with ReservedKeyId, and a value whose id is of another purpose than the call fails with KeyPurposeMismatch. Both fail before any store or KMS call. A record that holds a reserved id fails with RecordInvalid and the reason ReservedKeyId. Each purpose has 2^24 - 1 ordinals, and ids are never reused: a destroyed version keeps its id in the record. A key id goes up to 2^32 - 1, so a SQL column holding one is a BIGINT.

Keyring records

kms-aead-keyring keeps a keyring record as one JSON document, the same in every keyring store. A record with deterministic and beacon versions, after one randomised rotation and with another one staged, with the encrypted DEKs shortened:

{
  "schema": 1,
  "id": "tenant-42",
  "kek": { "provider": "local", "key": "tenant-kek" },
  "algorithms": {
    "randomized": "aes-256-gcm",
    "deterministic": "aes-256-siv",
    "beacon": "hmac-sha256",
    "mac": null
  },
  "seal_epoch": 2,
  "versions": [
    {
      "key_id": 1,
      "algorithm": "aes-256-gcm",
      "state": "decrypt_only",
      "compromised": null,
      "seal_epochs": { "start": 1, "end": 2 },
      "created_at": "2026-10-18T12:18:31.053483320Z",
      "state_changed_at": "2026-10-18T12:18:31.054258061Z",
      "encrypted_dek": "AQp0ZW5hbnQta2VrAAAAAV6OYLYtnCqk...",
      "kek_version": "1"
    },
    {
      "key_id": 2147483649,
      "algorithm": "aes-256-siv",
      "state": "active",
      "compromised": null,
      "seal_epochs": { "start": 1, "end": null },
      "created_at": "2026-10-18T12:18:31.053483320Z",
      "state_changed_at": "2026-10-18T12:18:31.053483320Z",
      "encrypted_dek": "AQp0ZW5hbnQta2VrAAAAAeY4U51ScBd+...",
      "kek_version": "1"
    },
    {
      "key_id": 1073741825,
      "algorithm": "hmac-sha256",
      "state": "active",
      "compromised": null,
      "seal_epochs": { "start": 1, "end": null },
      "created_at": "2026-10-18T12:18:31.053483320Z",
      "state_changed_at": "2026-10-18T12:18:31.053483320Z",
      "encrypted_dek": "AQp0ZW5hbnQta2VrAAAAAWYRS+ENPZF7...",
      "kek_version": "1"
    },
    {
      "key_id": 2,
      "algorithm": "aes-256-gcm",
      "state": "active",
      "compromised": null,
      "seal_epochs": { "start": 2, "end": null },
      "created_at": "2026-10-18T12:18:31.053897100Z",
      "state_changed_at": "2026-10-18T12:18:31.054258061Z",
      "encrypted_dek": "AQp0ZW5hbnQta2VrAAAAASNGwiIu93uT...",
      "kek_version": "1"
    },
    {
      "key_id": 3,
      "algorithm": "aes-256-gcm",
      "state": "pending",
      "compromised": null,
      "seal_epochs": null,
      "created_at": "2026-10-18T12:18:31.054603074Z",
      "state_changed_at": "2026-10-18T12:18:31.054603074Z",
      "encrypted_dek": "AQp0ZW5hbnQta2VrAAAAAWVYn2R7AWay...",
      "kek_version": "1"
    }
  ],
  "created_at": "2026-10-18T12:18:31.053483320Z",
  "updated_at": "2026-10-18T12:18:31.054603074Z"
}
  • schema is 1;
  • kek names the provider and the KEK the keyring was created with;
  • algorithms holds the algorithm new versions of each purpose use. deterministic, beacon and mac are null for a keyring without versions of that purpose. mac is mac-hmac-sha256 or mac-hmac-sha512, distinct from the beacon’s hmac-sha256, since the algorithm name fixes a version’s purpose;
  • signature is an optional top-level member, absent from the record above: "signature": "<standard base64 of the detached Signature bytes>", written where the administration signs its records, see The signed keyring record. A reader that predates record signing ignores it;
  • seal_epoch is the record’s re-encryption epoch: it counts the writes that made a version active, from 1 at the creation, see Encryption markers;
  • versions holds every version ever created, in creation order, each under its key id;
  • state is pending, active, decrypt_only, retired or destroyed. For a pending version, state_changed_at is the time it was staged;
  • compromised is null, or {"at": "<time>", "note": "<the operator's note, or null>"};
  • seal_epochs is the version’s re-encryption range as epochs, {"start": <epoch>, "end": <epoch or null>}: the epoch of the write that made it active, and the epoch of the first write after it stopped being active that moved the epoch on, null until then. It is null for a version that was never active, see Encryption markers;
  • encrypted_dek is the standard base64 of the encrypted DEK, the bytes the provider returned, here the local KMS layout. It is null for a destroyed version;
  • kek_version is the version of the KEK that encrypted encrypted_dek, as the KMS reported it, here the local KEK version. It is null for a destroyed version, and under a KMS that reports none, such as AWS KMS;
  • the times are RFC 3339, in UTC.

A reader parses at most 1 MiB of JSON. The size of a version is mostly its encrypted DEK, so the number of versions that fit depends on the KMS:

KEKBytes per versionVersions in 1 MiB
local KMS359about 2,900
Vault Transit380about 2,750
GCP Cloud KMS412about 2,550
AWS KMS504about 2,050
Azure, RSA 2048-bit key674about 1,550
Azure, RSA 4096-bit key1,014about 1,050
Cloud KMS, RSA 2048-bit key, public-key encryption (computed)608about 1,700
Cloud KMS, RSA 3072-bit key, public-key encryption (computed)776about 1,350
Cloud KMS, RSA 4096-bit key, public-key encryption (computed)948about 1,100
AWS KMS, RSA 2048-bit key, public-key encryption (computed)602about 1,750
AWS KMS, RSA 4096-bit key, public-key encryption (computed)942about 1,100
Azure, RSA 2048-bit key, public-key encryption (computed)678about 1,550
Azure, RSA 4096-bit key, public-key encryption (computed)1,018about 1,000
Vault Transit, RSA 2048-bit key, public-key encryption (computed)608about 1,700
local KMS, RSA 2048-bit key, 10-byte KEK id, public-key encryption (computed)619about 1,700

The local KMS row was measured on a record the crate wrote after 500 randomised rotations, each version AES-256-GCM, decrypt-only with a re-encryption range. The other rows are the same record with each encrypted DEK replaced by one of that KMS’s length, and a KEK version of that KMS’s form: none for AWS, two digits for GCP and Vault, 32 hex digits for Azure. The rows marked computed were not measured: they are the same record with the encrypted DEK of the 0x02 layout, the header and one RSA block, see DEKs encrypted with a public key.

A reader fails with RecordInvalid on a document that breaks any of:

  • at most one active and one pending version per purpose, neither of them compromised;
  • an encrypted DEK on every version but the destroyed ones, and a kek_version, when there is one, of 1 to 255 ASCII alphanumerics beside it;
  • unique key ids of the purpose of their algorithm, increasing within a purpose in creation order;
  • no two versions with the same encrypted_dek bytes (DuplicateEncryptedDek), so that a key filed under a second id is refused where the record is read;
  • a seal_epoch of 1 or more;
  • seal_epochs on every active, decrypt-only and retired version and on no pending one, open on the active version, starting at 1 or more and below its end, and within the seal_epoch.

A reader reads past a member it does not know, at any depth, and keeps it in the canonical digest that a signature covers. An administrative write refuses a record that holds one, with RecordInvalid and the reason UnknownMembers, before it writes anything: the record it writes holds only the members its release knows, so the others would be lost, and a signing administration would sign what is left. Once a later release writes a member into a record, an administrative binary of an earlier release still reads the record and no longer writes it, until it moves to that release.

Encryption markers

An encryption marker is the re-encryption epoch of the keyring record a write encrypted a record’s fields under, which the application stores beside them:

[0x01][re-encryption epoch: u32 BE]

5 bytes in all, so that markers compare as their epochs do, and so do their bytes as Firestore, PostgreSQL and BigQuery compare them. EncryptionMarker::ENVELOPE, 01 00 00 00 00, is epoch 0, the marker of a record of envelope values. EncryptionMarker::try_from fails with InvalidEncryptionMarker on bytes of any other length or first byte. Serde stores a marker as bytes, an array of numbers in serde_json, and the postgres and sqlx features as BYTEA. See Sweeps for the query it serves.

The record’s JSON members for the epoch and the ranges keep the names seal_epoch and seal_epochs. KeyVersion::reencrypt_range() returns the markers of a version’s seal_epochs as a ReencryptRange: start(), and end(), None while the range is open. A record whose fields were encrypted through one Encryptor, and which stores the marker of the encryptor’s record, lies in the range of every version its fields are under. See Records under a version for the query it serves.

Error handling

This page lists the errors of both crates: the variants of KmsAeadError and the codes of the library, what may be retried, the errors of kms-aead-keyring, and what an error never carries. Read it to decide how a caller reacts to a failure; the Incident runbook covers what an operator does about one.

Every fallible call returns KmsAeadResult<T>, whose error is kms_aead::errors::KmsAeadError:

  • SystemError: the configuration or the environment, such as invalid provider options or a KMS client that cannot be built, and the caller’s own source or sink of a stream failing (STREAM_IO);
  • NetworkError: a KMS that could not be reached, did not answer in time, failed on its side or limited the rate of requests. The same call may succeed later;
  • EncryptionError: encrypting or decrypting a value or a DEK failed, a stored value could not be read, or a KMS refused the request, such as a denied permission or a disabled key. The same call fails the same way again;
  • UnsupportedAlgorithm: the backend does not implement the algorithm, from constructors only;
  • SignatureError: a signature could not be made, read or verified, or a KMS refused a sign or public-key request; never retried.

The enum is #[non_exhaustive], so a match on it needs a _ arm.

Codes

code() returns a code to match on: one of the library’s own codes, or the code the KMS returned, such as AWS’s IncorrectKeyException. It is also the error_code field of the spans.

use kms_aead::backends::Ring;
use kms_aead::errors::KmsAeadError;
use kms_aead::formats::Bare;
use kms_aead::{AeadAlgorithm, AeadCipher, Encrypted};
use secret_vault_value::SecretValue;

fn main() -> kms_aead::KmsAeadResult<()> {
let cipher = AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?;
let dek = cipher.generate_dek()?;
let cipher_text: Encrypted<SecretValue, Bare> =
    cipher.encrypt_bare(b"orders/1042", &SecretValue::from("secret"), &dek)?;

match cipher.decrypt_bare(b"orders/1043", &cipher_text, &dek) {
    Err(KmsAeadError::EncryptionError(error)) if error.public.code == "DECRYPT" => {
        // Not authentic under this key and AAD
    }
    other => panic!("{other:?}"),
}

let too_short = Encrypted::<SecretValue, Bare>::try_from(vec![0; 8]);
assert!(matches!(&too_short, Err(e) if e.code() == "INVALID_CIPHER_TEXT_FORMAT"));
Ok(())
}

The library’s codes, by area:

Values, keys and formats

CodeVariantMeaning
ENCRYPT, DECRYPTencryptionencrypting failed, or a value, or a chunk of a streamed value, is not authentic under the key and the AAD, among them a final chunk that a sequential read finds cut or followed by more bytes
ENCRYPT_KEY, DECRYPT_KEYencryptionthe backend refused a key, or a KMS request could not be built
RANDOM_GENERATORencryptionthe CSPRNG failed, for a nonce or a key
INVALID_KEY_LENGTHencryptiona key that does not fit the algorithm, such as a MAC key of another length than 32 or 64 bytes, a KMS generator that returned another length, or a DEK longer than the OAEP limit of the public key it is encrypted with
UNSUPPORTED_ALGORITHMunsupported algorithmthe backend does not implement the algorithm, an AEAD algorithm or an asymmetric KEK algorithm such as RSA-OAEP on ring. algorithm is a BackendAlgorithm
UNKNOWN_ALGORITHMencryptionFromStr of an algorithm name it does not know, a signing or MAC algorithm included
INVALID_CIPHER_TEXT_FORMATencryptiona stored value whose layout does not parse, see the cases below the table
UNKNOWN_CIPHER_TEXT_LAYOUTencryptionan empty envelope value, or a first byte that starts no layout
INVALID_PLAINTEXTencryptiona decrypted value that is not an encoding of its type, or a JsonEncoded value that does not serialise
INVALID_KEY_FORMATencryptiona decrypted DEK that is not a serialised Tink key, such as an encrypted keyset
INVALID_KEY_VERSIONencryptiona key version that is not ASCII alphanumeric, in an Azure encrypted DEK
INVALID_HEXencryptiontry_from_hex_string of text that is not hex
LEGACY_FORMATencryptiona layout of 0.29 or earlier, at Encrypted::try_from or at decryption, see Values written by 0.29 and earlier
INVALID_DEK_CACHE_TTLsystema DEK cache TTL of zero
INVALID_DEK_REUSE_POLICYsystema reuse policy out of range, or beside a disabled cache

INVALID_CIPHER_TEXT_FORMAT is returned for:

  • a value too short, or a length past its end;
  • a Randomized or Deterministic value without Tink’s output prefix;
  • a stream header that is not 61 bytes (56 bare) or does not start with 0x01;
  • an envelope stream header whose encrypted DEK length is not 1 to 4,096 or that is not 60 + w bytes.

Beacons, MACs and digests

CodeVariantMeaning
INVALID_BEACON_FORMATencryptionstored bytes that are not [0x01][key id: u32 BE] and 1 to 32 bytes of HMAC, at Beacon::try_from
INVALID_BEACON_CONTEXTencryptiona beacon context longer than 2^32 - 1 bytes
BEACONencryptionthe backend failed to calculate a beacon’s HMAC
INVALID_PAYLOADencryptionto_payload or from_payload failed, from a signing or a MAC call, such as a payload that is not the JSON of a JsonEncoded type
MAC_INVALIDencryptionthe tag does not match, or is not the length of the key’s algorithm
INVALID_MAC_FORMATencryptionbytes that are not a Mac or WithMac layout
MACencryptionthe backend failed to compute an HMAC
DIGESTencryptionthe backend failed to compute a SHA-256, of a payload or a pre-image

Streams

CodeVariantMeaning
STREAM_ALGORITHMencryptiona cipher or key version whose algorithm is not AES-256-GCM asked to encrypt or decrypt a streamed value
STREAM_LENGTHencryptiona length or a source that the length rules of the stream format refuse, see the cases below the table
STREAM_KEY_COMMITMENTencryptionthe header’s commitment is not the one the DEK, the salt and the AAD derive: a wrong key, a wrong AAD, or a modified salt or commitment
STREAM_RANGEencryptiona plaintext range past the value’s length or with start > end, or a chunk read plan of a value in another form
STREAM_IOsystemthe source or the sink of a stream call failed, see the cases below the table. The source’s or sink’s error is the root cause. The retry is the whole stream again

STREAM_LENGTH is returned for:

  • a stored length that the length rules refuse, given to StreamFormat::plan_chunk_read or plan_final_chunk_read;
  • bytes given to decrypt_chunk_read of another length than the plan’s ciphertext();
  • a source of a sequential read that ends at a chunk boundary or less than a tag into a chunk, where no value ends, or holds more chunks than a value can;
  • a source that ends inside the header that decrypting_stream or decrypting_reader read.

STREAM_IO is returned when:

  • the source or the sink of encrypt_stream or decrypt_stream failed;
  • the source of an EncryptingStream or a DecryptingStream failed;
  • the source of decrypting_stream or decrypting_reader failed while they read the header.

Asymmetric KEKs

CodeVariantMeaning
ASYMMETRIC_ENCRYPTED_DEK_FORMATencryptiona 0x02 encrypted DEK with an unknown algorithm byte, a header past the end, an i or k of another shape than the reading provider’s, or a block of another length than its key’s, before any KMS call
ASYMMETRIC_KEK_PUBLIC_KEYsystema public key or a KEK version that cannot be used, see the cases below the table
ASYMMETRIC_KEK_PRIVATE_KEYsystemlocal private key bytes that are not in the named PrivateKeyFormat, or not an RSA key of 2048, 3072 or 4096 bits
ASYMMETRIC_KEK_MISMATCHsysteman AsymmetricKekProvider whose public key names another KEK than its KMS provider, or a pinned producer whose key has another fingerprint

ASYMMETRIC_KEK_PUBLIC_KEY is returned for:

  • public key bytes that are not in the named PublicKeyFormat;
  • a key that is not an RSA key of 2048, 3072 or 4096 bits;
  • a key the backend refuses;
  • a KEK version missing where the KMS decrypts with one, present under AWS, or not a decimal version for a local KEK;
  • a KMS key the fetch describes as another kind.

Signatures

CodeVariantMeaning
SIGN_KEY, GET_PUBLIC_KEYsignaturea Cloud KMS signing request, or its public key request, whose routing header could not be built
SIGNATURE_INVALIDsignatureno key with the signature’s key id verifies it
SIGNING_KEY_UNKNOWNsignatureno key in the set has the signature’s key id: the set is stale, or the signer is not trusted; also with_record_signer, create_signed and open_or_create_signed with a signer the registry’s record verification does not hold
INVALID_SIGNATURE_FORMATsignaturebytes that are not a Signature or Signed layout, at TryFrom
SIGNATURE_ENCODINGsignaturethe KMS returned a signature that is not strict DER, or not 64 bytes, or a Cloud KMS checksum failed
SIGNING_KEY_MISMATCHsignaturethe KMS response names another key or version than the configured one
SIGNING_ALGORITHM_MISMATCHsignaturethe KMS key is not of the configured algorithm
INVALID_PUBLIC_KEYsignaturea public key, JWK or JWK Set that does not parse, is of another algorithm, is not on the curve, or is an Ed25519 point of order 8 or less
EMPTY_KEY_SETsignatureVerifier::new with no key, and KeyringRegistry::new with RecordSignaturePolicy::Required and no key
DUPLICATE_KEY_IDsignaturetwo different keys under one key id, at VerifyingKeySet::new, insert or from_jwks, or two local versions sharing one
SIGNsignaturethe backend failed to sign with a local signing key
INVALID_LOCAL_SIGNING_KEY_NAMEsystema local signing key name that is empty, longer than 255 bytes or holds another character than the name allows
LOCAL_SIGNING_KEY_SOURCEsystema key file that cannot be read, is not a regular file or is too large, or an environment variable that is unset, too large or not base64 where base64 is expected
LOCAL_SIGNING_KEY_FORMATsystemkey bytes that are not the format, another algorithm, an encrypted PKCS#8 or a P-256 key without its public point, or a key the backend refuses
LOCAL_SIGNING_KEY_VERSIONSsystema local signing provider with no keys, or with a version listed twice
AWS_SIGNING_KEY_ALIASsysteman AWS signing key named by an alias, which a rotation could point at another key

Providers

CodeVariantMeaning
AWS_ERRORencryptionan AWS KMS response without the encrypted DEK, the plaintext DEK or the random bytes it was asked for, see AWS KMS
INVALID_LOCAL_KEK_ID, LOCAL_*system, encryptionthe local KMS
AZURE_*system, encryptionthe Azure provider
VAULT_*system, network, encryptionthe Vault Transit provider

The KMS codes are the gRPC status codes of Google Cloud KMS, such as PermissionDenied, the AWS error codes, such as NotFoundException, and Key Vault’s error codes, such as KeyNotFound. A sign or public-key request that fails with a network code is a NetworkError, and with any other KMS code a SignatureError that keeps the KMS’s code.

Retries

The library retries nothing itself. The AWS and Azure SDKs apply their own retry policies, which the Azure provider takes in client_options.

A NetworkError may be retried, with a backoff. An EncryptionError or a SignatureError should not be: a revoked permission, a missing key or an encrypted DEK of another key fails the same way on every retry.

The variant per provider:

Google Cloud KMS

  • NetworkError: gRPC Unavailable, DeadlineExceeded, ResourceExhausted, Aborted, Internal, Unknown, Cancelled;
  • EncryptionError: any other gRPC code, such as PermissionDenied, Unauthenticated, NotFound, InvalidArgument, FailedPrecondition.

AWS KMS

  • NetworkError: ThrottlingException, KMSInternalException, DependencyTimeoutException, KeyUnavailableException, a 5xx or 429 status, a timeout, a connection failure, a response the SDK could not read;
  • EncryptionError: any other AWS error code, such as AccessDeniedException, NotFoundException, IncorrectKeyException, InvalidCiphertextException, DisabledException, KMSInvalidStateException, a request that could not be built or signed, and AWS_ERROR.

Azure Key Vault

  • NetworkError: a 5xx or 429 status, a connection or I/O failure;
  • EncryptionError: any other status, such as Forbidden or KeyNotFound, and a response that does not parse.

Vault Transit

  • NetworkError: VAULT_STATUS_5xx, VAULT_STATUS_429, VAULT_HTTP, VAULT_TIMEOUT;
  • EncryptionError: any other VAULT_STATUS_<status>, VAULT_RESPONSE, VAULT_RESPONSE_TOO_LARGE, VAULT_CIPHERTEXT.

Google’s client libraries retry the Cloud KMS Encrypt and Decrypt calls on Unavailable and DeadlineExceeded only. Keep a retry on the other Google Cloud KMS network codes to a few attempts.

STREAM_IO is the caller’s own source or sink failing, such as a reset download or a full disk, and the library cannot tell whether it may be retried. The root cause is the source’s or the sink’s error, and it says whether a retry can help. The retry is the whole stream again, from the start.

Keyring errors

Every fallible call of kms-aead-keyring returns KeyringResult<T>, whose error is KeyringError, also #[non_exhaustive]. code() returns kms-aead’s code for KmsAead, such as DECRYPT or a KMS’s code, and the variant’s name in upper snake case otherwise, such as KEY_VERSION_COMPROMISED. It is the error_code field of the keyring’s spans and the error.type of its metrics. Match on the variant and its fields, or on the code: the Display text may change in any release.

Records and the store

VariantCodeMeaning
KmsAeadkms-aead’sa KMS call, a decryption or an encoding failed, see Codes
StoreSTOREthe keyring store failed: store, operation, and the client’s error as root_cause and source()
InvalidIdentifierINVALID_IDENTIFIERa keyring id, an AAD part or a store name that breaks the rule of its type
RecordMissingRECORD_MISSINGno record for the keyring: at open and admin, before an administrative write, and from reload once the process took the record as deleted, see A record gone from the store. A dangerously_shred() of a keyring already gone returns Ok
RecordExistsRECORD_EXISTScreate found a record
RecordInvalidRECORD_INVALIDa record that breaks a size cap or an invariant, such as two versions holding the same encrypted DEK (DuplicateEncryptedDek) or a signature member that is not a detached signature (MalformedSignature); and before an administrative write, a record that holds members this release does not know (UnknownMembers), see Keyring records
RecordUnsignedRECORD_UNSIGNEDan unsigned record where record verification is Required, or where a signing admin writes over it, see Signing the keyring record
RecordSignatureInvalidRECORD_SIGNATURE_INVALIDa record whose signature fails under the verifying keys, or that is signed where the registry has no key; the cause carries the signature error’s code
RecordSignerMissingRECORD_SIGNER_MISSINGa write by an administration without a record signer over a signed record, before any store write; under Required, any write without one, before any KMS call or store write: create, open_or_create where it would create the record, after the one read that finds none, and every write of such an administration, dangerously_unsign_record included
RecordSignatureRemovedRECORD_SIGNATURE_REMOVEDan unsigned record where the process holds a signed one, under VerifyIfSigned, or held one before the record’s deletion; a create that it refuses writes nothing
RecordRegressedRECORD_REGRESSEDa record that moves a version backwards from the one this process holds, from reload and before an administrative write
RecordConflictRECORD_CONFLICTan administrative write lost every compare-and-swap, attempts of them
KekMismatchKEK_MISMATCHthe provider’s KEK is not the one the record names

Key versions

VariantCodeMeaning
NoActiveVersionNO_ACTIVE_VERSIONno active version of the purpose, so nothing new is encrypted under it
NoAlgorithmNO_ALGORITHMthe record names no algorithm for the purpose, so no version of it is created: change_algorithm sets one
KeyVersionUnknownKEY_VERSION_UNKNOWNno version with the value’s key id, also after a reload
KeyVersionRetiredKEY_VERSION_RETIREDthe value’s version is retired; reinstate brings it back
KeyVersionDestroyedKEY_VERSION_DESTROYEDthe value’s version is destroyed
KeyVersionPendingKEY_VERSION_PENDINGa pending version selected as the primary of a keyset export
KeyVersionCompromisedKEY_VERSION_COMPROMISEDthe value’s version is compromised under the Block policy
EncryptorOutdatedENCRYPTOR_OUTDATEDa value under a version newer than the encryptor’s record
KeyPurposeMismatchKEY_PURPOSE_MISMATCHa key id of another purpose than the call’s
InvalidTransitionINVALID_TRANSITIONa lifecycle call that does not apply to the version’s state, see States
PromotionTooEarlyPROMOTION_TOO_EARLYa promotion before record_ttl has passed since the version was staged
ReservedKeyIdRESERVED_KEY_IDa key id no version has: ordinal zero, or one of bits 24 to 29 set, see Keyring key ids
UnknownKeyVersionStateUNKNOWN_KEY_VERSION_STATEFromStr of a name that is no KeyVersionState

Other calls

VariantCodeMeaning
DeterministicDisabledDETERMINISTIC_DISABLEDa deterministic version created without the deterministic feature
InteropINTEROPan encryption or a keyset export that a field’s Interop reader would not read
CustomAadUnsupportedCUSTOM_AAD_UNSUPPORTEDcustom_aad on a field BigQuery decrypts
ExportAlgorithmUnsupportedEXPORT_ALGORITHM_UNSUPPORTEDa version in an export whose algorithm the keyset’s reader does not read
InvalidEncryptionMarkerINVALID_ENCRYPTION_MARKERstored bytes that are not an EncryptionMarker

What a caller may run again

Besides the retry policies of the store clients, such as aws-sdk-s3’s, the keyring retries only an administrative write’s compare-and-swap, up to cas_retries times. What a caller may run again:

  • KmsAead: as in Retries, a NetworkError with a backoff;
  • Store: the library does not classify a store’s errors, so the decision follows the client’s error in root_cause;
  • RecordConflict: the administrative call, which reads the record again;
  • EncryptorOutdated: the write, with a new encryptor from Keyring::encryptor, see Re-encrypting a value;
  • PromotionTooEarly: the promotion, once its remaining has passed.

The other variants fail the same way until the record, the configuration or the call changes.

What errors never carry

No error carries plaintext, key material in any form, plaintext or encrypted, AAD content or cipher text bytes, in Display or in Debug. An application can log errors with {} and {:?}. A JsonEncoded value that does not decode also logs a redacted outline of its JSON, see Observability.

message is meant for a person reading logs. public holds the code, the part safe to return to the application’s own callers, and it is Serialize and Deserialize. std::error::Error::source() returns the root cause, the error of the SDK or library that failed, when there is one.

Observability

kms-aead and kms-aead-keyring report what they do through tracing spans and events, and through OpenTelemetry metrics. This page lists the two pages that hold them and states what neither ever logs; read it before you enable the spans in a pipeline that other people can read:

  • Spans and events: one DEBUG span for every envelope call, KMS call and keyring call, with the fields of each; the events both crates log; how to show the spans and export them as OpenTelemetry traces; and the event of a JSON value that does not decode;
  • Metrics: the OpenTelemetry instruments of the opentelemetry feature, the views that leave out the smallest and the largest plaintext size and that limit the number of series, and the Prometheus names.

What is never logged

No span field or event carries:

  • plaintext, DEKs in any form, plaintext or encrypted, or KEK material;
  • AAD content, which can hold entity ids and so personal data;
  • cipher text bytes;
  • the length of a value or of its AAD. For AES-256-GCM the plaintext length is the value’s length minus a fixed overhead, and a length tells short values such as yes, no or a country code apart.

The kms_aead.plaintext.size histogram is the exception: it adds up plaintext lengths. A keyring or an envelope that encrypts one value per export interval gives that value’s length to whoever reads the metrics. The SDK also keeps the smallest and the largest value of each series, under cumulative temporality since the process started, and OTLP exports them: the exact length of the shortest and the longest value per keyring and version, at any traffic. A Prometheus exporter exports neither. The OpenTelemetry API gives kms-aead’s instrument no setting to leave them out, so the view in Metrics turns them off with record_min_max: false. Treat the histogram like the values themselves where traffic is low, and everywhere without that view.

The kms_aead::json event is the other exception, under a policy that opts in: its outline then carries the length of the values and keys of the JSON that did not decode, which gives away a hidden boolean, and the values the policy reveals. The default policy carries neither, but every policy shows serde_json’s message for a syntax error, which is fixed text and can state a property of a hidden value, such as number out of range.

Key identifiers are recorded: KEK names, key versions and local KEK ids. A KEK name identifies the project, the location and the key, and a per-tenant KEK name carries the tenant id, so treat the key field accordingly in a trace pipeline.

Errors follow the same rules, see Error handling.

Spans and events

This page has the spans and events of kms-aead and kms-aead-keyring, and the fields of each span. Read it to filter the library’s logs, to build traces, or to find the log line behind an alert. What they never carry is on Observability.

Spans

The library uses tracing. Every envelope call and every KMS call opens one span at the DEBUG level, and the spans carry what a call used besides how long it took: the mode, the algorithm and backend, whether the DEK came from the cache, the KMS key and its version, and the error code.

The spans are:

SpanOpened byFields
KMS AEAD encryptthe envelope’s encrypt, encrypt_with_dek, encrypt_with_encrypted_dek, stream_encryptor and stream_encryptor_baremode, algorithm, backend, dek_cache, error_code
KMS AEAD decryptthe envelope’s decrypt, decrypt_with_dek, decrypt_with_encrypted_dek, stream_decryptor and stream_decryptor_baremode, algorithm, backend, dek_cache, error_code
KMS AEAD generate DEKgenerate_encrypted_dek and generate_encrypted_deterministic_dekpurpose, algorithm, backend, error_code
KMS AEAD decrypt DEKdecrypt_deterministic_dekpurpose, algorithm, dek_cache, error_code
KMS AEAD re-encrypt DEKreencrypt_dek and reencrypt_encrypted_dekdek_cache, error_code
KMS AEAD beaconthe envelope’s beaconalgorithm, backend, dek_cache, error_code
KMS encrypt DEKeach provider’s encryption of a DEK, or its encryption with a public keyprovider, key, kek_version, response_time, error_code
KMS decrypt DEKeach provider’s decryption of a DEKprovider, key, kek_version, response_time, error_code
KMS randoma call to the GCP or AWS KMS generator, when the provider uses itprovider, key, len, response_time, error_code
Signature signa Signer’s sign, sign_attached and sign_digestalgorithm, backend, key_id, payload_type, error_code
Signature verifya Verifier’s verify, verify_signed and verify_digestalgorithm, backend, key_id, payload_type, error_code
MAC computean Authenticator’s mac and mac_attachedalgorithm, backend, key_id, payload_type, error_code
MAC verifyan Authenticator’s verify and verify_with_macalgorithm, backend, key_id, payload_type, error_code
KMS signeach signing provider’s sign requestprovider, key, response_time, error_code
KMS public keyeach signing provider’s request for the public key of its key, and each KMS provider’s public_key of an asymmetric KEKprovider, key, kek_version, response_time, error_code

The KMS spans nest inside the envelope span, so a DEK the envelope had to decrypt shows its KMS call as a child, and a DEK served by the cache shows none. AeadCipher and DeterministicCipher open no spans: they run once per value inside the caller’s span.

Showing the spans

Any tracing subscriber works. With tracing-subscriber, an EnvFilter that enables DEBUG for the library and span close events, every span is printed with its fields when it ends:

use kms_aead::backends::Ring;
use kms_aead::formats::Envelope;
use kms_aead::providers::{LocalKekId, LocalKmsProvider};
use kms_aead::{Encrypted, KmsAeadEnvelope};
use secret_vault_value::SecretValue;
use tracing_subscriber::fmt::format::FmtSpan;

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let subscriber = tracing_subscriber::fmt()
    .with_env_filter("kms_aead=debug")
    .with_span_events(FmtSpan::CLOSE)
    .finish();
tracing::subscriber::set_global_default(subscriber)?;

let provider = LocalKmsProvider::<Ring>::ephemeral(LocalKekId::try_from("example".to_string())?)?;
let envelope = KmsAeadEnvelope::<LocalKmsProvider<Ring>, Ring>::new(provider)?;

let aad = b"orders/1042";
let encrypted: Encrypted<SecretValue, Envelope> =
    envelope.encrypt(aad, &SecretValue::from("secret")).await?;
let decrypted: SecretValue = envelope.decrypt(aad, &encrypted).await?;
assert_eq!(decrypted, SecretValue::from("secret"));
Ok(())
}

The decrypt prints, without timestamps:

DEBUG KMS AEAD decrypt{/kms_aead/mode="per_call" /kms_aead/algorithm=aes-256-gcm /kms_aead/backend=ring /kms_aead/dek_cache=disabled}:KMS decrypt DEK{/kms_aead/provider=local /kms_aead/key="example" /kms_aead/kek_version="1" /kms_aead/response_time=0}: kms_aead::spans::kms: close time.busy=16.4µs time.idle=6.95µs
DEBUG KMS AEAD decrypt{/kms_aead/mode="per_call" /kms_aead/algorithm=aes-256-gcm /kms_aead/backend=ring /kms_aead/dek_cache=disabled}: kms_aead::spans: close time.busy=62.0µs time.idle=12.3µs

Full example available here, run it with cargo run --example tracing --features ring.

OpenTelemetry

With tracing-opentelemetry every span field becomes a span attribute with the same name, such as /kms_aead/kek_version, so the KMS calls and cache hits show up next to the latency of a request in Cloud Trace, Jaeger, etc.

The fields are declared empty when the span opens and recorded once their value is known, which tracing-opentelemetry exports the same way as fields given at the start. Add its layer to the subscriber as usual:

use opentelemetry::trace::TracerProvider;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;

let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder()
    .with_batch_exporter(exporter) // any exporter, e.g. opentelemetry-otlp
    .build();

tracing_subscriber::registry()
    .with(tracing_subscriber::EnvFilter::new("info,kms_aead=debug"))
    .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("my-service")))
    .init();

Be aware the library spans are DEBUG, so the filter has to enable that level for kms_aead.

Fields

Every field name has the /kms_aead/ prefix, such as /kms_aead/mode. A value nobody reported is left unrecorded, never recorded as 0 or an empty string.

FieldValue
modeon KMS AEAD encrypt and KMS AEAD decrypt: per_call for encrypt, decrypt and the stream calls, store_less for them on a store-less envelope, caller_dek for the *_with_dek and *_with_encrypted_dek calls
algorithmchacha20-poly1305, aes-128-gcm, aes-256-gcm or aes-256-gcm-siv on KMS AEAD encrypt and KMS AEAD decrypt; the algorithm of the key on KMS AEAD generate DEK and KMS AEAD decrypt DEK, aes-256-siv for deterministic keys; hmac-sha256 on KMS AEAD beacon; ed25519 or ecdsa-p256-sha256 on a signature span, mac-hmac-sha256 or mac-hmac-sha512 on a MAC span
backendring, aws-lc or rustcrypto; on KMS AEAD generate DEK the envelope’s backend
dek_cacheon KMS AEAD encrypt and KMS AEAD decrypt: disabled for an envelope without a cache; hit or miss for a call that decrypts through an enabled cache, a failed decryption recording miss; unrecorded for a call that looks nothing up. On KMS AEAD decrypt DEK and KMS AEAD re-encrypt DEK: bypassed beside an enabled cache, since the call never goes through it, disabled otherwise. On KMS AEAD beacon: disabled for an envelope without a cache; hit or miss with one, a failed decryption of the beacon key recording miss
purposerandomized or deterministic
providergcp, aws, azure, hc_vault_transit, local, or the name of an application’s own provider
keyon KMS encrypt DEK and KMS decrypt DEK the KEK, see below; on KMS random the GCP location, and unrecorded on AWS; on KMS sign and KMS public key the signing key, see SigningKeyRef::key, or the KEK of an asymmetric KEK’s public key
kek_versionon KMS encrypt DEK and KMS decrypt DEK: from the KMS response on encryption, and the public key’s version on an encryption with a public key; from the encrypted DEK’s bytes on decryption for Azure, Vault Transit, the local KMS and every DEK a public key encrypted; unrecorded when neither has one, as for AWS and a GCP decryption of a symmetric key. On KMS public key, the public key of an asymmetric KEK only: the version asked for, or the one the response names when none was
lenon KMS random: the bytes requested from the KMS generator
key_idthe decimal key id the signature or MAC names
payload_typethe PAYLOAD_TYPE of the signed type
response_timemilliseconds the KMS call took
error_codethe code of the error the call returned

A KMS AEAD re-encrypt DEK has a KMS decrypt DEK as a child under the version that encrypted the DEK and a KMS encrypt DEK under the current one. A beacon key the cache did not hold shows its KMS decrypt DEK as a child of KMS AEAD beacon.

The key of each provider:

  • GCP: the CryptoKey name, projects/<project>/locations/<location>/keyRings/<ring>/cryptoKeys/<key>;
  • AWS: the key or alias ARN, or the configured key id when no region is known;
  • Azure: <vault URL>/keys/<name>;
  • Vault Transit: <vault address>/<namespace>/<mount>/keys/<name>, without the namespace segment when none is set;
  • local: the KEK id.

With the opentelemetry feature the signing and MAC calls record their duration as the envelope calls do. The spans carry no payload, signature, tag or key bytes.

Events

Besides the spans, the library logs:

  • WARN, inside the KMS span: a GCP or Vault Transit response without a key version;
  • WARN, when a Vault Transit provider is created: an http address to another host, or a system CA certificate that cannot be loaded;
  • WARN, on the kms_aead::json target: a JsonEncoded value that does not decode, see JSON that does not decode;
  • INFO, when a provider that holds the public key of an asymmetric KEK is created (PublicKeyKekProvider, AsymmetricKekProvider and LocalAsymmetricKmsProvider): the KEK, its version and the public key’s fingerprint, the SHA-256 of its SubjectPublicKeyInfo in hex, so that an operator compares the producer’s and the administration’s;
  • INFO, when a local KMS provider is created: its KEK id and versions, each with where it came from, in the key and kek_versions fields;
  • INFO, when a local signing provider is created: its key id and versions, each with its algorithm, key id and where it came from, in the key and key_versions fields.

The library retries nothing itself, so there is no retry field.

JSON that does not decode

A JsonEncoded value whose bytes are not the JSON of its type, a decrypted plaintext or the payload of an attached signature or MAC after it verified, fails with INVALID_PLAINTEXT or INVALID_PAYLOAD. The error never quotes the bytes, and names serde_json’s category of failure (Syntax, Data or Eof) without the line and column, which are byte offsets that give away the length of the values before them. The library logs one WARN event on the kms_aead::json target beside it, with an outline of the JSON.

FieldValue
error_codeINVALID_PLAINTEXT or INVALID_PAYLOAD
decoded_typethe Rust type the JSON does not decode to
payload_typethe PAYLOAD_TYPE of a signed type; unrecorded for a plaintext
json_errorserde_json’s error: the message of a syntax error, such as EOF while parsing a string, or Data error for JSON of another shape than the type, with the line and column under SIZES
outlinethe outline of the JSON

By default the outline shows the shape of the JSON: the type of every value, <key> for every key, the nesting, and where serde_json stopped reading it, with serde_json’s message for a syntax error. That message can state a property of a value the outline hides, and the default shows no length and no position, see What is never logged.

A type opts into more with a policy, the second type parameter of JsonEncoded. A signed payload is often public, so its policy may show more than an encrypted plaintext’s. See JSON that does not decode for a policy and the outlines it produces. kms_aead::json=off in an EnvFilter turns the event off.

An application outlines JSON of its own with RedactedJson, with no encryption involved, see Log a webhook payload that failed to parse.

Keyring spans

The kms-aead-keyring crate follows the same rules: one DEBUG span per call, field names with the /kms_aead_keyring/ prefix, and nothing recorded for a value nobody reported. kms-aead’s spans nest inside them, so a KMS decrypt DEK under a Keyring decrypt is a DEK cache miss, and a KMS encrypt DEK under a Keyring rotate is the new version’s DEK. Enable kms_aead_keyring=debug in the filter beside kms_aead=debug. The spans from Keyring rotate to Keyring export are those of KeyringAdmin calls, under the admin feature.

SpanOpened byFields
Keyring encryptan encryptor’s encrypt and encrypt_deterministic, deterministic_probes, and stream_encryptorkeyring, purpose, key_id, algorithm, backend, dek_cache, error_code
Keyring decryptdecrypt, decrypt_with_trust, their deterministic pair, decrypt_envelope_for_migration, and stream_decryptorkeyring, purpose, key_id, key_state, reload, dek_cache, error_code
Keyring loadevery store read: open, a revalidation, a reload, the read before a write of a KeyringAdmin, including a dangerously_shredkeyring, store, reason, changed, revision, response_time, error_code
Keyring beaconan encryptor’s beacon, beacon_probeskeyring, key_id, algorithm, dek_cache, error_code
Keyring macan encryptor’s mac and mac_attachedkeyring, key_id, algorithm, dek_cache, error_code
Keyring verify macverify_mac, verify_mac_with_trust and verify_with_mackeyring, purpose, key_id, key_state, reload, dek_cache, error_code
Keyring rotaterotate, change_algorithmkeyring, purpose, to_key_id, cas_retries, error_code
Keyring promotepromotekeyring, key_id, from_key_id, to_key_id, cas_retries, error_code
Keyring mark compromisedmark_compromisedkeyring, key_id, to_key_id, cas_retries, error_code
Keyring retire, Keyring reinstate, Keyring destroythe call of that namekeyring, key_id, cas_retries, error_code
Keyring destroy all versionsdangerously_destroy_all_versionskeyring, cas_retries, error_code
Keyring shreddangerously_shredkeyring, cas_retries, error_code
Keyring re-encrypt DEKsreencrypt_dekskeyring, versions, dek_cache, cas_retries, error_code
Keyring exportexport_bigquery_keyset, export_tink_keysetkeyring, purpose, versions, dek_cache, error_code
Keyring sign recordeach write of a signed record by the administrationkeyring, key_id, error_code
Keyring sweepsweep::reencrypt_records, sweep::reencrypt_records_batchedkeyring, scanned, reencrypted, reencrypted_from_compromised, skipped, failed
FieldValue
keyringthe keyring id, which can name a tenant
purposerandomized, deterministic, beacon or mac
key_idthe decimal key id; unrecorded for an envelope value, which names no version, and for deterministic_probes and beacon_probes, which run under several
algorithmthe version’s algorithm, such as aes-256-gcm, hmac-sha256 or mac-hmac-sha256; unrecorded for deterministic_probes and beacon_probes
backendring, aws-lc or rustcrypto; unrecorded for deterministic calls, since AES-SIV runs on RustCrypto whatever the keyring’s backend
key_statepending, active, decrypt_only, retired, destroyed, compromised, or unknown for a key id the record does not have
reloadwhat an unknown key id caused: none, reloaded or rate_limited
dek_cachehit, miss or disabled; bypassed for reencrypt_deks, the export, and a compromised version read past the cache; unrecorded for deterministic_probes and beacon_probes
storememory, firestore, postgres, gcs, s3, or an application store’s name
reasonopen, ttl, watch, unknown_key_id, pending_key_id for a re-encryption under a version the cached record holds as pending, forced for Keyring::reload, export for the read a keyset export selects its versions from, admin for the read before a write
changedtrue for a new record taken, false, regressed for one refused because it moves a version backwards, refused for one refused by record verification, or deleted for a read that found the store holds no record, which the process takes as a shredded keyring
revisionthe store’s revision of the record read, as text
response_timemilliseconds the store call took
from_key_id, to_key_idthe version a promotion or a compromise replaced, and the new active one; for rotate, to_key_id is the staged version
cas_retriesthe compare-and-swap conflicts before the write landed
versionsthe versions reencrypt_deks encrypted again, or an export put in the keyset
scanned, reencrypted, reencrypted_from_compromised, skipped, failedthe counts of the SweepReport
error_codeKeyringError::code() of the error returned: kms-aead’s code for a KMS or AEAD error, such as DECRYPT, and the variant’s name in upper snake case otherwise, such as KEY_VERSION_COMPROMISED

Keyring events

  • WARN: a read of a compromised version under the Allow policy, with the key id;
  • WARN: a read refused because its version is retired or destroyed, for an operator watching a sweep;
  • WARN: a record that holds a DEK encrypted with a public key, loaded under any record verification mode but Required, with the keyring id, once per record loaded. Under an asymmetric KEK anyone holding the public key can plant a version, see Keyrings under an asymmetric KEK;
  • WARN: a KeyringAdmin without a record signer built over a provider whose encrypts_with_public_key() is true;
  • WARN: a failed revalidation, “The keyring record could not be revalidated; the cached record stays in use”. The process misses every change until the store answers again, so alert on it;
  • WARN: “The keyring store no longer holds the keyring record; every version is destroyed in this process”, when a read finds the record gone: the process then holds the record with every version destroyed and stops revalidating the keyring, see A record gone from the store. It is an INFO, “The keyring store no longer holds the keyring record of a shredded keyring; every version is destroyed in this process”, when the record the process held had every version destroyed already, which a shred leaves before it deletes the record. The process that ran the shred logs nothing for it;
  • ERROR: a refreshed record refused because it moves a version backwards, with the first rule it breaks. Alert on it: it is the detection of a rewritten or restored record;
  • ERROR: a refreshed record refused by record verification, with its code, RECORD_UNSIGNED, RECORD_SIGNATURE_INVALID or RECORD_SIGNATURE_REMOVED; the process keeps the record it holds, and the Keyring load span records the code. Alert on it as on the previous one;
  • WARN: a compromised flag written without a rotation because the new DEK could not be encrypted;
  • INFO: the active version of a purpose changed, with the old and new key ids;
  • WARN: the store’s listener disconnected, reconnected, or did not start, and a keyring opened with no tokio runtime to follow the store’s signals;
  • WARN: a KeyringRegistry dropped while its background tasks run, which aborts them, with the count of open keyrings, and a shutdown whose timeout aborted the tasks still running, with their count;
  • WARN: a record a sweep could not re-encrypt, with the Display of the application’s candidate in record and of its error in error. Both are the application’s own text, so it keeps values, secrets and personal data out of them. A record id is often an entity id, so the sweep’s log is an administrative log;
  • WARN: a candidate the sweep’s stream returned as an error, with the Display of the error in error;
  • WARN: a batch of sweep::reencrypt_records_batched whose re-encryption failed as a whole, with its number of candidates in candidates and the Display of the error in error, and a batch that returned a different number of outcomes from it was given candidates, with both counts in candidates and outcomes;
  • DEBUG: a rate-limited reload for an unknown key id, and a compare-and-swap conflict that is retried.

The keyring’s spans, events and errors leave out everything kms-aead’s do, see What is never logged. The AAD rule matters most there, since the default AAD holds the entity id: neither the AAD nor an EntityId appears anywhere. Key ids, keyring ids and store names are identifiers and appear.

Metrics

This page covers the OpenTelemetry instruments of both crates, their attributes and the views that bound their cost. Read it when you build dashboards or alerts on the library’s metrics.

With the opentelemetry feature, kms-aead records OpenTelemetry metrics for every envelope call and KMS request. kms-aead-keyring’s opentelemetry feature turns it on, and the keyring records into the same instruments, with its own attributes. Both depend on the opentelemetry API crate only (no SDK): the application installs the SDK and an exporter, such as OTLP with opentelemetry-otlp or Prometheus with opentelemetry-prometheus. Without the feature neither crate depends on OpenTelemetry.

The instruments come from the global meter provider, with an instrumentation scope named after kms-aead and its version, the first time either crate records, and stay bound to it for the life of the process. Install the provider before the first KMS, envelope or keyring call, otherwise the instruments record nothing:

use opentelemetry::Key;
use opentelemetry_sdk::metrics::exporter::PushMetricExporter;
use opentelemetry_sdk::metrics::{Aggregation, Instrument, SdkMeterProvider, Stream};

fn install_meter_provider(exporter: impl PushMetricExporter) -> SdkMeterProvider {
    let provider = SdkMeterProvider::builder()
        .with_periodic_exporter(exporter)
        // The plaintext size without its smallest and largest value, see below.
        .with_view(|instrument: &Instrument| {
            if instrument.name() != "kms_aead.plaintext.size" {
                return None;
            }
            Stream::builder()
                .with_aggregation(Aggregation::ExplicitBucketHistogram {
                    boundaries: Vec::new(),
                    record_min_max: false,
                })
                .build()
                .ok()
        })
        // Optional: the durations without `kms_aead.keyring`, see below.
        .with_view(|instrument: &Instrument| {
            let kept: &[&'static str] = match instrument.name() {
                "kms_aead.operation.duration" => &[
                    "kms_aead.operation",
                    "kms_aead.mode",
                    "kms_aead.algorithm",
                    "kms_aead.backend",
                    "kms_aead.purpose",
                    "error.type",
                ],
                "kms_aead.store.duration" => &["kms_aead.store", "kms_aead.reason", "error.type"],
                _ => return None,
            };
            Stream::builder()
                .with_allowed_attribute_keys(kept.iter().map(|key| Key::from_static_str(key)))
                .build()
                .ok()
        })
        .build();
    opentelemetry::global::set_meter_provider(provider.clone());
    provider
}
let provider = install_meter_provider(opentelemetry_sdk::metrics::InMemoryMetricExporter::default());
provider.shutdown().unwrap();

The names follow OpenTelemetry’s semantic conventions: the library’s own attributes have the kms_aead. prefix, and a failed call carries error.type, the code of its error. A successful call has no error.type.

InstrumentTypeUnitAttributesKeyring calls add
kms_aead.plaintext.sizehistogram, no bucketsBykms_aead.operation, kms_aead.mode, kms_aead.algorithm, kms_aead.backendkms_aead.keyring, kms_aead.purpose, kms_aead.key_id
kms_aead.operation.durationhistogramskms_aead.operation, kms_aead.mode, kms_aead.algorithm, kms_aead.backend, error.typekms_aead.keyring, kms_aead.purpose
kms_aead.kms.durationhistogramskms_aead.provider, kms_aead.operation, error.type
kms_aead.store.durationhistogramskms_aead.keyring, kms_aead.store, kms_aead.reason, error.type
kms_aead.record.refusalscounter{record}kms_aead.keyring, error.type

The values of the attributes that name the call:

AttributeValueRecorded for
kms_aead.operation on the value instrumentsencrypt, decrypta value’s encryption or decryption
beaconan envelope’s beacon
generate_dekgenerate_encrypted_dek and generate_encrypted_deterministic_dek
decrypt_dekdecrypt_deterministic_dek
reencrypt_dekreencrypt_dek and reencrypt_encrypted_dek
stream_encrypt, stream_decryptthe stream calls
sign, verify, mac, verify_maca Signer, a Verifier and an Authenticator
kms_aead.operation on kms_aead.kms.durationencrypt_dek, decrypt_dek, random, sign, public_key, encrypt_dek_with_public_keythe request to the KMS, or the local encryption with a public key
kms_aead.modeper_call, store_lessan envelope’s encrypt, decrypt, the stream calls and reencrypt_dek
caller_dekthe *_with_dek and *_with_encrypted_dek calls, beacon, the calls that generate or decrypt a DEK, reencrypt_encrypted_dek, and an Authenticator’s mac and verify_mac
signaturea Signer and a Verifier
keyringa keyring’s calls
  • kms_aead.plaintext.size records the plaintext length of each value encrypted or decrypted: its count is the values, and its sum their bytes. It has no buckets. The SDK also keeps the smallest and the largest value of each series and OTLP exports them, unless a view turns them off as above. A failed call records no value;
  • kms_aead.algorithm and kms_aead.backend are those of the span. kms_aead.algorithm is absent where it is unknown: on a re-encryption, in which the algorithm plays no part, on a probe, which runs under every version, and on a keyring call that fails before it finds its version. A keyring’s deterministic call has kms_aead.backend rustcrypto, since AES-SIV runs on RustCrypto whatever the keyring’s backend;
  • a keyring call is recorded once, with kms_aead.mode keyring: it runs kms-aead’s ciphers, never its envelope, see the table of values above. encrypt is an encryptor’s encrypt and encrypt_deterministic, decrypt is decrypt, decrypt_with_trust and their deterministic pair, reencrypt is reencrypt and reencrypt_deterministic, which also record the decrypt and encrypt they make, beacon is an encryptor’s beacon, and probe is beacon_probes and deterministic_probes. decrypt_envelope_for_migration is a decrypt with no kms_aead.purpose. kms_aead.key_id is the version’s key id, as a number;
  • probes and beacons record no value. A probe is never stored, and a beacon is an HMAC-SHA256 output: HMAC takes no nonce, and its bound as a PRF is far beyond the values one key can encrypt. Signatures and MACs record no value either. A keyring’s MAC calls add no keyring call of their own: the Authenticator they run records each one;
  • kms_aead.kms.duration covers the request to the KMS only, as the span’s response_time does. encrypt_dek_with_public_key is an encryption with the public key of an asymmetric KEK, which is a local operation and no KMS request, so that the duration tells the two apart. kms_aead.provider is the span’s provider. The KEK name is left out;
  • kms_aead.store.duration covers every read of a keyring record, with the store and reason of the Keyring load span;
  • the stream calls of an envelope, stream_encryptor, stream_decryptor and their bare forms, and a keyring’s stream_encryptor and stream_decryptor are recorded in kms_aead.operation.duration with kms_aead.operation stream_encrypt and stream_decrypt. The plaintext size instrument records nothing for them, since the size is not known at the call. AeadCipher’s stream calls open no span;
  • kms_aead.record.refusals counts each keyring record a process refused because of its signature, by code in error.type: RECORD_UNSIGNED, RECORD_SIGNATURE_INVALID or RECORD_SIGNATURE_REMOVED. It is the metric of the ERROR event for a record refused by record verification, see Keyring events.

No attribute names a DEK, so the envelope’s values are recorded per algorithm, not per key. A store-less envelope needs no alert on them: it renews its DEK at max_uses and max_bytes, see Volume limit.

A Prometheus exporter adds the unit to the name and replaces the dots with underscores: kms_aead_plaintext_size_bytes_count and kms_aead_plaintext_size_bytes_sum, kms_aead_operation_duration_seconds, and attributes such as kms_aead_key_id. For an alert on the values and bytes under one keyring version, see Alerting on volume.

The keyring’s plaintext size has one time series per keyring, purpose, key version and operation. With a keyring per tenant, that is a series per tenant and version. Under cumulative temporality, the default, the SDK keeps a series until the process restarts, also once its version is no longer used. The SDK keeps a limited number of attribute sets per instrument, 2000 by default, and records every further one into one series with the attribute otel.metric.overflow, with no error: an alert per version stops counting the versions past the limit. Check the limit of your SDK version, and raise it with Stream::builder().with_cardinality_limit in a view where the keyrings and their versions come near it. Key ids are numbered per keyring, so the plaintext size keeps kms_aead.keyring: without it, version 1 of every keyring would add up to one series. The duration histograms do not need it, and with their buckets they cost the most series, so the view above drops it from them. The view’s with_allowed_attribute_keys needs the SDK’s spec_unstable_metrics_views feature.

Security considerations

This page defines the threat model, the nonce and data volume bounds, key lifetime and zeroisation, what rotation does not protect, the assumptions of a keyring deployment and where to report a vulnerability. Read it when you review a deployment or decide which controls to rely on; the permissions of a deployment are in Permissions: applications and administration.

Threat model

Envelope encryption protects stored values from whoever can read the store but cannot use the KEK: a database dump, a backup, a replica, a data export or an operator with read access to the tables. Decrypting a value needs a KMS decryption, and the KMS checks the caller’s permission and, for the cloud KMSs, writes an audit log entry.

It does not protect values from:

  • a process, or whoever controls it, that may decrypt with the KEK: it can read every value it can fetch;
  • whoever can read the memory of a process while it holds plaintext DEKs, in the DEK cache or as a store-less writer’s DEK;
  • a reader of the store learning which values are equal, for values encrypted with deterministic encryption;
  • a reader of the store learning the length of each plaintext, since a stored value is as long as its plaintext plus a fixed overhead, see Plaintext.

The AAD protects a value from being moved: a value copied into another row or column, with an AAD that names its place, fails to decrypt there. The AAD itself is not encrypted, and neither is the length of the encrypted DEK at the start of Tink’s KMS envelope, which is not authenticated either.

An encrypted DEK carries no context that the KMS authenticates. Whoever can write where encrypted DEKs are stored, such as a database table or a keyring store, can copy an encrypted DEK to another record or relabel it, and the KMS decrypts it for any principal allowed to decrypt with that KEK. The controls for this are in the deployment:

  • write access to the stored keys is kept apart from the right to decrypt with the KEK;
  • each isolation boundary, such as a tenant or an environment, has a KEK of its own, so a DEK copied across it fails to decrypt;
  • the KMS audit log of decrypt calls, turned on where the KMS leaves it off by default, shows which principal decrypted which key.

A DEK encrypted with the public half of an asymmetric KEK leaves no KMS audit log entry; the decrypt log and the record’s signature are the controls, see Asymmetric KEKs.

The local KMS has no IAM, no audit log and no HSM, see its limits.

Nonces

Every AEAD algorithm takes a random 96-bit nonce from the backend’s CSPRNG for each value, and writes it in front of the cipher text. NIST SP 800-38D allows 2^32 encryptions under one key with random 96-bit nonces, and the library applies the same bound to every algorithm:

  • the per-call envelope encrypts one value per DEK, so the bound does not apply to it;
  • a store-less envelope renews its DEK at max_uses, at most 2^32, see Volume limit;
  • with encrypt_with_dek and AeadCipher, the application counts the values it encrypts under one key, and moves to a new key before 2^32;
  • the local KMS encrypts each DEK it encrypts with AES-256-GCM, so a KEK version is good for about 2^32 encryptions. Add a new version before that.

AES-256-GCM-SIV (RFC 8452) resists nonce misuse: a repeated nonce reveals only whether the two values encrypted with it are equal, and does not break integrity.

Deterministic encryption with AES-SIV takes no random nonce.

Data volume

AES-GCM also has a bound on the data under one key, whatever the nonces. The bounds per algorithm, and the sources below the table:

AlgorithmValues under one keyData under one key
AES-GCM2^32 with random 96-bit nonces2^38.5 bytes (RFC 8446), at most 2^52 bytes (RFC 8452)
AES-GCM-SIV2^32 values of up to 8 GiB eachno bound beyond the number of values
ChaCha20-Poly13052^32, the library’s bound for every algorithmno confidentiality limit beyond ChaCha20 itself
  • AES-GCM: RFC 8446, section 5.5, allows “up to 2^24.5 full-size records (about 24 million)” of 2^14 bytes, 2^38.5 bytes, “while keeping a safety margin of approximately 2^-57 for Authenticated Encryption (AE) security”. Luykx and Paterson, “Limits on Authenticated Encryption Use in TLS”, table 1, give the same 2^24.5 records for a confidentiality advantage of 2^-60. RFC 8452, section 9, allows 2^48 blocks, 2^52 bytes, under one AES-GCM key for an advantage of 2^-32;
  • AES-GCM-SIV: RFC 8452, section 9, allows 2^32 values of up to 8 GiB each under one key with random nonces for an advantage of 2^-32, so the bound on the number of values bounds it already;
  • ChaCha20-Poly1305: draft-irtf-cfrg-aead-limits, section 6.3, gives it no confidentiality limit beyond the security of ChaCha20 itself, and its integrity bound depends on the number of forgery attempts, which no writer can count.

The bound applies to AES-GCM keys this way:

  • a store-less envelope renews its DEK at max_bytes, which defaults below the 2^38.5 of RFC 8446 under AES-GCM and is at most 2^52, see Volume limit. AES-256-GCM-SIV and ChaCha20-Poly1305 have no default volume limit;
  • with encrypt_with_dek and AeadCipher, the application counts the bytes it encrypts under one AES-GCM key too, and moves to a new key before 2^38 bytes.

Key lifetime and zeroisation

DataEncryptionKey, LocalKek and the Vault token are zeroised on drop and shown as *** by Debug. The DEK cache zeroises a key when its entry leaves the cache and no with_dek closure holds it.

Some copies are out of the library’s reach:

  • the KMS SDKs and HTTP clients the providers use keep copies of each plaintext DEK in request and response buffers, which kms-aead cannot zeroise. The same holds for the Vault token in the HTTP stack;
  • the copies of a key inside a crypto backend: what each backend clears is in its section of Crypto backends: ring, aws-lc-rs and RustCrypto;
  • an expired DEK stays in the cache’s memory until the next call on the cache or purge_expired;
  • decrypt returns the application’s own T: Plaintext. Only SecretValue as T is zeroised on drop; String and Vec<u8> take over the decrypted buffer and leave it in freed memory, and what the application does with the value afterwards is its own.

What rotation does not protect

Rotating the KEK in the KMS makes the KMS encrypt new DEKs under the new key version. It does not:

  • re-encrypt the DEKs already stored: they still decrypt with the old key version, which the KMS must keep enabled for as long as those values are read;
  • re-encrypt any value: a DEK that leaked keeps decrypting every value encrypted under it, whatever the KEK version that encrypts it. To retire a leaked DEK, decrypt and encrypt the values again under new DEKs;
  • reach DEKs already in a DEK cache: they keep serving until their entries expire, or until invalidate or clear. The same holds for disabling a KMS key or revoking an IAM grant;
  • renew a store-less writer’s DEK: it is renewed by its policy, or once it leaves the cache.

With the local KMS, rotation is a new KEK version. The old version has to stay in the provider for as long as DEKs encrypted under it are read, and crypto-shredding means destroying every copy of it, backups included.

Keyring deployment

A keyring record decides which versions are read and which one encrypts new values, and the administration signs it where record signing is on, see Signing the keyring record; without it, its integrity rests on the keyring store’s access control. The two principals of a deployment and their rights are in Permissions: applications and administration.

A writer of the keyring store can copy or relabel an encrypted DEK, between versions of one keyring or between keyrings under the same KEK: the KMS decrypts an encrypted DEK for any principal allowed to decrypt with the KEK, whatever version or keyring it is filed under. Such a writer can bring a compromised or destroyed version’s DEK back into use under a new key id, or point one tenant’s version at another tenant’s DEK. Under a symmetric KEK, a writer without KMS rights cannot add a DEK of its own, since every decryption names the configured KEK and the KMS refuses a DEK encrypted under another key; an asymmetric KEK encrypts for anyone holding its public key, see Keyring limits. The controls for this are the deployment’s, as in the threat model:

  • write access to the keyring store for the administration only, and read-only access for the applications;
  • one KEK per isolation boundary, such as a tenant or an environment, so a DEK copied across it fails to decrypt;
  • backups of the record, or versioning in the store, to compare with and restore from;
  • the KMS audit log of encrypt calls, which shows whether the administrative job encrypted a version’s DEK. An asymmetric KEK’s encryption is local and leaves none: the signature on the record and the KMS log of the signing call take its place.

A running process also refuses every record that moves a version backwards, with an ERROR, see Record cache. That catches a rewritten state, such as a cleared compromised flag, and not a copied DEK filed under a new version.

Keyring limits

  • The administration is trusted. KMS encrypt plus store write re-activates any version, and so does an application that provisions keyrings lazily with the admin feature and those rights. With record signing on, the right to sign records plus store write does. The KMS audit log is the detection;
  • a new process has no baseline. A store writer can clear a compromised flag, re-activate a version or restore a destroyed one for the processes that start after the write. Running processes refuse such a record and log an ERROR, also a process that took the record’s deletion, which keeps the deleted record as the baseline. A signed record read under Required refuses such a write; under VerifyIfSigned a running process refuses it and a new process has no baseline. A signature proves the record was written by a signer, not that it is the latest: a store writer can restore an older signed record;
  • an asymmetric KEK encrypts for anyone holding its public key, an RSA key on Azure Key Vault included: whoever holds it encrypts a DEK of their own into the record. A signed record under RecordSignaturePolicy::Required is the control, see Keyrings under an asymmetric KEK;
  • decrypt_envelope_for_migration knows no key version. It decrypts the encrypted DEK an envelope value carries, so an encrypted DEK kept from a version, compromised or destroyed since, still decrypts values through it. Keep it in the read path for the migration only;
  • a destroyed version’s DEK lives as long as the KEK version that encrypted it. A backup of the record holds encrypted DEKs the KMS still decrypts, and a keyset exported before the destroy holds the version’s key under the same KEK, see What survives a shred;
  • dangerously_shred() reaches the store’s API only. It deletes the record with the earlier versions the store keeps, and never calls the KMS. A copy the store keeps beyond its API, such as a backup, and every BigQuery and Tink keyset exported from the keyring, still decrypts while a KEK version that encrypted its DEKs exists: delete the copies, or rotate the KEK, re-encrypt every other keyring under it and destroy the previous KEK versions. See What a delete removes for each store’s copies;
  • a running process keeps the deleted record as the baseline of its id. A store writer who deletes the record and writes another under the id gains nothing against it: an unsigned record under VerifyIfSigned fails with RecordSignatureRemoved, and a copy of the record from before the deletion fails with RecordRegressed and an ERROR. The baseline lasts until the process restarts, and a new process has no baseline, so Required is the control for it, see A record gone from the store;
  • an exported BigQuery keyset holds the versions’ keys, encrypted with no associated data, since BigQuery decrypts it with none. Treat it as a copy of the record’s readable versions, and export again after every rotation and every mark_compromised;
  • a sweep re-encrypts forgeries as trusted values. Values read through a compromised version are decided per record before a sweep re-encrypts them, see The trust of re-encrypted values;
  • deterministic fields leak equality and frequency, and an equality query across a rotation links a value’s history for whoever reads the query, see Queries across rotations;
  • beacons leak likely equality and frequency, as far as their bits tell values apart, see What a beacon leaks;
  • a promotion’s guard covers healthy processes only. promote refuses until record_ttl has passed since the rotation, and promote_now skips that. A process whose revalidations fail keeps an older record for longer: when it meets a value under a version it has not seen, it reloads its record, and fails the read when it cannot reach the store. So the wait beyond the record TTL is the operator’s, see Staged rotation.

Supply chain

kms-aead and kms-aead-keyring read sensitive data, so manage them and their dependencies with the procedures you use for commercial products. Pin versions in a lockfile, and audit the changes of an upgrade before you take it: a broad version requirement pulls in a new release of a dependency without that audit.

Reporting a vulnerability

See SECURITY.md.

Migrating from 0.30

0.31 adds streaming encryption, signatures and MACs, record signing for keyrings, asymmetric KEKs and the deletion of a keyring’s record. Move the readers of a deployment to 0.31 before its producers, see Readers before producers. Apply this guide after Migrating from 0.29 if the deployment is older than 0.30.

Eight changes break a build against 0.30:

One behaviour changes without breaking a build: a running process takes a keyring record gone from the store as shredded.

Everything else is additive, see New in 0.31.

The unsupported algorithm error

KmsAeadUnsupportedAlgorithmError::algorithm is a BackendAlgorithm in 0.31, an AeadAlgorithm in 0.30, so that the one error names whichever algorithm a backend lacks: an AEAD algorithm, as AES-256-GCM-SIV on ring, or an asymmetric KEK algorithm, as RSA-OAEP (RSA encryption with OAEP padding) on ring. The variant, KmsAeadError::UnsupportedAlgorithm, and its code, UNSUPPORTED_ALGORITHM, do not change.

0.300.31
error.algorithm == AeadAlgorithm::Aes256GcmSiverror.algorithm == BackendAlgorithm::Aead(AeadAlgorithm::Aes256GcmSiv)
let algorithm: AeadAlgorithm = error.algorithm;let BackendAlgorithm::Aead(algorithm) = error.algorithm else { … };
error.algorithm.key_len()match error.algorithm { BackendAlgorithm::Aead(algorithm) => algorithm.key_len(), _ => … }

BackendAlgorithm is #[non_exhaustive], so a match on it needs a _ arm, and it implements From<AeadAlgorithm> and From<AsymmetricKekAlgorithm>. Its Display is the inner algorithm’s name, so a log line that printed error.algorithm prints the same text.

Purpose and KeyAlgorithm

Purpose and KeyAlgorithm of kms-aead-keyring gain the Mac variant for the MAC versions of a keyring, a MAC being a keyed tag that proves the bytes it covers are unchanged, see MACs in a keyring. Both are #[non_exhaustive] from 0.31, so an exhaustive match on either needs a _ arm: a breaking change for every such match, made once so that a later purpose is additive.

0.300.31
match purpose { Purpose::Randomized => …, Purpose::Deterministic => …, Purpose::Beacon => … }the same arms and _ => …, or Purpose::Mac => …
match algorithm { KeyAlgorithm::Randomized(_) => …, KeyAlgorithm::Deterministic(_) => …, KeyAlgorithm::Beacon(_) => … }the same arms and _ => …, or KeyAlgorithm::Mac(_) => …

Loading a local KEK

LocalKek::from_secret, from_file and from_env take a SymmetricKeyFormat as their last argument: pass SymmetricKeyFormat::Raw where 0.30 took raw bytes (from_secret) and SymmetricKeyFormat::Base64 where it read base64 (from_file, from_env). The methods keep their names, so the old signatures cannot stay as deprecated wrappers, and every call site fails to compile until it names a format.

0.300.31
LocalKek::from_secret(version, material)LocalKek::from_secret(version, material, SymmetricKeyFormat::Raw)
LocalKek::from_file(version, &path)LocalKek::from_file(version, &path, SymmetricKeyFormat::Base64)
LocalKek::from_env(version, "APP_DEV_KEK")LocalKek::from_env(version, "APP_DEV_KEK", SymmetricKeyFormat::Base64)

SymmetricKeyFormat is in kms_aead::formats and is #[non_exhaustive]. Raw is the key bytes themselves, Base64 the standard base64 of the key bytes, trailing whitespace allowed, and Jwk an oct JSON Web Key. The key is 32 bytes in every format. from_file reads a file of up to 32 KiB, where 0.30 read up to 256 bytes. The loaders of the signing and asymmetric KEK keys take the same kind of enum, see Key formats.

The serde features

The serde and serde-json features of kms-aead and of kms-aead-keyring are removed: serde support, JsonEncoded<T> and JWK are in every build of both. Delete the two features from the dependency on each crate in your Cargo.toml; Cargo refuses an unknown feature.

The Firestore features

The firestore feature of 0.30 is firestore-tls-roots in 0.31. In 0.31 firestore is the Firestore keyring store on firestore-rs without its default features, so it has no TLS root store and no crypto provider, as gcs has none. A build that names firestore therefore enables a firestore-rs or gcloud-sdk root store feature of its own, or one of the two features that do:

  • firestore-tls-roots: the system’s native roots, firestore-rs’s tls-roots, which brings native-tls and so OpenSSL on Linux;
  • firestore-tls-webpki: rustls, with the bundled WebPKI roots for the gRPC connection to Firestore, and no native TLS;

each with firestore-rs’s auth-default-crypto. The Cloud Storage features are split the same way: gcs, gcs-tls-roots and gcs-tls-webpki.

0.300.31
features = ["firestore"]features = ["firestore-tls-roots"], the same build as 0.30
no equivalentfeatures = ["firestore-tls-webpki"], for a build without OpenSSL

The rustcrypto feature adds rsa

The rustcrypto feature adds the rsa crate for RSA-OAEP, so every application that enables it carries rsa in its lockfile. The feature also adds p256 and ed25519-dalek, for signatures. kms-aead depends on serde, serde_bytes, serde_json, sha2, base64ct, der, spki, pkcs8, sec1 and pem-rfc7468 in every build, for serde support, the key framing, JSON Web Keys and the thumbprints of public keys, and kms-aead-keyring on sha2, for the canonical digest of a record.

The aws features read aws login sessions

The features that enable AWS KMS turn on aws-config’s credentials-login, so that the default credentials chain takes the session of aws login, as the AWS CLI does.

Readers before producers

The encrypted DEK a public key encrypts is a layout of 0.31, which starts with 0x02, and no earlier release reads it, see DEKs encrypted with a public key. A deployment moves every reader, every application and administrative job that decrypts, to 0.31 before the first producer encrypts with a public key, as every reader moved to 0.30 before the first value in Tink’s envelope format, see Upgrading stored values. Nothing already stored changes: the encrypted DEKs the KMS encrypted keep their bytes and keep decrypting.

A keyring record gains a signature member, which 0.30 reads and ignores, and which a 0.30 administrative write removes, since 0.30 rewrites the record from its own fields: move every administrative binary to 0.31 before the first record is signed. A keyring’s first MAC version is created only once every process reads the keyring on 0.31, see MACs in a keyring.

Run a keyring under an asymmetric KEK with RecordSignaturePolicy::Required on every application: anyone holding the public key can file a DEK of their own in its record, and under VerifyIfSigned a store writer who holds it plants a version for every process that starts afterwards, see Keyrings under an asymmetric KEK. An existing Azure Key Vault or Vault Transit RSA deployment moves its encryptions to the producer in the order of Migrating an Azure or Transit RSA deployment.

In 0.31 a store-less writer whose renewed DEK leaves the DEK cache before it encrypts uses the DEK it generated, in place of decrypting its encrypted DEK again. A store-less encrypt makes no KMS decryption under any provider, see The DEK lives in the cache.

Names

0.31 uses one vocabulary: encrypt and decrypt for every confidentiality operation, and “open” only for opening a keyring. The keyring’s write handle, its re-encryption of a value under the active version, and the sweep’s encryption marker, the 5 bytes a record stores beside its encrypted fields to name the key versions they are under, take the new words. KekProvider and KekVersion take names that say they belong to any key of a KMS. No old name stays as an alias: a build that uses one fails until it uses the new one.

Area0.300.31
KMS nameskms_aead::KekProviderkms_aead::KmsProvider
kms_aead::providers::KekVersionkms_aead::providers::KmsKeyVersion
Keyring writesSealerEncryptor
Keyring::sealer()Keyring::encryptor()
Sealer::resealEncryptor::reencrypt
Sealer::reseal_deterministicEncryptor::reencrypt_deterministic
Resealed<T, F>Reencrypted<T, F>
Sweepssweep::SealMarkersweep::EncryptionMarker
sweep::runsweep::reencrypt_records
sweep::run_batchedsweep::reencrypt_records_batched
sweep::SealRangesweep::ReencryptRange
sweep::ResealOutcome, ResealOutcome::Resealedsweep::ReencryptOutcome, ReencryptOutcome::Reencrypted
SweepReport::resealed, SweepReport::resealed_from_compromisedSweepReport::reencrypted, SweepReport::reencrypted_from_compromised
KeyringRecord::seal_markerKeyringRecord::encryption_marker
KeyVersion::seal_rangeKeyVersion::reencrypt_range
EncryptedKeyset::seal_markerEncryptedKeyset::encryption_marker
Plaintextskms_aead::Json<T>, behind the serde-json featurekms_aead::JsonEncoded<T>, in every build
Json(value)JsonEncoded::new(value)
let Json(value) = json;let value = json.0;
ErrorsKeyringError::SealerOutdated, code SEALER_OUTDATEDKeyringError::EncryptorOutdated, code ENCRYPTOR_OUTDATED
KeyringError::InvalidSealMarker, code INVALID_SEAL_MARKERKeyringError::InvalidEncryptionMarker, code INVALID_ENCRYPTION_MARKER
RecordInvalidReason::SealEpochOutOfRangeRecordInvalidReason::ReencryptEpochOutOfRange
RecordInvalidReason::SealRangeInvalidRecordInvalidReason::ReencryptRangeInvalid
RegressionRule::SealEpochRevertedRegressionRule::ReencryptEpochReverted
RegressionRule::SealRangeRevertedRegressionRule::ReencryptRangeReverted

Nothing stored changes. A keyring record keeps its seal_epoch and seal_epochs keys, and a encryption marker keeps its 5 bytes, 0x01 and the epoch, so records and markers that 0.30 wrote read in 0.31, and the reverse. The book’s sweep examples name the marker column encryption_marker where 0.30’s named it seal; an existing column keeps its name, since the library never reads a column by name. KmsProvider and KmsKeyVersion keep every value, method and Display string: the provider and kek_version span fields keep their values, and a keyring record’s kek.provider reads as before. KekRef and LocalKekVersion keep their names, since they name a key encryption key.

Telemetry

These renames change what a dashboard, a log query or an alert matches:

Signal0.300.31
Keyring sweep span field/kms_aead_keyring/resealed/kms_aead_keyring/reencrypted
Keyring sweep span field/kms_aead_keyring/resealed_from_compromised/kms_aead_keyring/reencrypted_from_compromised
kms_aead.operation of a keyring callresealreencrypt
error.type and the error_code span fieldSEALER_OUTDATED, INVALID_SEAL_MARKERENCRYPTOR_OUTDATED, INVALID_ENCRYPTION_MARKER

The error and log messages use the new words too, so a query on the text of a message, such as the WARN of a sweep that could not re-encrypt a record, needs the new text.

Your own provider

The provider trait of 0.30 is two traits in 0.31, so that a provider that only encrypts, such as the PublicKeyKekProvider of a producer, has no decryption, and an envelope over it has no call that decrypts:

  • KmsAeadEncryptionProvider keeps kek, encrypt_data_encryption_key and generate_key_material, and gains encrypts_with_public_key, with a default of false;
  • KmsAeadDecryptionProvider, whose supertrait is KmsAeadEncryptionProvider, holds decrypt_data_encryption_key, with the signature of 0.30.

A provider of 0.30 fails to compile until its decrypt_data_encryption_key moves into an impl of the new trait. A wrapper implements each trait where the provider it wraps does, see the example in Your own provider.

Code generic over a provider names the trait its calls need. KmsAeadDecryptionProvider covers both, so code that encrypts and decrypts names it alone:

0.300.31
P: KmsAeadEncryptionProvider, for an envelope’s decrypt, decrypt_with_dek, *_with_encrypted_dek, beacon, decrypt_deterministic_dek, reencrypt_dek, reencrypt_encrypted_dek or legacy upgradesP: KmsAeadDecryptionProvider
P: KmsAeadEncryptionProvider, for DekCache::with_dekP: KmsAeadDecryptionProvider
P: KmsAeadEncryptionProvider, for a Keyring, a KeyringAdmin, an Encryptor or a KeyringRegistry call that returns oneP: KmsAeadDecryptionProvider
P: KmsAeadEncryptionProvider, for encrypt, encrypt_with_dek and the generate_encrypted_* calls onlyunchanged
use kms_aead::KmsAeadEncryptionProvider, to call decrypt_data_encryption_key on a provideruse kms_aead::KmsAeadDecryptionProvider

A provider that encrypts DEKs with the public half of a key pair returns true from encrypts_with_public_key, so that a keyring refuses the BigQuery and Tink exports its KEK cannot serve, see Producers and readers.

Your own keyring store

KeyringStore gains a fifth method, delete, which has no default: a build that implements the trait for an application’s own store fails until the store implements it.

fn delete(
    &self,
    id: &KeyringId,
    expected: &Self::Revision,
) -> impl Future<Output = KeyringResult<Deletion>> + Send;

It deletes the record when its stored revision is expected, with every earlier version of it the store keeps, such as the noncurrent versions of a versioned bucket:

  • Deletion::Deleted once the store holds no record of the id, also when it held none;
  • Deletion::Conflict when the stored revision is another. The live record stays, though the store may have removed its earlier versions first;
  • errors are returned as load returns them, as KeyringError::Store with StoreOperation::Delete, whose text in the error is delete. A delete that fails may have removed part of the earlier versions already, and the caller repeats it with the same expected;
  • a store with push signals the deletion as a change;
  • the store never gives an id the same revision twice, across a delete too. A revision that restarts at 1 for a record created again would let a process that missed the deletion keep the deleted record.

StoreOperation gains the Delete variant. It is #[non_exhaustive], so a match on it has a _ arm already. What each library store deletes, and what it leaves to the operator, is in What a delete removes.

A keyring record gone from the store

In 0.30 a running process kept a record that went missing from the store in use, with a WARN, and only new processes failed at open. In 0.31 the process takes it as a shredded keyring:

  • it destroys every version of its cached record in memory, and writes nothing. That evicts the keyring’s keys from the DEK cache;
  • it logs a WARN, “The keyring store no longer holds the keyring record; every version is destroyed in this process”, or an INFO when the record it held had every version destroyed already, as a shred leaves it, sets the changed field of the Keyring load span to deleted, and stops revalidating and watching the keyring;
  • its handles then fail before any KMS call: encrypting with NoActiveVersion, reading with KeyVersionDestroyed, reload with RecordMissing;
  • the registry’s next open of the id reads the store again: RecordMissing, or a record created since. A handle opened before stays on the destroyed record.

So an accidental deletion of a record stops a running process at its next revalidation, within reload_min_interval of the signal with push and once the cached record is older than record_ttl without. A record restored from a copy is refused by that process with RecordRegressed, because it revives versions the process holds destroyed, so the process restarts after a restore.

The text of the WARN ended in “the cached record stays in use” in 0.30, so change a log alert that matches that ending. The runbook is The keyring record was deleted or corrupted.

Under record signing, the deleted record stays the baseline of the id: the next record must be signed if the deleted one was, and a keyring created again opens, see Signing the keyring record.

New in 0.31

The other changes are additive. KmsAeadError is already #[non_exhaustive], so its new SignatureError variant needs no change in a match that has a _ arm.

Migrating from 0.29

This guide moves a build from 0.29 to 0.30. To reach a later release, apply the guides after it in order, starting with Migrating from 0.30.

0.30 replaces the ring-only API with a choice of crypto backends, adds store-less DEK reuse, the DEK cache, deterministic encryption and the local KMS, and makes ring optional. It writes the KMS envelope format of Tink, Google’s open-source cryptography library, for every provider. Values written by 0.29 and earlier read only in 0.30 to 0.33, with the deprecated legacy-formats feature, which also rewrites them in the new format, see Old values.

Eight changes break a build against 0.29:

0.30 also adds what 0.29 had no counterpart for, so nothing below maps to it:

  • typed fields: Encrypted<T, F> takes any type that implements Plaintext, such as an application newtype, where the tables below name SecretValue, see Stored values;
  • beacons, for lookups of randomised fields, see Beacons;
  • the kms-aead-keyring crate, with key versions kept in a store, staged rotation and sweeps, see Keyring and field encryption. Envelope values move to it with a sweep, see Move envelope values to a keyring.

Features

0.290.30
ring-aead-encryptionring
a provider feature alone, which turned on ringthe provider feature plus ring, aws-lc, aws-lc-fips or rustcrypto
vault-transit-kms-encryptionhashicorp-vault-transit-kms-encryption
vault-transit-kms-encryption-basehashicorp-vault-transit-kms-encryption-base
vault-transit-kms-encryption-tls-roots, -tls-webpkihashicorp-vault-transit-kms-encryption-tls-roots, -tls-webpki
vault-transit-kms-encryption-tls-aws-lc-rs, -tls-ringhashicorp-vault-transit-kms-encryption-tls-aws-lc-rs, -tls-ring

In 0.30 the provider features do not turn on ring. A 0.29 build that relied on it fails with “kms-aead needs a crypto backend for its KMS providers”, so add a backend feature. aws-lc adds no second crypto library to a cloud provider build, see Choose a provider and a backend.

0.30 declares rust-version = "1.99".

Names

0.290.30
KmsAeadRingEnvelopeEncryption<P>KmsAeadEnvelope<P, Ring>, with the backend as a type parameter
KmsAeadRingEnvelopeEncryption::new(provider).await?KmsAeadEnvelope::<P, Ring>::new(provider)?, not async, on AES-256-GCM rather than ChaCha20-Poly1305, see Default algorithm
KmsAeadRingEnvelopeEncryption::with_algorithm(provider, &ring::aead::AES_256_GCM)KmsAeadEnvelope::<P, Ring>::with_options(provider, KmsAeadEnvelopeOptions::new().with_algorithm(AeadAlgorithm::Aes256Gcm))
with_options, with_algorithm_optionsKmsAeadEnvelope::<P, Ring>::with_options(provider, options)
KmsAeadRingEnvelopeEncryptionOptionsKmsAeadEnvelopeOptions
KmsAeadRingEncryptionProviderKmsAeadEncryptionProvider, see Your own provider
module kms_aead::ring_encryptionremoved; AeadCipher<Ring>, with AeadCipher at the crate root and Ring in kms_aead::backends
RingAeadEncryption::new()AeadCipher::<Ring>::new(AeadAlgorithm::ChaCha20Poly1305)?
RingAeadEncryption::with_algorithm(&ring::aead::AES_256_GCM, rand)AeadCipher::<Ring>::new(AeadAlgorithm::Aes256Gcm)?
RingAeadEncryption::with_rand, with_options, with_algorithm_optionsremoved; the backend owns its CSPRNG (cryptographically secure random number generator), and the random nonce was the only option
RingAeadEncryptionOptions, RingAeadEncryptionNonceKindremoved
RingAeadEncryption.algoAeadCipher::algorithm()
RingAeadEncryption::generate_data_encryption_key()AeadCipher::generate_dek()
kms_aead::kms_envelope_encryption::…the same names at the crate root
CipherText(bytes)Encrypted::<SecretValue, Bare>::try_from(bytes)?, which checks the layout
CipherTextWithEncryptedKey(bytes)Encrypted::<SecretValue, Envelope>::try_from(bytes)?, which checks the layout
CipherTextWithEncryptedKey::new(&cipher_text, &encrypted_dek)Encrypted::<SecretValue, Envelope>::join(&bare, &encrypted_dek)?, in Tink’s KMS envelope format
cipher_text.to_hex_string()value.to_hex_string(), read back with Encrypted::try_from_hex_string
cipher_text == othervalue.value() == other.value()
EncryptedDataEncryptionKey::new(encrypted, key_version)EncryptedDataEncryptionKey::new(bytes): the provider’s bytes, which carry the key version where the KMS needs one; a provider adds the KEK version the KMS reported with with_kek_version
encrypted_dek.wrapped(), to_bytes()?, TryFrom<&[u8]>encrypted_dek.value(), a &[u8], and EncryptedDataEncryptionKey::from(bytes)
encrypted_dek.to_hex_string()?encrypted_dek.to_hex_string(), infallible
encrypted_dek.key_version()encrypted_dek.kek_version(), the KEK version the KMS reported, on an encrypted DEK the provider has just returned or a keyring record holds, and None on one read back from the bytes; the kek_version field of the KMS spans
kms_aead::KmsKeyVersionkms_aead::providers::KekVersion, the type of AzureKmsKeyRef::kek_version
AzureKmsKeyRef::with_key_version, opt_key_version, without_key_version, key_version, mopt_key_version, reset_key_versionAzureKmsKeyRef::with_kek_version, opt_kek_version, without_kek_version, kek_version, mopt_kek_version, reset_kek_version
AzureKmsKeyRef.key_versionAzureKmsKeyRef.kek_version
DataEncryptionKey(secret), DataEncryptionKey::new(secret), dek.0DataEncryptionKey::from(secret), dek.value()
errors::BoxedErrorremoved
AzureKmsProviderOptions::with_algorithm(EncryptionAlgorithm::RsaOaep256), with the Azure SDK’s enumwith_algorithm(AzureKmsAlgorithm::RsaOaepSha256); RsaOaep is RsaOaepSha1, A128Kw, A192Kw and A256Kw are Aes128KeyWrap, Aes192KeyWrap and Aes256KeyWrap, and CkmAesKeyWrap and CkmAesKeyWrapPad are Pkcs11AesKeyWrap and Pkcs11AesKeyWrapWithPadding. Rsa1_5, refused by 0.29 too, and the algorithms Key Vault does not wrap keys with have no variant

HashiCorp Vault Transit types have the Hc prefix:

0.290.30
VaultTransitProviderHcVaultTransitProvider
VaultTransitProviderOptionsHcVaultTransitProviderOptions
VaultTransitKeyRefHcVaultTransitKeyRef
VaultTransitTokenHcVaultTransitToken
examples/vault_transit_kms.rsexamples/hc_vault_transit_kms.rs

GcpKmsProviderOptions, AwsKmsProviderOptions and AzureKmsProviderOptions are #[non_exhaustive], so a struct literal of one fails to compile. Build them with new() and the with_* setters.

Traits replaced by inherent methods

AeadEncryption and KmsAeadEnvelopeEncryption are gone. Their methods are inherent methods of AeadCipher and KmsAeadEnvelope, so delete the trait imports. The AAD is any &(impl AsRef<[u8]> + ?Sized), like 0.29’s Aad: AsRef<[u8]>, so &aad still compiles, and the calls that make no KMS call are not async:

0.290.30
use kms_aead::KmsAeadEnvelopeEncryption; envelope.encrypt_value(&aad, &value).await?envelope.encrypt(&aad, &value).await?
envelope.encrypt_value_with_dek(&aad, &value, &dek).await?envelope.encrypt_with_dek(&aad, &value, &dek)?
envelope.decrypt_value(&aad, &cipher_text).await?envelope.decrypt(&aad, &value).await?
envelope.decrypt_value_with_dek(&aad, &cipher_text, &dek).await?envelope.decrypt_with_dek(&aad, &bare, &dek)?
encrypt_value_with_encrypted_dek, decrypt_value_with_encrypted_dekencrypt_with_encrypted_dek, decrypt_with_encrypted_dek
KmsAeadEnvelopeEncryption::<Aad>::generate_new_dek(&envelope)envelope.generate_encrypted_dek()
use kms_aead::AeadEncryption; cipher.encrypt_value(&aad, &value, &key).await?cipher.encrypt_bare(&aad, &value, &key)?
cipher.decrypt_value(&aad, &cipher_text, &key).await?cipher.decrypt_bare(&aad, &bare, &key)?

Every cipher text is an Encrypted<T, F>, see Formats. It has its own value() and into_value(), and so has EncryptedDataEncryptionKey. DataEncryptionKey does not implement ValueStruct in 0.30, and has its own value().

0.30 does not implement ConstantTimeEq on the public types. == still compares in constant time. The Debug of Encrypted prints only the length, and == is gone from randomised values: only an Encrypted<T, Deterministic> has it.

Your own provider

An application’s own implementation of the provider trait:

  • implements KmsAeadEncryptionProvider instead of KmsAeadRingEncryptionProvider, without #[async_trait]. Its methods stay async fn, and their futures must be Send;
  • adds fn kek(&self) -> &KekRef, with KekProvider::Other, and a key name that identifies the key;
  • deletes generate_encryption_key when it returned the backend’s key. The replacement, generate_key_material(&self, len), has a default implementation that lets the backend generate the key, and is implemented only for a KMS generator;
  • returns EncryptedDataEncryptionKey::new(bytes) from encrypt_data_encryption_key, with the KEK version the KMS reported added by with_kek_version. A KMS that needs the key version to decrypt gets it from those bytes, as the Azure provider’s do.

The plaintext the provider encrypts is the DEK serialised as a Tink key, see Formats. The library never inspects the provider’s own bytes.

The trait has no dyn form, so a Box<dyn KmsAeadRingEncryptionProvider> becomes a type parameter P: KmsAeadEncryptionProvider, or an enum of the providers the application uses. The trait requires Send and Sync, so P: KmsAeadEncryptionProvider needs no + Send + Sync.

Errors

KmsAeadError is #[non_exhaustive], so an exhaustive match on it needs a _ arm. It has two new variants, UnsupportedAlgorithm and LegacyFormat. code() returns the code of any variant, and source() returns the root cause.

KmsAeadSystemError, KmsAeadNetworkError, KmsAeadEncryptionError and the type of their public field, KmsAeadErrorPublicGenericDetails, are #[non_exhaustive] too, so a struct literal of one fails to compile, and a pattern on one needs ... Build the errors with create(code, message), or with new(public, message) and, where it has one, with_root_cause, and the details with KmsAeadErrorPublicGenericDetails::new(code).

The From conversions of SDK errors into KmsAeadError are gone: gcloud_sdk::error::Error, gcloud_sdk::tonic::Status, the AWS SdkError, the hyper client error, azure_core::Error and SystemTimeError. Map an SDK error in the application.

The variant of a Google Cloud KMS or AWS KMS error follows its code. In 0.29 every gRPC status was a NetworkError and every AWS error an EncryptionError. A PermissionDenied or NotFound from Google Cloud KMS is an EncryptionError in 0.30, and a timeout, a connection failure or a ThrottlingException from AWS KMS a NetworkError. The codes stay the same. See Retries.

Error codes that changed:

0.290.30Where
INVALID_CIPHERTEXTINVALID_CIPHER_TEXT_FORMATEncrypted::try_from of a Bare value shorter than a nonce and a tag
ENCRYPTIONRANDOM_GENERATORa CSPRNG failure, for a nonce or a key
DECRYPT_KEYENCRYPT_KEYthe GCP encryption, when its request cannot be built
DECRYPT_KEYRANDOM_GENERATORthe GCP KMS generator, when its request cannot be built
SYSTEM_TIME_ERRORremoved
UNKNOWN_ENCRYPTED_KEY_LAYOUTremovedstored encrypted DEKs are the provider’s bytes
AZURE_KEY_VERSION_MISSINGAZURE_ENCRYPTED_DEK_FORMATthe Azure decryption of bytes outside its layout; up to 0.33, the old code stays for a 0.29 value without a key version, with legacy-formats
AZURE_WRAP_ALGORITHMremovedAzureKmsAlgorithm has no variant for Rsa1_5 or an unknown algorithm

The other 0.29 codes keep their spelling. The new codes are listed in Error handling.

AWS KMS decryption names the key

The AWS provider sends the configured key as KeyId on every decryption. In 0.29 a decryption left it out, so AWS KMS decrypted under whichever key the encrypted DEK named, for any key the principal may decrypt with. A 0.30 process refuses a DEK encrypted under another key with IncorrectKeyException. A deployment that relied on decrypting under a second key configures a provider per key.

An alias name such as alias/orders becomes an alias ARN, where 0.29 built a key ARN of it. Configure the key ARN rather than an alias, see AWS KMS.

Default algorithm

The default algorithm of KmsAeadEnvelope is AES-256-GCM, which every Tink implementation reads in a KMS envelope. The default of 0.29 was ChaCha20-Poly1305.

A value does not record its algorithm. Values encrypted under the default of 0.29 decrypt only with ChaCha20-Poly1305 configured, and an envelope on the new default fails them with DECRYPT. A 0.29 envelope that named no algorithm becomes:

use kms_aead::backends::Ring;
use kms_aead::providers::{GcpKmsKeyRef, GcpKmsProvider};
use kms_aead::{AeadAlgorithm, KmsAeadEnvelope, KmsAeadEnvelopeOptions};

async fn example(key_ref: GcpKmsKeyRef) -> kms_aead::KmsAeadResult<()> {
// 0.29: KmsAeadRingEnvelopeEncryption::new(provider).await?
let envelope = KmsAeadEnvelope::<GcpKmsProvider, Ring>::with_options(
    GcpKmsProvider::new(&key_ref).await?,
    KmsAeadEnvelopeOptions::new().with_algorithm(AeadAlgorithm::ChaCha20Poly1305),
)?;
let _ = envelope;
Ok(())
}

Configure it on every envelope that reads those values, on the one that upgrades them, see Old values, and on every envelope that writes new values beside them: a reader cannot tell the two algorithms apart. AES-256-GCM suits a column that holds no 0.29 values.

Old values

0.30 writes Tink’s KMS envelope, and encrypts every DEK but Azure’s as a serialised Tink key. 0.29 wrote envelope layout v1 and the encrypted DEK layout v1 [0xFF][0x01]…, and 0.28.1 and earlier a length-prefixed envelope, all with the raw DEK encrypted. 0.30 to 0.33 read them only with the deprecated legacy-formats feature, and fail with LEGACY_FORMAT without it. Later releases have no such feature and refuse them, see Values written by 0.29 and earlier.

kms-aead 0.33 is the last release that reads them, so stored values move to the new format on it. The envelopes that read and upgrade those values keep the algorithm they were encrypted with, see Default algorithm.

To move stored values to the new format:

  1. upgrade every process that reads the values to 0.33 with legacy-formats. 0.29 and earlier cannot read Tink’s format, so no process writes it before every reader has the upgrade;
  2. rewrite the stored values with upgrade_legacy_value and upgrade_legacy_encrypted_dek of KmsAeadEnvelope, one or two KMS calls per value, see Upgrading stored values. upgrade_legacy_value takes the value’s AAD, and fails with DECRYPT on a value that does not decrypt under the envelope’s algorithm and that AAD;
  3. turn the feature off, and move to a later release.

Encrypted::<T, Envelope>::separate reads Tink’s format only, in every release, so code that separated stored 0.29 values runs after the sweep.

Values written by 0.29 and earlier

Releases after 0.33 never read the layouts of 0.29 and earlier. Reading one fails with KmsAeadError::EncryptionError and the code LEGACY_FORMAT:

  • Encrypted::<T, Envelope>::try_from refuses the envelope layout v1 and the length-prefixed envelope;
  • a decryption, the DEK cache and the re-encryptions refuse the encrypted DEK layout v1 before the KMS call, and an encrypted DEK that decrypts to the raw key after it. The values of 32-bit targets before 0.24.0 fail this way, since their framing is Tink’s.

The error never echoes the bytes read. The KMS AEAD decrypt spans of such values record error_code=LEGACY_FORMAT, see Observability.

In 0.30 to 0.33, legacy-formats reads them:

  • KmsAeadEnvelope::decrypt reads the three envelope layouts, which Encrypted<T, Envelope> holds with the feature;
  • the *_with_encrypted_dek calls and the DEK cache read the encrypted DEK layout v1 of 0.29 and raw encrypted DEKs.

Without the feature, those releases fail with KmsAeadError::LegacyFormat, the code LEGACY_FORMAT, and with the feature, the first read of each layout in a process logs one WARN event that names the upgrade methods.

Upgrading stored values

With legacy-formats, two methods of KmsAeadEnvelope in 0.30 to 0.33 rewrite a stored value in Tink’s format, and return None when it already is in it, so a sweep writes only the rows that change:

  • upgrade_legacy_value, for envelope values;
  • upgrade_legacy_encrypted_dek, for encrypted DEKs stored apart, such as the bytes of 0.29’s to_bytes.

Each decrypts the DEK with the provider, without the DEK cache, and encrypts it again as a serialised Tink key when it was in an older layout: one KMS call for a current value, two for an old one. A value in Tink’s framing needs the decryption to be told from the 32-bit layout before 0.24.0. The AEAD bytes stay as they are.

An upgraded DEK is encrypted under the KEK’s current version, so the upgrade also does what reencrypt_dek and reencrypt_encrypted_dek do for a value or a DEK already in Tink’s format, see Re-encrypt DEKs after a KEK rotation. Those two refuse a layout of 0.29 or earlier with LEGACY_FORMAT, so a sweep after a KEK rotation upgrades a value in an old layout and re-encrypts the DEK of a value in Tink’s format.

The envelope’s algorithm is the one the values were encrypted with: ChaCha20-Poly1305 for values that 0.29 and earlier encrypted under their default. A raw DEK does not record its algorithm, and the encrypted DEK of the upgrade records it as a Tink key type, so upgrade_legacy_value takes the value’s AAD and decrypts the value before it writes anything. Under another algorithm or another AAD it fails with DECRYPT. upgrade_legacy_encrypted_dek has no value to decrypt, so it records the envelope’s algorithm for any key of its length. Be aware not to upgrade a DEK stored apart under another algorithm than its values were encrypted with: use upgrade_legacy_value wherever the values are at hand.

A sweep over stored rows, on kms-aead 0.33 with legacy-formats:

use kms_aead::backends::AeadBackend;
use kms_aead::formats::Envelope;
use kms_aead::{Encrypted, KmsAeadDecryptionProvider, KmsAeadEnvelope, KmsAeadResult};
use secret_vault_value::SecretValue;

/// A stored envelope value and the AAD it was encrypted under.
struct Row {
    aad: Vec<u8>,
    value: Vec<u8>,
}

/// Rewrites the envelope values of `rows` in Tink's format, and returns how many changed.
#[allow(deprecated)]
async fn upgrade_values<P, B>(
    envelope: &KmsAeadEnvelope<P, B>,
    rows: &mut [Row],
) -> KmsAeadResult<usize>
where
    P: KmsAeadDecryptionProvider,
    B: AeadBackend,
{
    let mut upgraded = 0;
    for row in rows.iter_mut() {
        let stored = Encrypted::<SecretValue, Envelope>::try_from(row.value.clone())?;
        if let Some(value) = envelope.upgrade_legacy_value(&row.aad, &stored).await? {
            row.value = value.into_value();
            upgraded += 1;
        }
    }
    Ok(upgraded)
}

Upgrade every reader to 0.33 before the sweep writes: 0.29 and earlier cannot read Tink’s format.

Removal

Reading the layouts of 0.29 and earlier was deprecated in 0.30.0. 0.33 is the last release with the legacy-formats feature and the two upgrade methods, and later releases refuse the older layouts with LEGACY_FORMAT.