Skip to main content

hyprstream_core/auth/
production_user_store.rs

1//! Single production construction boundary for credential/account storage.
2//!
3//! `ProductionUserStore` is the only account-store handle accepted by OAuth,
4//! CLI, and bootstrap wiring. Its public constructor resolves deployment
5//! configuration and rejects plaintext-capable backends in an encrypted-account-admission
6//! build before opening any account database.
7
8use super::UserStore;
9use crate::config::{CredentialsBackend, CredentialsConfig, HyprConfig};
10use anyhow::{Context, Result};
11use std::{ops::Deref, path::Path, sync::Arc};
12
13/// Opaque handle proving that an account store passed production admission.
14///
15/// The inner trait object is intentionally private. Callers cannot manufacture
16/// this proof from an arbitrary `UserStore`; they must use [`Self::open`].
17///
18/// Raw plaintext backends are also not constructible out of crate:
19///
20/// ```compile_fail
21/// use hyprstream_core::auth::RocksDbUserStore;
22///
23/// let _ = RocksDbUserStore::open(std::path::Path::new("/tmp/plaintext"));
24/// ```
25///
26/// Nor can a downstream crate implement its own plaintext `UserStore`, because
27/// the trait's required sealing supertrait is crate-private:
28///
29/// ```compile_fail
30/// struct PlaintextStore;
31/// impl hyprstream_core::auth::user_store::private::Sealed for PlaintextStore {}
32/// ```
33///
34/// The admission constructor itself is not an injection point either:
35///
36/// ```compile_fail
37/// # struct PlaintextStore;
38/// let _ = hyprstream_core::auth::ProductionUserStore::from_encrypted_backend(
39///     PlaintextStore,
40/// );
41/// ```
42///
43/// Public OAuth wiring also requires the admitted handle, not an arbitrary
44/// trait object:
45///
46/// ```compile_fail
47/// use hyprstream_core::{
48///     auth::UserStore,
49///     services::oauth::state::OAuthState,
50/// };
51/// use std::sync::Arc;
52///
53/// fn inject_plaintext(state: OAuthState, store: Arc<dyn UserStore>) {
54///     let _ = state.with_user_store(store);
55/// }
56/// ```
57#[derive(Clone)]
58pub struct ProductionUserStore {
59    inner: Arc<dyn UserStore>,
60}
61
62/// Capability required by every raw backend constructor.
63///
64/// The type is crate-visible so backend modules can accept it, but its field is
65/// private to this module. Production callers therefore cannot open a backend
66/// without first passing this module's admission checks.
67pub(crate) struct ProductionStorePermit(());
68
69impl ProductionUserStore {
70    fn permit() -> ProductionStorePermit {
71        ProductionStorePermit(())
72    }
73
74    /// Open the deployment-selected account store through the sole production
75    /// admission boundary.
76    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    /// Open from already-resolved configuration. Kept crate-private so public
84    /// callers cannot substitute a configuration after deployment admission.
85    pub(crate) async fn open_with_config(
86        credentials_dir: &Path,
87        config: &CredentialsConfig,
88    ) -> Result<Self> {
89        // Metrics builds intentionally have no account provider. Keep the
90        // path consumed in the PGlite/default profile while allowing the
91        // provider-absence branch to compile without an unused argument.
92        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    /// Open the admitted account store and the independent anonymous-device
170    /// store used by OAuth. Builds without the encrypted-account admission
171    /// policy that select RocksDB share one handle so RocksDB's exclusive
172    /// writer lock is not acquired twice.
173    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        // The anonymous-device store is the one RocksDB handle that every
195        // production posture shares; a build without the `rocksdb` feature
196        // has no device store (already tolerated as `None` downstream).
197        #[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    /// Admit a backend whose implementation is structurally marked as
211    /// encrypted-at-rest. PGlite and Postgres are both explicit admission
212    /// providers.
213    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
240/// Crate-private admission marker for encrypted-at-rest account backends.
241///
242/// Keeping the implementation list here makes adding a backend an explicit
243/// security decision rather than something any `UserStore` implementation
244/// inherits automatically.
245pub(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}