hyprstream_core/auth/
production_user_store.rs1use super::UserStore;
9use crate::config::{CredentialsBackend, CredentialsConfig, HyprConfig};
10use anyhow::{Context, Result};
11use std::{ops::Deref, path::Path, sync::Arc};
12
13#[derive(Clone)]
58pub struct ProductionUserStore {
59 inner: Arc<dyn UserStore>,
60}
61
62pub(crate) struct ProductionStorePermit(());
68
69impl ProductionUserStore {
70 fn permit() -> ProductionStorePermit {
71 ProductionStorePermit(())
72 }
73
74 pub async fn open(credentials_dir: &Path) -> Result<Self> {
77 let config = HyprConfig::load()
78 .context("failed to load production credential configuration")?
79 .credentials;
80 Self::open_with_config(credentials_dir, &config).await
81 }
82
83 pub(crate) async fn open_with_config(
86 credentials_dir: &Path,
87 config: &CredentialsConfig,
88 ) -> Result<Self> {
89 let _ = credentials_dir;
93 config.backend.ensure_allowed_for_build()?;
94
95 match config.backend {
96 CredentialsBackend::Pglite => {
97 #[cfg(feature = "pglite")]
98 {
99 let store = super::PgliteUserStore::open_admitted(
100 credentials_dir.join("pglite"),
101 &Self::permit(),
102 )
103 .await
104 .context("open encrypted PGlite credential store")?;
105 Ok(Self::from_encrypted_backend(store))
106 }
107 #[cfg(not(feature = "pglite"))]
108 anyhow::bail!(
109 "credentials.backend = \"pglite\" but this binary lacks the pglite feature"
110 )
111 }
112 CredentialsBackend::Postgres => {
113 #[cfg(feature = "postgres")]
114 {
115 let store = super::PostgresUserStore::open_admitted(&Self::permit()).await?;
116 Ok(Self::from_encrypted_backend(store))
117 }
118 #[cfg(not(feature = "postgres"))]
119 anyhow::bail!(
120 "credentials.backend = \"postgres\" but this binary lacks the postgres feature"
121 )
122 }
123 CredentialsBackend::Rocksdb => {
124 #[cfg(all(not(feature = "encrypted-account-admission"), feature = "rocksdb"))]
125 {
126 let store =
127 super::RocksDbUserStore::open_admitted(credentials_dir, &Self::permit())
128 .context("open legacy RocksDB credential store")?;
129 Ok(Self {
130 inner: Arc::new(store),
131 })
132 }
133 #[cfg(all(not(feature = "encrypted-account-admission"), not(feature = "rocksdb")))]
134 {
135 anyhow::bail!(
136 "credentials.backend = \"rocksdb\" but this binary lacks the rocksdb feature"
137 )
138 }
139 #[cfg(feature = "encrypted-account-admission")]
140 unreachable!("encrypted-account-admission policy admitted RocksDB")
141 }
142 CredentialsBackend::Valkey => {
143 #[cfg(all(not(feature = "encrypted-account-admission"), feature = "valkey"))]
144 {
145 let store = super::ValkeyUserStore::connect_admitted(
146 &config.valkey.url,
147 &Self::permit(),
148 )
149 .await
150 .context("open legacy Valkey credential store")?;
151 Ok(Self {
152 inner: Arc::new(store),
153 })
154 }
155 #[cfg(all(not(feature = "encrypted-account-admission"), not(feature = "valkey")))]
156 {
157 anyhow::bail!(
158 "credentials.backend = \"valkey\" but this binary lacks the valkey feature"
159 )
160 }
161 #[cfg(feature = "encrypted-account-admission")]
162 {
163 unreachable!("encrypted-account-admission policy admitted Valkey")
164 }
165 }
166 }
167 }
168
169 pub(crate) async fn open_with_device_store(
174 credentials_dir: &Path,
175 config: &CredentialsConfig,
176 ) -> Result<(Self, Option<Arc<dyn super::DeviceStore>>)> {
177 config.backend.ensure_allowed_for_build()?;
178
179 #[cfg(all(not(feature = "encrypted-account-admission"), feature = "rocksdb"))]
180 if config.backend == CredentialsBackend::Rocksdb {
181 let store = Arc::new(
182 super::RocksDbUserStore::open_admitted(credentials_dir, &Self::permit())
183 .context("open legacy RocksDB credential/device store")?,
184 );
185 return Ok((
186 Self {
187 inner: Arc::clone(&store) as Arc<dyn UserStore>,
188 },
189 Some(store as Arc<dyn super::DeviceStore>),
190 ));
191 }
192
193 let account_store = Self::open_with_config(credentials_dir, config).await?;
194 #[cfg(feature = "rocksdb")]
198 let device_store = super::RocksDbUserStore::open_admitted(credentials_dir, &Self::permit())
199 .map(|store| Arc::new(store) as Arc<dyn super::DeviceStore>)
200 .map_err(|error| {
201 tracing::warn!("could not open RocksDB device store: {error:#}");
202 error
203 })
204 .ok();
205 #[cfg(not(feature = "rocksdb"))]
206 let device_store: Option<Arc<dyn super::DeviceStore>> = None;
207 Ok((account_store, device_store))
208 }
209
210 pub(crate) fn from_encrypted_backend<T>(store: T) -> Self
214 where
215 T: EncryptedUserStoreBackend + 'static,
216 {
217 Self {
218 inner: Arc::new(store),
219 }
220 }
221
222 pub(crate) fn clone_inner(&self) -> Arc<dyn UserStore> {
223 Arc::clone(&self.inner)
224 }
225
226 #[cfg(test)]
227 pub(crate) fn for_test(store: Arc<dyn UserStore>) -> Self {
228 Self { inner: store }
229 }
230}
231
232impl Deref for ProductionUserStore {
233 type Target = dyn UserStore;
234
235 fn deref(&self) -> &Self::Target {
236 self.inner.as_ref()
237 }
238}
239
240pub(crate) trait EncryptedUserStoreBackend: UserStore {}
246
247#[cfg(feature = "pglite")]
248impl EncryptedUserStoreBackend for super::PgliteUserStore {}
249
250#[cfg(feature = "postgres")]
251impl EncryptedUserStoreBackend for super::PostgresUserStore {}
252
253#[cfg(all(test, feature = "encrypted-account-admission"))]
254mod tests {
255 use super::*;
256
257 #[tokio::test]
258 async fn invalid_config_never_defaults_account_selection() -> Result<()> {
259 const CHILD: &str = "HYPRSTREAM_STORE_CONFIG_FAILURE_CHILD";
260 if std::env::var_os(CHILD).is_none() {
261 let root = tempfile::tempdir()?;
262 let mut child = std::process::Command::new(std::env::current_exe()?);
263 for (key, _) in std::env::vars_os() {
264 if key.to_string_lossy().starts_with("HYPRSTREAM__") {
265 child.env_remove(key);
266 }
267 }
268 let status = child.args([
269 "--exact", "auth::production_user_store::tests::invalid_config_never_defaults_account_selection",
270 "--nocapture",
271 ])
272 .env(CHILD, "1")
273 .env("XDG_CONFIG_HOME", root.path().join("config"))
274 .env("XDG_DATA_HOME", root.path().join("data"))
275 .env("HYPRSTREAM__CREDENTIALS__BACKEND", "postgres")
276 .env("HYPRSTREAM__OAUTH__PORT", "invalid-port")
277 .status()?;
278 anyhow::ensure!(
279 status.success(),
280 "invalid credential configuration child failed"
281 );
282 return Ok(());
283 }
284 let credentials = tempfile::tempdir()?;
285 let error = match ProductionUserStore::open(credentials.path()).await {
286 Ok(_) => anyhow::bail!("invalid configuration opened an account store"),
287 Err(error) => error,
288 };
289 assert!(error
290 .to_string()
291 .contains("failed to load production credential configuration"));
292 assert_eq!(std::fs::read_dir(credentials.path())?.count(), 0);
293 Ok(())
294 }
295
296 #[tokio::test]
297 async fn production_boundary_rejects_plaintext_backends_before_opening_storage() -> Result<()> {
298 let credentials_dir = tempfile::tempdir()?;
299
300 for backend in [CredentialsBackend::Rocksdb, CredentialsBackend::Valkey] {
301 let config = CredentialsConfig {
302 backend,
303 ..CredentialsConfig::default()
304 };
305 let error = match ProductionUserStore::open_with_config(credentials_dir.path(), &config)
306 .await
307 {
308 Ok(_) => panic!("encrypted-account-admission policy admitted a plaintext-capable account backend"),
309 Err(error) => error,
310 };
311 assert!(
312 error.to_string().contains(
313 "encrypted credential storage requires credentials.backend = \"pglite\" or \"postgres\"",
314 ),
315 "unexpected admission error: {error:#}"
316 );
317 }
318
319 assert!(
320 !credentials_dir.path().join("users.db").exists(),
321 "rejected backend must not open or create plaintext storage"
322 );
323 Ok(())
324 }
325
326 #[cfg(not(feature = "pglite"))]
327 #[tokio::test]
328 async fn metrics_profile_rejects_missing_encrypted_provider_before_opening_storage(
329 ) -> Result<()> {
330 let credentials_dir = tempfile::tempdir()?;
331 let error = match ProductionUserStore::open_with_config(
332 credentials_dir.path(),
333 &CredentialsConfig::default(),
334 )
335 .await
336 {
337 Ok(_) => panic!("metrics profile admitted an unavailable PGlite provider"),
338 Err(error) => error,
339 };
340
341 assert!(
342 error.to_string().contains(
343 "credentials.backend = \"pglite\" but this binary lacks the pglite feature"
344 ),
345 "unexpected provider error: {error:#}"
346 );
347 assert!(
348 !credentials_dir.path().join("pglite").exists(),
349 "missing provider must not create PGlite storage"
350 );
351 assert!(
352 !credentials_dir.path().join("users.db").exists(),
353 "missing provider must not create plaintext storage"
354 );
355 Ok(())
356 }
357}