# Multi-tenant data and key-service cost Calling a key service for every envelope costs latency, money, and quota: a service that seals 10,000 records per second would make 10,000 KMS requests per second. *Hierarchical keys* put one key-service call in front of thousands of envelopes, and give every tenant a key of its own. ## How it works ```{mermaid} flowchart LR R[root key
in the key service] -- wraps --> B1[branch key
tenant-acme] R -- wraps --> B2[branch key
tenant-globex] B1 -- derives a key per envelope --> E1[(envelopes)] B2 -- derives a key per envelope --> E2[(envelopes)] ``` A *branch key* is a random 256-bit key, stored only wrapped by the root key. The first use of a branch key unwraps it through the key service and caches it; later envelopes derive a fresh wrapping key from the cached branch key locally. The cache is bounded by age, number of uses, and size, overwrites the keys it evicts, and fetches each branch key once even under concurrency. ## Set up a branch key per tenant ```python from cryptography_suite import EncryptionContext, Policy, Protector from cryptography_suite.providers.hierarchical import ( HierarchicalKeyProvider, InMemoryBranchKeyStore, ) from cryptography_suite.providers.hpke import HpkeRecipientProvider, generate_private_key root = HpkeRecipientProvider(provider_id="example.kms") # stands in for a key service root_key = root.add_identity("root", generate_private_key()) branches = HierarchicalKeyProvider( store=InMemoryBranchKeyStore(), root=root, root_key=root_key, cache_ttl=300, # seconds a branch key stays cached max_uses=100_000, # envelopes per cached branch key ) branches.create_branch_key("tenant-acme") branches.create_branch_key("tenant-globex") ``` Give each tenant a `Protector` whose primary key is its branch key. Name the branch without a version, so that the tenant seals with the active version and trusts every version of its own branch after a rotation: ```python from cryptography_suite import KeyRef acme = Protector( provider=branches, policy=Policy(), primary_key=KeyRef(branches.provider_id, "tenant-acme"), ) globex = Protector( provider=branches, policy=Policy(), primary_key=KeyRef(branches.provider_id, "tenant-globex"), ) context = EncryptionContext({"tenant": "acme"}, purpose="orders") envelopes = [acme.seal(f"order {n}".encode(), context=context) for n in range(1_000)] assert all(acme.open(e, context=context) for e in envelopes) print(branches.root_calls) # 1: one key-service unwrap for 1,000 seals and opens ``` ## Isolation between tenants Each tenant's `Protector` trusts only its own branch key, so it refuses another tenant's envelopes before any key is used, even though both branch keys live in the same provider: ```python from cryptography_suite import ProviderError try: globex.open(envelopes[0], context=context) except ProviderError as error: print(error.code) # KEY_NOT_FOUND ``` Bind the tenant in the encryption context as well, as above. Then even code that trusts several tenants' keys cannot open one tenant's envelope as another's. ## Store branch keys durably `InMemoryBranchKeyStore` is for tests and single processes. In production, implement `BranchKeyStore` over your database. A record contains only the root-wrapped branch key, never the key itself, and serializes to JSON: ```python import sqlite3 from cryptography_suite.providers.hierarchical import BranchKeyRecord class SqliteBranchKeyStore: def __init__(self, connection: sqlite3.Connection) -> None: self._db = connection self._db.execute( "CREATE TABLE IF NOT EXISTS branch_keys (" " branch_id TEXT, version TEXT, record TEXT, active INTEGER," " PRIMARY KEY (branch_id, version))" ) def put(self, record: BranchKeyRecord, *, active: bool) -> None: with self._db: if active: self._db.execute( "UPDATE branch_keys SET active = 0 WHERE branch_id = ?", (record.branch_id,), ) self._db.execute( "INSERT INTO branch_keys VALUES (?, ?, ?, ?)", (record.branch_id, record.version, record.to_json(), int(active)), ) def get(self, branch_id: str, version: str) -> BranchKeyRecord | None: row = self._db.execute( "SELECT record FROM branch_keys WHERE branch_id = ? AND version = ?", (branch_id, version), ).fetchone() return None if row is None else BranchKeyRecord.from_json(row[0]) def active(self, branch_id: str) -> BranchKeyRecord | None: row = self._db.execute( "SELECT record FROM branch_keys WHERE branch_id = ? AND active = 1", (branch_id,), ).fetchone() return None if row is None else BranchKeyRecord.from_json(row[0]) database = sqlite3.connect("branch-keys.db") durable = HierarchicalKeyProvider( store=SqliteBranchKeyStore(database), root=root, root_key=root_key, ) durable.create_branch_key("tenant-initech") tenant = Protector( provider=durable, policy=Policy(), primary_key=KeyRef(durable.provider_id, "tenant-initech"), ) assert tenant.open(tenant.seal(b"invoice", context=context), context=context) == b"invoice" database.close() ``` The store is not trusted for integrity. A record that was altered, or copied from another tenant under a new name, fails to unwrap, because each branch key's wrap is bound to its branch identifier and version. ## Rotate a branch key `create_branch_key` with an existing name creates and activates a new version. New envelopes use it; old envelopes keep opening under the version that wrapped them, and `rewrap` moves them: ```python new_version = branches.create_branch_key("tenant-acme") rotated = acme.rewrap(envelopes[0], destination_key=new_version) assert acme.open(rotated, context=context) == b"order 0" ``` Rotating the root key at the key service leaves existing branch keys readable through the root version that wrapped them; branch versions created afterwards use the new root version. To retire an old root version, create a new version of each branch and rewrap its envelopes. ## Choosing the cache settings | Setting | Default | Trade-off | | --- | --- | --- | | `cache_ttl` | 300 seconds | How long a revoked root key keeps working for cached branches, against key-service calls per branch. | | `max_uses` | unlimited | Envelopes per cached branch key before it is fetched again. | | `max_cache_entries` | 1,024 | Branch keys held in memory; the least recently used is evicted. | `clear_cache()` overwrites and drops every cached branch key, for example when a tenant is offboarded.