ncryptf/rocket/
mod.rs

1use rocket::Request;
2
3/// The cached public key from the request
4pub struct RequestPublicKey(pub Vec<u8>);
5
6/// The cached signing public key from the request
7pub struct RequestSigningPublicKey(pub Vec<u8>);
8
9mod json;
10pub use json::{respond_to_with_ncryptf, Error as JsonError, Json, JsonResponse, parse_body};
11mod ek;
12mod auth;
13pub use auth::{AuthorizationTrait, TokenError, RequestData, *};
14use crate::shared::{ExportableEncryptionKeyData, EncryptionKey};
15use cached::{Cached, IOCached};
16use std::sync::{Arc, Mutex};
17
18/// A wrapper for supported cache types
19pub enum CacheWrapper {
20    TimedCache(Arc<Mutex<cached::TimedCache<String, EncryptionKey>>>),
21    UnboundCache(Arc<Mutex<cached::UnboundCache<String, EncryptionKey>>>),
22    RedisCache(Arc<Mutex<cached::RedisCache<String, EncryptionKey>>>),
23}
24
25impl CacheWrapper {
26    pub fn get(&self, key: &str) -> Option<EncryptionKey> {
27        match self {
28            CacheWrapper::TimedCache(cache) => {
29                let mut guard = cache.lock().ok()?;
30                guard.cache_get(&key.to_string()).cloned()
31            }
32            CacheWrapper::UnboundCache(cache) => {
33                let mut guard = cache.lock().ok()?;
34                guard.cache_get(&key.to_string()).cloned()
35            }
36            CacheWrapper::RedisCache(cache) => {
37                let guard = cache.lock().ok()?;
38                match guard.cache_get(&key.to_string()) {
39                    Ok(value) => value,
40                    Err(_) => None,
41                }
42            }
43        }
44    }
45
46    pub fn set(&self, key: String, value: EncryptionKey) {
47        match self {
48            CacheWrapper::TimedCache(cache) => {
49                if let Ok(mut guard) = cache.lock() {
50                    guard.cache_set(key, value);
51                }
52            }
53            CacheWrapper::UnboundCache(cache) => {
54                if let Ok(mut guard) = cache.lock() {
55                    guard.cache_set(key, value);
56                }
57            }
58            CacheWrapper::RedisCache(cache) => {
59                if let Ok(guard) = cache.lock() {
60                    let _ = guard.cache_set(key, value);
61                }
62            }
63        }
64    }
65
66    pub fn remove(&self, key: &str) -> Option<EncryptionKey> {
67        match self {
68            CacheWrapper::TimedCache(cache) => {
69                let mut guard = cache.lock().ok()?;
70                guard.cache_remove(&key.to_string())
71            }
72            CacheWrapper::UnboundCache(cache) => {
73                let mut guard = cache.lock().ok()?;
74                guard.cache_remove(&key.to_string())
75            }
76            CacheWrapper::RedisCache(cache) => {
77                let guard = cache.lock().ok()?;
78                match guard.cache_remove(&key.to_string()) {
79                    Ok(value) => value,
80                    Err(_) => None,
81                }
82            }
83        }
84    }
85}
86
87/// Get the managed cache from Rocket state
88/// Returns a cache wrapper that can handle different cache types
89#[doc(hidden)]
90pub fn get_cache(req: &Request<'_>) -> Result<CacheWrapper, anyhow::Error> {
91    // Try cached::TimedCache
92    if let Some(cache) = req.rocket().state::<Arc<Mutex<cached::TimedCache<String, EncryptionKey>>>>() {
93        return Ok(CacheWrapper::TimedCache(cache.clone()));
94    }
95
96    // Try cached::UnboundCache
97    if let Some(cache) = req.rocket().state::<Arc<Mutex<cached::UnboundCache<String, EncryptionKey>>>>() {
98        return Ok(CacheWrapper::UnboundCache(cache.clone()));
99    }
100
101    // Try cached::RedisCache
102    if let Some(cache) = req.rocket().state::<Arc<Mutex<cached::RedisCache<String, EncryptionKey>>>>() {
103        return Ok(CacheWrapper::RedisCache(cache.clone()));
104    }
105
106    Err(anyhow::anyhow!(
107        "No supported cache found in rocket state. Make sure to add your cache as managed state with .manage(Arc::new(Mutex::new(your_cache)))"
108    ))
109}