Skip to main content

encore/
secrets.rs

1//! Application secrets. Declared at module scope and resolved from the runtime.
2//!
3//! ```no_run
4//! use encore::secrets::Secret;
5//!
6//! static API_KEY: Secret = Secret::new("ApiKey");
7//!
8//! fn authorization() -> Result<String, encore::Error> {
9//!     Ok(format!("Bearer {}", *API_KEY.value()?))
10//! }
11//! ```
12//!
13//! # Scope
14//!
15//! Which of the three types a secret is declared with says who it belongs to:
16//!
17//! - A [`Secret`] belongs to the service that declares it. Two services may
18//!   each declare one of the same name and hold different values in them, so
19//!   adding a secret to one service can never collide with — or silently
20//!   reuse — a name another already took. It must be declared inside a service.
21//! - A [`SharedSecret`] has one value for the whole app. Any service may
22//!   declare it, and each that reads it is granted access to it.
23//! - A [`GlobalSecret`] has one value for the whole app and is available to
24//!   every service, without being granted.
25//!
26//! # Values
27//!
28//! [`Secret::value`] returns a [`Value`]: a handle to the secret's current
29//! value, cheap to make and to clone, which reads as the value itself. A
30//! secret's value can change while the app runs; a handle keeps the value it
31//! was made with, and the next call to `value` gives the new one. So take a
32//! handle where the value is used, rather than keeping one.
33//!
34//! A secret is a `String` unless its type says otherwise: `Secret<Vec<u8>>`
35//! for bytes, `Secret<Json<T>>` for a value stored as JSON.
36//!
37//! # In a config
38//!
39//! A field of a [config](crate::config) type may be a secret, naming the
40//! secret it reads: `#[config(secret = "StripeKey")] api_key: Secret`. The
41//! secret has the config's own scope, and is declared in code as any other.
42//! The config's value never holds it; reading the field reads the secret,
43//! with `value` as for any other.
44//!
45//! # Tests
46//!
47//! Under `encore test` a test can give a secret a value of its own, which no
48//! other test sees: [`testing::set_secret`](crate::testing::set_secret).
49
50use 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
63/// A type a secret's value can be read as.
64pub trait SecretValue: Sized + Send + Sync + 'static {
65    /// Reads the value from the secret's bytes.
66    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
82/// A secret value stored as JSON: `Secret<Json<Credentials>>`. Reads as the
83/// `T` inside.
84pub 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        // The error says where the JSON is wrong, never what it holds.
97        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
111/// A handle to a secret's value, as it was when the handle was made. Reads as
112/// the value: `&*value`, or any of its methods directly.
113///
114/// Cheap to clone: the clones share the value. It does not print it: its
115/// `Debug` says only that it is a secret.
116pub 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
140/// A secret's name and scope, and its value as last read: what the three
141/// secret types are.
142struct Inner<T> {
143    name: &'static str,
144    scope: Scope,
145    /// The value, with the runtime's secret it was read from: the runtime
146    /// gives a secret a new one when its value changes.
147    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        // A test's own value for the secret, if it set one. A thread that is no
161        // test's reads the app's, like any other code.
162        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        // A name has one scope across the app, so the lookup is by name.
169        let secret = core().secrets().get(self.name.into()).ok_or_else(|| {
170            Error::not_found(format!(
171                "secret {:?} is not configured for this service",
172                self.name
173            ))
174        })?;
175
176        let current = self.current.read().unwrap_or_else(|e| e.into_inner());
177        if let Some((read_from, value)) = current.as_ref() {
178            if Arc::ptr_eq(read_from, &secret) {
179                return Ok(Value(value.clone()));
180            }
181        }
182        drop(current);
183
184        let bytes = secret
185            .get()
186            .map_err(|e| Error::wrap(ErrCode::Internal, e))?;
187        let value = Arc::new(T::from_bytes(bytes)?);
188        *self.current.write().unwrap_or_else(|e| e.into_inner()) = Some((secret, value.clone()));
189        Ok(Value(value))
190    }
191}
192
193/// Where a secret field goes in a config's value: the runtime puts this
194/// placeholder there, naming the secret the type says the field reads.
195#[derive(Deserialize)]
196#[serde(deny_unknown_fields)]
197struct Placeholder {
198    // `encore_sdk_core::config::PLACEHOLDER_KEY`, checked in the tests.
199    #[serde(rename = "$encore_secret")]
200    secret: PlaceholderSecret,
201}
202
203#[derive(Deserialize)]
204#[serde(deny_unknown_fields)]
205struct PlaceholderSecret {
206    name: String,
207    scope: String,
208}
209
210/// The `'static` name a deserialized secret is declared with. Interned, so the
211/// same names read in every new config value are kept once.
212fn intern(name: String) -> &'static str {
213    static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
214    let mut names = NAMES
215        .get_or_init(Default::default)
216        .lock()
217        .unwrap_or_else(|e| e.into_inner());
218    match names.get(name.as_str()) {
219        Some(interned) => interned,
220        None => {
221            let interned: &'static str = Box::leak(name.into_boxed_str());
222            names.insert(interned);
223            interned
224        }
225    }
226}
227
228/// A config's secret field: read from the placeholder the runtime puts where
229/// the field goes, which names the secret and its scope — the config's own:
230/// a service's own config reads that service's secret, a shared or global
231/// config one of the app's. See the [`config`](crate::config) module.
232impl<'de, T: SecretValue> Deserialize<'de> for Secret<T> {
233    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
234        // Not serde's error, which would quote what was there instead: a
235        // value written where a secret goes may be the secret.
236        let placeholder = Placeholder::deserialize(deserializer).map_err(|_| {
237            D::Error::custom("a secret field reads a secret, and is not set in config")
238        })?;
239        let scope = match placeholder.secret.scope.as_str() {
240            "service" => Scope::Service,
241            "shared" | "global" => Scope::App,
242            other => {
243                return Err(D::Error::custom(format!(
244                    "the secret {:?} has no scope {other:?}",
245                    placeholder.secret.name
246                )))
247            }
248        };
249        Ok(Self(Inner::new(intern(placeholder.secret.name), scope)))
250    }
251}
252
253macro_rules! secret_type {
254    ($(#[$doc:meta])* $name:ident, $scope:expr) => {
255        $(#[$doc])*
256        pub struct $name<T = String>(Inner<T>);
257
258        impl<T: SecretValue> $name<T> {
259            /// Declare a secret by name. `const` so it can initialize a
260            /// module-scope `static`; nothing is resolved until its value is
261            /// asked for.
262            pub const fn new(name: &'static str) -> Self {
263                Self(Inner::new(name, $scope))
264            }
265
266            /// The name the secret was declared with.
267            pub const fn name(&self) -> &'static str {
268                self.0.name
269            }
270
271            /// The secret's current value: see [`Value`].
272            pub fn value(&self) -> Result<Value<T>, Error> {
273                self.0.value()
274            }
275        }
276
277        impl<T> sealed::Sealed for $name<T> {
278            fn key(&self) -> (Scope, &'static str) {
279                (self.0.scope, self.0.name)
280            }
281        }
282
283        impl<T> AnySecret for $name<T> {}
284    };
285}
286
287secret_type!(
288    /// A secret belonging to the service that declares it, which holds its own
289    /// value for it. Must be declared inside a service.
290    Secret,
291    Scope::Service
292);
293
294secret_type!(
295    /// A secret with one value for the whole app. A service that reads it is
296    /// granted access to it.
297    SharedSecret,
298    Scope::App
299);
300
301secret_type!(
302    /// A secret with one value for the whole app, available to every service
303    /// without being granted.
304    GlobalSecret,
305    Scope::App
306);
307
308mod sealed {
309    /// Who a secret belongs to.
310    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
311    pub enum Scope {
312        /// One value for the app, held in the shared namespace: a
313        /// `SharedSecret` or a `GlobalSecret`.
314        App,
315        /// The declaring service's own: a `Secret`.
316        Service,
317    }
318
319    pub trait Sealed {
320        fn key(&self) -> (Scope, &'static str);
321    }
322}
323
324/// Any of the secret types, whatever its value's type. Sealed: [`Secret`],
325/// [`SharedSecret`] and [`GlobalSecret`] are the only ones.
326pub trait AnySecret: sealed::Sealed {}
327
328/// The scope and name a secret is held under.
329pub(crate) fn key_of(secret: &impl AnySecret) -> (Scope, &'static str) {
330    secret.key()
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336
337    #[test]
338    fn a_secret_field_reads_its_placeholder() {
339        assert_eq!(encore_sdk_core::config::PLACEHOLDER_KEY, "$encore_secret");
340        let placeholder =
341            serde_json::json!({"$encore_secret": {"name": "StripeKey", "scope": "shared"}});
342        let secret: Secret = serde_json::from_value(placeholder.clone()).unwrap();
343        assert_eq!(secret.name(), "StripeKey");
344        // The placeholder's scope says which namespace it is read from.
345        assert_eq!(key_of(&secret), (Scope::App, "StripeKey"));
346        let own: Secret = serde_json::from_value(
347            serde_json::json!({"$encore_secret": {"name": "StripeKey", "scope": "service"}}),
348        )
349        .unwrap();
350        assert_eq!(key_of(&own), (Scope::Service, "StripeKey"));
351
352        // The same name read again is the same interned string.
353        let again: Secret = serde_json::from_value(placeholder).unwrap();
354        assert!(std::ptr::eq(secret.name(), again.name()));
355
356        // A value is no placeholder.
357        let err = serde_json::from_value::<Secret>(serde_json::json!("sk_live"))
358            .err()
359            .unwrap();
360        assert!(err.to_string().contains("not set in config"), "{err}");
361        assert!(!err.to_string().contains("sk_live"), "{err}");
362    }
363
364    #[test]
365    fn a_value_reads_as_what_it_holds_and_does_not_print_it() {
366        let value = Value(Arc::new("hunter2".to_string()));
367        assert_eq!(*value, "hunter2");
368        assert!(value.starts_with("hunter"));
369        // Clones share it.
370        let clone = value.clone();
371        assert!(Arc::ptr_eq(&value.0, &clone.0));
372        assert_eq!(format!("{value:?}"), "Value(<secret>)");
373    }
374}