weirdnet_exchange/
credentials.rs1use std::fmt;
20use std::marker::PhantomData;
21use std::sync::Arc;
22
23use zeroize::Zeroizing;
24
25use crate::exchange::Environment;
26use crate::{ExchangeError, Result};
27
28pub trait SecretSource: Send + Sync {
30 fn environment(&self) -> Environment;
32
33 fn label(&self) -> String;
35
36 fn with_secret(&self, f: &mut dyn FnMut(&[u8])) -> Result<()>;
38}
39
40mod sealed {
41 pub trait Sealed {}
42}
43
44pub trait EnvKind: sealed::Sealed + Send + Sync + 'static {
46 const ENVIRONMENT: Environment;
47}
48
49#[derive(Debug, Clone, Copy)]
51pub enum Live {}
52
53#[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
66pub 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 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 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#[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}