Skip to main content

haste_server/
tenant_keys.rs

1//! Encryption under a tenant's own key.
2//!
3//! Each tenant has a key of its own for the secrets the server has to read
4//! back. The key is stored wrapped by a platform key (see
5//! `haste_repository::tenant_key`), so reading the database does not give it
6//! away. A tenant gets its key the first time something is encrypted for it.
7//!
8//! Keys have versions. A value is encrypted under the tenant's active key and
9//! is stored with that key's version, which is what decrypts it later, also
10//! once another version has become the active one.
11
12use haste_encryption::{
13    Encryptor as _, KeyWrapper, encryption::aes::AesGcmEncryptor, traits::EncryptionResult,
14};
15use haste_fhir_operation_error::{OperationOutcomeError, derive::OperationOutcomeError};
16use haste_jwt::TenantId;
17use haste_repository::tenant_key::{TenantKey, TenantKeyProvider};
18use moka::future::Cache;
19use std::{sync::Arc, time::Duration};
20
21/// How long an unwrapped key stays in memory. Until it is dropped, nothing
22/// asks the platform key (a network call, with a KMS) or the database.
23///
24/// It is also how long a server goes on encrypting under a key after another
25/// server has made a newer version the active one.
26const UNWRAPPED_KEY_LIFETIME: Duration = Duration::from_mins(5);
27
28/// The most unwrapped keys held at once, per cache.
29const UNWRAPPED_KEY_CAPACITY: u64 = 10_000;
30
31#[derive(OperationOutcomeError, Debug)]
32pub enum TenantKeyError {
33    #[error(
34        code = "exception",
35        diagnostic = "No platform key is configured to protect tenant keys."
36    )]
37    NotConfigured,
38    /// The tenant has keys and none of them is active.
39    #[fatal(code = "exception", diagnostic = "The tenant has no active key.")]
40    NoActiveKey,
41    #[fatal(
42        code = "exception",
43        diagnostic = "The tenant has no key of version {arg0}."
44    )]
45    UnknownVersion(i32),
46    #[fatal(
47        code = "exception",
48        diagnostic = "The tenant's key is protected by a platform key other than the configured one."
49    )]
50    OtherPlatformKey,
51}
52
53/// A value encrypted for a tenant, with the version of the tenant's key that
54/// decrypts it. Store the version next to the value.
55pub struct TenantEncryptionResult {
56    pub key_version: i32,
57    pub encrypted: EncryptionResult,
58}
59
60/// A tenant's key, ready to use.
61struct UnwrappedKey {
62    version: i32,
63    encryptor: AesGcmEncryptor,
64}
65
66/// Encrypts and decrypts with the keys of tenants.
67pub struct TenantKeys<Store> {
68    store: Arc<Store>,
69    /// `None` when no platform key is configured: every use then fails.
70    wrapper: Option<Arc<dyn KeyWrapper>>,
71    /// The key that encrypts for a tenant.
72    active: Cache<TenantId, Arc<UnwrappedKey>>,
73    /// The keys that decrypt, by version.
74    by_version: Cache<(TenantId, i32), Arc<UnwrappedKey>>,
75}
76
77/// A cache load hands its error to every waiting caller behind an `Arc`.
78fn unshare(error: Arc<OperationOutcomeError>) -> OperationOutcomeError {
79    Arc::try_unwrap(error)
80        .unwrap_or_else(|shared| OperationOutcomeError::new(None, shared.outcome().clone()))
81}
82
83impl<Store: TenantKeyProvider + Send + Sync + 'static> TenantKeys<Store> {
84    /// `store` is not a transaction: a key it creates has to outlast the
85    /// request that needed it first.
86    #[must_use]
87    pub fn new(store: Arc<Store>, wrapper: Option<Arc<dyn KeyWrapper>>) -> Self {
88        Self {
89            store,
90            wrapper,
91            active: Cache::builder()
92                .max_capacity(UNWRAPPED_KEY_CAPACITY)
93                .time_to_live(UNWRAPPED_KEY_LIFETIME)
94                .build(),
95            by_version: Cache::builder()
96                .max_capacity(UNWRAPPED_KEY_CAPACITY)
97                .time_to_live(UNWRAPPED_KEY_LIFETIME)
98                .build(),
99        }
100    }
101
102    /// Encrypts `plaintext` under the active key of `tenant`, creating the
103    /// tenant's first key when it has none, and binds the result to `aad`
104    /// (see [`haste_encryption::Encryptor::encrypt_with_aad`]).
105    ///
106    /// # Errors
107    ///
108    /// Fails when no platform key is configured, when the tenant's key cannot
109    /// be read, created or unwrapped, or when the encryption fails.
110    pub async fn encrypt(
111        &self,
112        tenant: &TenantId,
113        plaintext: &[u8],
114        aad: &[u8],
115    ) -> Result<TenantEncryptionResult, OperationOutcomeError> {
116        let key = self
117            .active
118            .try_get_with_by_ref(tenant, self.load_active(tenant))
119            .await
120            .map_err(unshare)?;
121
122        Ok(TenantEncryptionResult {
123            key_version: key.version,
124            encrypted: key.encryptor.encrypt_with_aad(plaintext, aad)?,
125        })
126    }
127
128    /// Decrypts what [`Self::encrypt`] returned for `tenant` and `aad`, with
129    /// the key version it was stored with.
130    ///
131    /// # Errors
132    ///
133    /// Fails when no platform key is configured, when the tenant has no key
134    /// of `key_version` or it cannot be unwrapped, or when `encrypted` was
135    /// altered or was encrypted for another tenant, key version or `aad`.
136    pub async fn decrypt(
137        &self,
138        tenant: &TenantId,
139        key_version: i32,
140        encrypted: &EncryptionResult,
141        aad: &[u8],
142    ) -> Result<Vec<u8>, OperationOutcomeError> {
143        let key = self
144            .by_version
145            .try_get_with(
146                (tenant.clone(), key_version),
147                self.load_version(tenant, key_version),
148            )
149            .await
150            .map_err(unshare)?;
151
152        key.encryptor.decrypt_with_aad(encrypted, aad)
153    }
154
155    fn wrapper(&self) -> Result<&dyn KeyWrapper, TenantKeyError> {
156        self.wrapper.as_deref().ok_or(TenantKeyError::NotConfigured)
157    }
158
159    async fn load_active(
160        &self,
161        tenant: &TenantId,
162    ) -> Result<Arc<UnwrappedKey>, OperationOutcomeError> {
163        let wrapper = self.wrapper()?;
164
165        let stored = if let Some(stored) = self.store.active_tenant_key(tenant).await? {
166            stored
167        } else {
168            let key = AesGcmEncryptor::generate_key();
169            let wrapped_key = wrapper
170                .wrap_key(key.expose_bytes(), tenant.as_ref())
171                .await?;
172
173            // Another server may have stored a first key meanwhile; that one
174            // is then the tenant's key, and the one generated here is dropped.
175            let stored = self
176                .store
177                .create_first_tenant_key(tenant, &wrapped_key, wrapper.key_id())
178                .await?
179                .ok_or(TenantKeyError::NoActiveKey)?;
180
181            if stored.wrapped_key == wrapped_key {
182                tracing::info!(
183                    tenant = %tenant,
184                    version = stored.version,
185                    wrapped_by = %stored.wrapped_by,
186                    "Created the tenant's first key"
187                );
188            }
189            stored
190        };
191
192        let key = self.unwrap(tenant, stored).await?;
193        // What is encrypted under it is decrypted without unwrapping again.
194        self.by_version
195            .insert((tenant.clone(), key.version), key.clone())
196            .await;
197
198        Ok(key)
199    }
200
201    async fn load_version(
202        &self,
203        tenant: &TenantId,
204        version: i32,
205    ) -> Result<Arc<UnwrappedKey>, OperationOutcomeError> {
206        self.wrapper()?;
207
208        let stored = self
209            .store
210            .tenant_key(tenant, version)
211            .await?
212            .ok_or(TenantKeyError::UnknownVersion(version))?;
213
214        self.unwrap(tenant, stored).await
215    }
216
217    async fn unwrap(
218        &self,
219        tenant: &TenantId,
220        stored: TenantKey,
221    ) -> Result<Arc<UnwrappedKey>, OperationOutcomeError> {
222        let wrapper = self.wrapper()?;
223
224        if stored.wrapped_by != wrapper.key_id() {
225            tracing::error!(
226                tenant = %tenant,
227                version = stored.version,
228                wrapped_by = %stored.wrapped_by,
229                configured = %wrapper.key_id(),
230                "The tenant's key is wrapped by a platform key other than the configured one"
231            );
232            return Err(TenantKeyError::OtherPlatformKey.into());
233        }
234
235        let key = wrapper
236            .unwrap_key(&stored.wrapped_key, tenant.as_ref())
237            .await?;
238
239        Ok(Arc::new(UnwrappedKey {
240            version: stored.version,
241            encryptor: AesGcmEncryptor::new(key.expose_bytes())?,
242        }))
243    }
244}
245
246#[cfg(test)]
247pub(crate) mod tests {
248    use super::*;
249    use haste_encryption::{Secret, SecretsProvider, key_wrapper::local::LocalKeyWrapper};
250    use std::{
251        collections::HashMap,
252        future::Future,
253        pin::Pin,
254        sync::{
255            Mutex,
256            atomic::{AtomicUsize, Ordering},
257        },
258    };
259
260    /// Tenant keys in memory, with `retired` and `active` as the table has
261    /// them, and a count of the reads and writes.
262    #[derive(Default)]
263    pub(crate) struct MemoryStore {
264        keys: Mutex<HashMap<String, Vec<(TenantKey, bool)>>>,
265        calls: AtomicUsize,
266    }
267
268    impl MemoryStore {
269        fn calls(&self) -> usize {
270            self.calls.load(Ordering::SeqCst)
271        }
272
273        fn versions(&self, tenant: &TenantId) -> Vec<TenantKey> {
274            let keys = self.keys.lock().unwrap();
275            keys.get(tenant.as_ref())
276                .map(|keys| keys.iter().map(|(key, _)| key.clone()).collect())
277                .unwrap_or_default()
278        }
279
280        /// Retires the active key of `tenant` and makes `key` the active one.
281        pub(crate) fn rotate_to(&self, tenant: &TenantId, key: TenantKey) {
282            let mut keys = self.keys.lock().unwrap();
283            let keys = keys.entry(tenant.as_ref().to_string()).or_default();
284            for (_, active) in keys.iter_mut() {
285                *active = false;
286            }
287            keys.push((key, true));
288        }
289    }
290
291    impl TenantKeyProvider for MemoryStore {
292        async fn active_tenant_key(
293            &self,
294            tenant: &TenantId,
295        ) -> Result<Option<TenantKey>, OperationOutcomeError> {
296            self.calls.fetch_add(1, Ordering::SeqCst);
297            let keys = self.keys.lock().unwrap();
298            Ok(keys.get(tenant.as_ref()).and_then(|keys| {
299                keys.iter()
300                    .find(|(_, active)| *active)
301                    .map(|(key, _)| key.clone())
302            }))
303        }
304
305        async fn tenant_key(
306            &self,
307            tenant: &TenantId,
308            version: i32,
309        ) -> Result<Option<TenantKey>, OperationOutcomeError> {
310            self.calls.fetch_add(1, Ordering::SeqCst);
311            let keys = self.keys.lock().unwrap();
312            Ok(keys.get(tenant.as_ref()).and_then(|keys| {
313                keys.iter()
314                    .find(|(key, _)| key.version == version)
315                    .map(|(key, _)| key.clone())
316            }))
317        }
318
319        async fn create_first_tenant_key(
320            &self,
321            tenant: &TenantId,
322            wrapped_key: &[u8],
323            wrapped_by: &str,
324        ) -> Result<Option<TenantKey>, OperationOutcomeError> {
325            self.calls.fetch_add(1, Ordering::SeqCst);
326            let mut keys = self.keys.lock().unwrap();
327            let keys = keys.entry(tenant.as_ref().to_string()).or_default();
328            if keys.is_empty() {
329                keys.push((
330                    TenantKey {
331                        version: 1,
332                        wrapped_key: wrapped_key.to_vec(),
333                        wrapped_by: wrapped_by.to_string(),
334                    },
335                    true,
336                ));
337            }
338            Ok(keys
339                .iter()
340                .find(|(_, active)| *active)
341                .map(|(key, _)| key.clone()))
342        }
343    }
344
345    /// Platform keys by name, in memory.
346    pub(crate) struct StaticSecrets;
347
348    impl SecretsProvider for StaticSecrets {
349        fn get_secret<'a>(
350            &'a self,
351            name: &'a str,
352        ) -> Pin<Box<dyn Future<Output = Result<Secret, OperationOutcomeError>> + Send + 'a>>
353        {
354            Box::pin(async move {
355                match name {
356                    "PLATFORM_KEY" => Ok(Secret::new(vec![1u8; 32])),
357                    "OTHER_PLATFORM_KEY" => Ok(Secret::new(vec![2u8; 32])),
358                    other => Err(haste_encryption::EncryptionError::SecretNotFound(
359                        other.to_string(),
360                    )
361                    .into()),
362                }
363            })
364        }
365    }
366
367    pub(crate) fn wrapper(secret_name: &str) -> Arc<dyn KeyWrapper> {
368        Arc::new(LocalKeyWrapper::new(
369            Arc::new(StaticSecrets),
370            secret_name.to_string(),
371        ))
372    }
373
374    pub(crate) fn tenant_keys(store: &Arc<MemoryStore>) -> TenantKeys<MemoryStore> {
375        TenantKeys::new(store.clone(), Some(wrapper("PLATFORM_KEY")))
376    }
377
378    pub(crate) fn tenant(id: &str) -> TenantId {
379        TenantId::new(id.to_string()).unwrap()
380    }
381
382    /// A new key for `tenant` at `version`, wrapped as the server would.
383    pub(crate) async fn new_stored_key(tenant: &TenantId, version: i32) -> TenantKey {
384        let wrapper = wrapper("PLATFORM_KEY");
385        TenantKey {
386            version,
387            wrapped_key: wrapper
388                .wrap_key(
389                    AesGcmEncryptor::generate_key().expose_bytes(),
390                    tenant.as_ref(),
391                )
392                .await
393                .unwrap(),
394            wrapped_by: wrapper.key_id().to_string(),
395        }
396    }
397
398    #[tokio::test]
399    async fn the_first_encryption_creates_the_tenants_key() {
400        let store = Arc::new(MemoryStore::default());
401        let keys = tenant_keys(&store);
402        let acme = tenant("acme");
403
404        let result = keys.encrypt(&acme, b"totp-secret", b"label").await.unwrap();
405
406        assert_eq!(result.key_version, 1);
407        assert_ne!(result.encrypted.ciphertext, b"totp-secret");
408        let stored = store.versions(&acme);
409        assert_eq!(stored.len(), 1);
410        assert_eq!(stored[0].wrapped_by, "PLATFORM_KEY");
411
412        let plaintext = keys
413            .decrypt(&acme, result.key_version, &result.encrypted, b"label")
414            .await
415            .unwrap();
416        assert_eq!(plaintext, b"totp-secret");
417    }
418
419    /// Another server, which shares only the store and the platform key,
420    /// reads what this one wrote.
421    #[tokio::test]
422    async fn another_server_decrypts_with_the_stored_key() {
423        let store = Arc::new(MemoryStore::default());
424        let acme = tenant("acme");
425        let result = tenant_keys(&store)
426            .encrypt(&acme, b"totp-secret", b"label")
427            .await
428            .unwrap();
429
430        let other_server = tenant_keys(&store);
431        let plaintext = other_server
432            .decrypt(&acme, result.key_version, &result.encrypted, b"label")
433            .await
434            .unwrap();
435        assert_eq!(plaintext, b"totp-secret");
436
437        // And it encrypts under the same key rather than a second one.
438        let again = other_server
439            .encrypt(&acme, b"totp-secret", b"label")
440            .await
441            .unwrap();
442        assert_eq!(again.key_version, 1);
443        assert_eq!(store.versions(&acme).len(), 1);
444    }
445
446    #[tokio::test]
447    async fn another_label_does_not_decrypt() {
448        let store = Arc::new(MemoryStore::default());
449        let keys = tenant_keys(&store);
450        let acme = tenant("acme");
451        let result = keys
452            .encrypt(&acme, b"totp-secret", b"user-1")
453            .await
454            .unwrap();
455
456        assert!(
457            keys.decrypt(&acme, result.key_version, &result.encrypted, b"user-2")
458                .await
459                .is_err()
460        );
461    }
462
463    /// The same label and key version in another tenant is another key.
464    #[tokio::test]
465    async fn another_tenant_does_not_decrypt() {
466        let store = Arc::new(MemoryStore::default());
467        let keys = tenant_keys(&store);
468        let (acme, globex) = (tenant("acme"), tenant("globex"));
469        let for_acme = keys.encrypt(&acme, b"totp-secret", b"label").await.unwrap();
470        let for_globex = keys
471            .encrypt(&globex, b"totp-secret", b"label")
472            .await
473            .unwrap();
474        assert_eq!(for_acme.key_version, for_globex.key_version);
475
476        assert!(
477            keys.decrypt(&globex, for_acme.key_version, &for_acme.encrypted, b"label")
478                .await
479                .is_err()
480        );
481    }
482
483    /// A tenant's stored key moved to another tenant's row does not unwrap.
484    #[tokio::test]
485    async fn a_key_stored_for_another_tenant_is_refused() {
486        let store = Arc::new(MemoryStore::default());
487        let (acme, globex) = (tenant("acme"), tenant("globex"));
488        tenant_keys(&store)
489            .encrypt(&acme, b"totp-secret", b"label")
490            .await
491            .unwrap();
492        let acme_key = store.versions(&acme).remove(0);
493        store.rotate_to(&globex, acme_key);
494
495        assert!(
496            tenant_keys(&store)
497                .encrypt(&globex, b"totp-secret", b"label")
498                .await
499                .is_err()
500        );
501    }
502
503    #[tokio::test]
504    async fn unwrapped_keys_are_reused() {
505        let store = Arc::new(MemoryStore::default());
506        let keys = tenant_keys(&store);
507        let acme = tenant("acme");
508
509        let result = keys.encrypt(&acme, b"totp-secret", b"label").await.unwrap();
510        let after_first_use = store.calls();
511        assert!(after_first_use > 0);
512
513        for _ in 0..5 {
514            let result = keys.encrypt(&acme, b"totp-secret", b"label").await.unwrap();
515            keys.decrypt(&acme, result.key_version, &result.encrypted, b"label")
516                .await
517                .unwrap();
518        }
519        keys.decrypt(&acme, result.key_version, &result.encrypted, b"label")
520            .await
521            .unwrap();
522
523        assert_eq!(store.calls(), after_first_use);
524    }
525
526    /// Requests that need a tenant's first key at once share one.
527    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
528    async fn concurrent_first_encryptions_share_one_key() {
529        let store = Arc::new(MemoryStore::default());
530        let keys = Arc::new(tenant_keys(&store));
531        let acme = tenant("acme");
532
533        let encryptions = (0..16)
534            .map(|_| {
535                let (keys, acme) = (keys.clone(), acme.clone());
536                tokio::spawn(
537                    async move { keys.encrypt(&acme, b"totp-secret", b"label").await.unwrap() },
538                )
539            })
540            .collect::<Vec<_>>();
541
542        for encryption in encryptions {
543            let result = encryption.await.unwrap();
544            let plaintext = keys
545                .decrypt(&acme, result.key_version, &result.encrypted, b"label")
546                .await
547                .unwrap();
548            assert_eq!(plaintext, b"totp-secret");
549        }
550        assert_eq!(store.versions(&acme).len(), 1);
551    }
552
553    /// After a rotation a server that starts encrypts under the new version
554    /// and still decrypts what the old one encrypted.
555    #[tokio::test]
556    async fn an_older_version_still_decrypts() {
557        let store = Arc::new(MemoryStore::default());
558        let acme = tenant("acme");
559        let before = tenant_keys(&store)
560            .encrypt(&acme, b"totp-secret", b"label")
561            .await
562            .unwrap();
563        store.rotate_to(&acme, new_stored_key(&acme, 2).await);
564
565        let keys = tenant_keys(&store);
566        let after = keys.encrypt(&acme, b"totp-secret", b"label").await.unwrap();
567        assert_eq!((before.key_version, after.key_version), (1, 2));
568
569        for result in [&before, &after] {
570            let plaintext = keys
571                .decrypt(&acme, result.key_version, &result.encrypted, b"label")
572                .await
573                .unwrap();
574            assert_eq!(plaintext, b"totp-secret");
575        }
576        // The version says which key: the other one does not decrypt.
577        assert!(
578            keys.decrypt(&acme, 2, &before.encrypted, b"label")
579                .await
580                .is_err()
581        );
582    }
583
584    #[tokio::test]
585    async fn an_unknown_version_is_an_error() {
586        let store = Arc::new(MemoryStore::default());
587        let keys = tenant_keys(&store);
588        let acme = tenant("acme");
589        let result = keys.encrypt(&acme, b"totp-secret", b"label").await.unwrap();
590
591        let error = keys
592            .decrypt(&acme, 7, &result.encrypted, b"label")
593            .await
594            .unwrap_err();
595        assert!(format!("{error:?}").contains("no key of version 7"));
596
597        // Decrypting never creates a key.
598        let globex = tenant("globex");
599        assert!(
600            keys.decrypt(&globex, 1, &result.encrypted, b"label")
601                .await
602                .is_err()
603        );
604        assert!(store.versions(&globex).is_empty());
605    }
606
607    #[tokio::test]
608    async fn without_a_platform_key_nothing_is_encrypted() {
609        let store = Arc::new(MemoryStore::default());
610        let keys = TenantKeys::new(store.clone(), None);
611        let acme = tenant("acme");
612
613        let error = keys
614            .encrypt(&acme, b"totp-secret", b"label")
615            .await
616            .err()
617            .unwrap();
618        assert!(format!("{error:?}").contains("No platform key is configured"));
619        assert!(store.versions(&acme).is_empty());
620        assert_eq!(store.calls(), 0);
621    }
622
623    /// A server configured with another platform key says so, rather than
624    /// failing to decrypt or creating a second key.
625    #[tokio::test]
626    async fn a_key_wrapped_by_another_platform_key_is_refused() {
627        let store = Arc::new(MemoryStore::default());
628        let acme = tenant("acme");
629        let result = tenant_keys(&store)
630            .encrypt(&acme, b"totp-secret", b"label")
631            .await
632            .unwrap();
633
634        let misconfigured = TenantKeys::new(store.clone(), Some(wrapper("OTHER_PLATFORM_KEY")));
635        for error in [
636            misconfigured
637                .encrypt(&acme, b"totp-secret", b"label")
638                .await
639                .err()
640                .unwrap(),
641            misconfigured
642                .decrypt(&acme, result.key_version, &result.encrypted, b"label")
643                .await
644                .unwrap_err(),
645        ] {
646            assert!(format!("{error:?}").contains("other than the configured one"));
647        }
648        assert_eq!(store.versions(&acme).len(), 1);
649    }
650
651    /// A failure to load a key is not remembered: the next use tries again.
652    #[tokio::test]
653    async fn a_failed_load_is_retried() {
654        let store = Arc::new(MemoryStore::default());
655        let acme = tenant("acme");
656        let keys = TenantKeys::new(store.clone(), Some(wrapper("MISSING")));
657        assert!(keys.encrypt(&acme, b"totp-secret", b"label").await.is_err());
658        assert!(keys.encrypt(&acme, b"totp-secret", b"label").await.is_err());
659        assert!(store.versions(&acme).is_empty());
660    }
661}