Skip to main content

weirdnet_exchange/
credentials.rs

1//! Credentials typed by environment.
2//!
3//! A [`SecretSource`] holds an API secret somewhere (in memory, in `weirdnet-vault` with the
4//! `vault` feature) and says which [`Environment`] it belongs to. A [`Credential<Live>`] can
5//! only be made from a live source and a [`Credential<Test>`] only from a test one, so an
6//! adapter whose live constructor takes `Credential<Live>` cannot be built from test
7//! credentials, and a test (sandbox) constructor cannot be handed live ones. The environment is
8//! checked again on every use.
9//!
10//! ```
11//! use weirdnet_exchange::{Credential, Environment, Live, StaticSecret, Test};
12//!
13//! let test = StaticSecret::new(Environment::Test, "sandbox key", b"key:secret".to_vec());
14//! assert!(Credential::<Live>::new(test.clone()).is_err());
15//! let cred = Credential::<Test>::new(test).unwrap();
16//! assert_eq!(cred.with_secret(|s| s.len()).unwrap(), 10);
17//! ```
18
19use std::fmt;
20use std::marker::PhantomData;
21use std::sync::Arc;
22
23use zeroize::Zeroizing;
24
25use crate::exchange::Environment;
26use crate::{ExchangeError, Result};
27
28/// Somewhere a secret is kept.
29pub trait SecretSource: Send + Sync {
30    /// The secret's environment.
31    fn environment(&self) -> Environment;
32
33    /// A name that is safe to log (never the secret).
34    fn label(&self) -> String;
35
36    /// Calls `f` with the secret bytes. Implementations should not keep copies.
37    fn with_secret(&self, f: &mut dyn FnMut(&[u8])) -> Result<()>;
38}
39
40mod sealed {
41    pub trait Sealed {}
42}
43
44/// [`Live`] or [`Test`].
45pub trait EnvKind: sealed::Sealed + Send + Sync + 'static {
46    const ENVIRONMENT: Environment;
47}
48
49/// Marks live credentials.
50#[derive(Debug, Clone, Copy)]
51pub enum Live {}
52
53/// Marks test (sandbox, paper) credentials.
54#[derive(Debug, Clone, Copy)]
55pub enum Test {}
56
57impl sealed::Sealed for Live {}
58impl sealed::Sealed for Test {}
59impl EnvKind for Live {
60    const ENVIRONMENT: Environment = Environment::Live;
61}
62impl EnvKind for Test {
63    const ENVIRONMENT: Environment = Environment::Test;
64}
65
66/// A secret source checked to be in environment `E`.
67pub struct Credential<E: EnvKind> {
68    source: Arc<dyn SecretSource>,
69    _env: PhantomData<E>,
70}
71
72impl<E: EnvKind> Clone for Credential<E> {
73    fn clone(&self) -> Self {
74        Self { source: self.source.clone(), _env: PhantomData }
75    }
76}
77
78impl<E: EnvKind> Credential<E> {
79    /// Refuses a source from the other environment.
80    pub fn new(source: impl SecretSource + 'static) -> Result<Self> {
81        Self::from_arc(Arc::new(source))
82    }
83
84    pub fn from_arc(source: Arc<dyn SecretSource>) -> Result<Self> {
85        check::<E>(&*source)?;
86        Ok(Self { source, _env: PhantomData })
87    }
88
89    pub fn environment(&self) -> Environment {
90        E::ENVIRONMENT
91    }
92
93    pub fn label(&self) -> String {
94        self.source.label()
95    }
96
97    /// Calls `f` with the secret, after checking the source's environment again.
98    pub fn with_secret<R>(&self, f: impl FnOnce(&[u8]) -> R) -> Result<R> {
99        check::<E>(&*self.source)?;
100        let mut f = Some(f);
101        let mut out = None;
102        self.source.with_secret(&mut |s| {
103            if let Some(f) = f.take() {
104                out = Some(f(s));
105            }
106        })?;
107        out.ok_or_else(|| ExchangeError::Auth { message: format!("{} gave no secret", self.source.label()) })
108    }
109}
110
111fn check<E: EnvKind>(s: &dyn SecretSource) -> Result<()> {
112    let got = s.environment();
113    if got == E::ENVIRONMENT {
114        Ok(())
115    } else {
116        Err(ExchangeError::Environment { message: format!("{} is a {} credential; {} needed", s.label(), got.as_str(), E::ENVIRONMENT.as_str()) })
117    }
118}
119
120impl<E: EnvKind> fmt::Debug for Credential<E> {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.debug_struct("Credential").field("environment", &E::ENVIRONMENT).field("label", &self.source.label()).finish_non_exhaustive()
123    }
124}
125
126/// A secret held in memory (zeroed on drop), for tests and simple setups.
127#[derive(Clone)]
128pub struct StaticSecret {
129    environment: Environment,
130    label: String,
131    bytes: Zeroizing<Vec<u8>>,
132}
133
134impl StaticSecret {
135    pub fn new(environment: Environment, label: impl Into<String>, bytes: Vec<u8>) -> Self {
136        Self { environment, label: label.into(), bytes: Zeroizing::new(bytes) }
137    }
138}
139
140impl fmt::Debug for StaticSecret {
141    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
142        f.debug_struct("StaticSecret").field("environment", &self.environment).field("label", &self.label).finish_non_exhaustive()
143    }
144}
145
146impl SecretSource for StaticSecret {
147    fn environment(&self) -> Environment {
148        self.environment
149    }
150
151    fn label(&self) -> String {
152        self.label.clone()
153    }
154
155    fn with_secret(&self, f: &mut dyn FnMut(&[u8])) -> Result<()> {
156        f(&self.bytes);
157        Ok(())
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::*;
164    use std::sync::atomic::{AtomicBool, Ordering};
165
166    struct Flip(AtomicBool);
167    impl SecretSource for Flip {
168        fn environment(&self) -> Environment {
169            if self.0.load(Ordering::SeqCst) { Environment::Live } else { Environment::Test }
170        }
171        fn label(&self) -> String {
172            "flip".into()
173        }
174        fn with_secret(&self, f: &mut dyn FnMut(&[u8])) -> Result<()> {
175            f(b"s");
176            Ok(())
177        }
178    }
179
180    #[test]
181    fn environments_are_enforced_and_debug_is_redacted() {
182        let live = StaticSecret::new(Environment::Live, "prod", b"hunter2".to_vec());
183        assert!(matches!(Credential::<Test>::new(live.clone()), Err(ExchangeError::Environment { .. })));
184        let c = Credential::<Live>::new(live.clone()).unwrap();
185        assert_eq!(c.with_secret(|s| s.to_vec()).unwrap(), b"hunter2");
186        assert!(!format!("{c:?}{live:?}").contains("hunter2"));
187        let flip = Arc::new(Flip(AtomicBool::new(false)));
188        let c = Credential::<Test>::from_arc(flip.clone()).unwrap();
189        flip.0.store(true, Ordering::SeqCst);
190        assert!(matches!(c.with_secret(|_| ()), Err(ExchangeError::Environment { .. })), "re-checked on use");
191    }
192}