1use std::collections::HashSet;
51use std::fmt;
52use std::ops::Deref;
53use std::sync::{Arc, Mutex, OnceLock, RwLock};
54
55use encore_sdk_core::secrets as core_secrets;
56use serde::de::{DeserializeOwned, Error as _};
57use serde::{Deserialize, Deserializer};
58
59use crate::error::{ErrCode, Error};
60use crate::runtime::core;
61use crate::testing;
62
63pub trait SecretValue: Sized + Send + Sync + 'static {
65 fn from_bytes(bytes: &[u8]) -> Result<Self, Error>;
67}
68
69impl SecretValue for String {
70 fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
71 String::from_utf8(bytes.to_vec())
72 .map_err(|_| Error::new(ErrCode::Internal, "the secret's value is not valid UTF-8"))
73 }
74}
75
76impl SecretValue for Vec<u8> {
77 fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
78 Ok(bytes.to_vec())
79 }
80}
81
82pub struct Json<T>(pub T);
85
86impl<T> Deref for Json<T> {
87 type Target = T;
88
89 fn deref(&self) -> &T {
90 &self.0
91 }
92}
93
94impl<T: DeserializeOwned + Send + Sync + 'static> SecretValue for Json<T> {
95 fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
96 serde_json::from_slice(bytes).map(Json).map_err(|e| {
98 Error::new(
99 ErrCode::Internal,
100 format!(
101 "the secret's value is not the JSON expected: {:?} at line {} column {}",
102 e.classify(),
103 e.line(),
104 e.column()
105 ),
106 )
107 })
108 }
109}
110
111pub struct Value<T>(Arc<T>);
117
118impl<T> Deref for Value<T> {
119 type Target = T;
120
121 fn deref(&self) -> &T {
122 &self.0
123 }
124}
125
126impl<T> Clone for Value<T> {
127 fn clone(&self) -> Self {
128 Self(self.0.clone())
129 }
130}
131
132impl<T> fmt::Debug for Value<T> {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 f.write_str("Value(<secret>)")
135 }
136}
137
138pub(crate) use sealed::Scope;
139
140struct Inner<T> {
143 name: &'static str,
144 scope: Scope,
145 current: RwLock<Option<(Arc<core_secrets::Secret>, Arc<T>)>>,
148}
149
150impl<T: SecretValue> Inner<T> {
151 const fn new(name: &'static str, scope: Scope) -> Self {
152 Self {
153 name,
154 scope,
155 current: RwLock::new(None),
156 }
157 }
158
159 fn value(&self) -> Result<Value<T>, Error> {
160 if let Some(test) = testing::active().ok().flatten() {
163 if let Some(bytes) = test.secret(self.scope, self.name) {
164 return T::from_bytes(&bytes).map(|value| Value(Arc::new(value)));
165 }
166 }
167
168 let secrets = core().secrets();
169 let secret = match self.scope {
170 Scope::App => secrets.shared_secret(self.name.into()),
171 Scope::Service => secrets.service_secret(self.name.into()),
172 }
173 .ok_or_else(|| {
174 Error::not_found(match self.scope {
175 Scope::App => format!("secret {:?} is not configured", self.name),
176 Scope::Service => {
177 format!("secret {:?} is not configured for this service", self.name)
178 }
179 })
180 })?;
181
182 let current = self.current.read().unwrap_or_else(|e| e.into_inner());
183 if let Some((read_from, value)) = current.as_ref() {
184 if Arc::ptr_eq(read_from, &secret) {
185 return Ok(Value(value.clone()));
186 }
187 }
188 drop(current);
189
190 let bytes = secret
191 .get()
192 .map_err(|e| Error::wrap(ErrCode::Internal, e))?;
193 let value = Arc::new(T::from_bytes(bytes)?);
194 *self.current.write().unwrap_or_else(|e| e.into_inner()) = Some((secret, value.clone()));
195 Ok(Value(value))
196 }
197}
198
199#[derive(Deserialize)]
202#[serde(deny_unknown_fields)]
203struct Placeholder {
204 #[serde(rename = "$encore_secret")]
206 secret: PlaceholderSecret,
207}
208
209#[derive(Deserialize)]
210#[serde(deny_unknown_fields)]
211struct PlaceholderSecret {
212 name: String,
213 scope: String,
214}
215
216fn intern(name: String) -> &'static str {
219 static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
220 let mut names = NAMES
221 .get_or_init(Default::default)
222 .lock()
223 .unwrap_or_else(|e| e.into_inner());
224 match names.get(name.as_str()) {
225 Some(interned) => interned,
226 None => {
227 let interned: &'static str = Box::leak(name.into_boxed_str());
228 names.insert(interned);
229 interned
230 }
231 }
232}
233
234impl<'de, T: SecretValue> Deserialize<'de> for Secret<T> {
239 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
240 let placeholder = Placeholder::deserialize(deserializer).map_err(|_| {
243 D::Error::custom("a secret field reads a secret, and is not set in config")
244 })?;
245 let scope = match placeholder.secret.scope.as_str() {
246 "service" => Scope::Service,
247 "shared" | "global" => Scope::App,
248 other => {
249 return Err(D::Error::custom(format!(
250 "the secret {:?} has no scope {other:?}",
251 placeholder.secret.name
252 )))
253 }
254 };
255 Ok(Self(Inner::new(intern(placeholder.secret.name), scope)))
256 }
257}
258
259macro_rules! secret_type {
260 ($(#[$doc:meta])* $name:ident, $scope:expr) => {
261 $(#[$doc])*
262 pub struct $name<T = String>(Inner<T>);
263
264 impl<T: SecretValue> $name<T> {
265 pub const fn new(name: &'static str) -> Self {
269 Self(Inner::new(name, $scope))
270 }
271
272 pub const fn name(&self) -> &'static str {
274 self.0.name
275 }
276
277 pub fn value(&self) -> Result<Value<T>, Error> {
279 self.0.value()
280 }
281 }
282
283 impl<T> sealed::Sealed for $name<T> {
284 fn key(&self) -> (Scope, &'static str) {
285 (self.0.scope, self.0.name)
286 }
287 }
288
289 impl<T> AnySecret for $name<T> {}
290 };
291}
292
293secret_type!(
294 Secret,
297 Scope::Service
298);
299
300secret_type!(
301 SharedSecret,
304 Scope::App
305);
306
307secret_type!(
308 GlobalSecret,
311 Scope::App
312);
313
314mod sealed {
315 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
317 pub enum Scope {
318 App,
321 Service,
323 }
324
325 pub trait Sealed {
326 fn key(&self) -> (Scope, &'static str);
327 }
328}
329
330pub trait AnySecret: sealed::Sealed {}
333
334pub(crate) fn key_of(secret: &impl AnySecret) -> (Scope, &'static str) {
336 secret.key()
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342
343 #[test]
344 fn a_secret_field_reads_its_placeholder() {
345 assert_eq!(encore_sdk_core::config::PLACEHOLDER_KEY, "$encore_secret");
346 let placeholder =
347 serde_json::json!({"$encore_secret": {"name": "StripeKey", "scope": "shared"}});
348 let secret: Secret = serde_json::from_value(placeholder.clone()).unwrap();
349 assert_eq!(secret.name(), "StripeKey");
350 assert_eq!(key_of(&secret), (Scope::App, "StripeKey"));
352 let own: Secret = serde_json::from_value(
353 serde_json::json!({"$encore_secret": {"name": "StripeKey", "scope": "service"}}),
354 )
355 .unwrap();
356 assert_eq!(key_of(&own), (Scope::Service, "StripeKey"));
357
358 let again: Secret = serde_json::from_value(placeholder).unwrap();
360 assert!(std::ptr::eq(secret.name(), again.name()));
361
362 let err = serde_json::from_value::<Secret>(serde_json::json!("sk_live"))
364 .err()
365 .unwrap();
366 assert!(err.to_string().contains("not set in config"), "{err}");
367 assert!(!err.to_string().contains("sk_live"), "{err}");
368 }
369
370 #[test]
371 fn a_value_reads_as_what_it_holds_and_does_not_print_it() {
372 let value = Value(Arc::new("hunter2".to_string()));
373 assert_eq!(*value, "hunter2");
374 assert!(value.starts_with("hunter"));
375 let clone = value.clone();
377 assert!(Arc::ptr_eq(&value.0, &clone.0));
378 assert_eq!(format!("{value:?}"), "Value(<secret>)");
379 }
380}