Skip to main content

rtb_app/
credentials.rs

1//! [`CredentialProvider`] — the type-erased object [`crate::app::App`]
2//! stores so commands can enumerate credentials without `App` itself
3//! becoming generic over the downstream tool's config type.
4//!
5//! # Why two traits?
6//!
7//! [`rtb_credentials::CredentialBearing`] returns
8//! `Vec<(&'static str, &CredentialRef)>` — borrows tied to the
9//! provider's lifetime. That's the right shape for *implementing*
10//! the trait on a typed config struct, but not for storing a
11//! type-erased `Box<dyn …>` on `App` (no lifetime to anchor the
12//! borrows to).
13//!
14//! `CredentialProvider` is the storage-side dual: returns owned
15//! `Vec<(String, CredentialRef)>`. There is a blanket impl for
16//! every `T: CredentialBearing + Send + Sync + 'static` — downstream
17//! tools implement `CredentialBearing` once and the framework
18//! converts on demand.
19
20use std::sync::Arc;
21
22use rtb_credentials::{CredentialBearing, CredentialRef};
23
24/// Type-erased credential listing. Stored on [`crate::app::App`] as
25/// `Option<Arc<dyn CredentialProvider>>`.
26pub trait CredentialProvider: Send + Sync {
27    /// Yield owned `(name, credential)` pairs for every credential
28    /// the underlying value knows about.
29    fn list(&self) -> Vec<(String, CredentialRef)>;
30}
31
32/// Blanket impl wrapping any `CredentialBearing` + `Send` + `Sync`
33/// type. Downstream tools `impl CredentialBearing for MyConfig`
34/// once and `Application::builder().credentials_from(Arc::new(my_config))`
35/// just works.
36impl<T> CredentialProvider for T
37where
38    T: CredentialBearing + Send + Sync + 'static,
39{
40    fn list(&self) -> Vec<(String, CredentialRef)> {
41        self.credentials()
42            .into_iter()
43            .map(|(name, cred)| (name.to_string(), cred.clone()))
44            .collect()
45    }
46}
47
48/// Convenience: an empty provider. Used by `App::for_testing` and
49/// any tool that hasn't wired a provider yet.
50#[derive(Default)]
51pub struct NoCredentials;
52
53impl CredentialProvider for NoCredentials {
54    fn list(&self) -> Vec<(String, CredentialRef)> {
55        Vec::new()
56    }
57}
58
59/// Test-friendly handle: the wrapped provider when `Some`, or an
60/// empty listing when `None`. Used by [`crate::app::App::credentials`].
61#[must_use]
62pub fn list_or_empty(
63    provider: Option<&Arc<dyn CredentialProvider>>,
64) -> Vec<(String, CredentialRef)> {
65    provider.map(|p| p.list()).unwrap_or_default()
66}