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        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/// Where a secret field goes in a config's value: the runtime puts this
200/// placeholder there, naming the secret the type says the field reads.
201#[derive(Deserialize)]
202#[serde(deny_unknown_fields)]
203struct Placeholder {
204    // `encore_sdk_core::config::PLACEHOLDER_KEY`, checked in the tests.
205    #[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
216/// The `'static` name a deserialized secret is declared with. Interned, so the
217/// same names read in every new config value are kept once.
218fn 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
234/// A config's secret field: read from the placeholder the runtime puts where
235/// the field goes, which names the secret and its scope — the config's own:
236/// a service's own config reads that service's secret, a shared or global
237/// config one of the app's. See the [`config`](crate::config) module.
238impl<'de, T: SecretValue> Deserialize<'de> for Secret<T> {
239    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
240        // Not serde's error, which would quote what was there instead: a
241        // value written where a secret goes may be the secret.
242        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            /// Declare a secret by name. `const` so it can initialize a
266            /// module-scope `static`; nothing is resolved until its value is
267            /// asked for.
268            pub const fn new(name: &'static str) -> Self {
269                Self(Inner::new(name, $scope))
270            }
271
272            /// The name the secret was declared with.
273            pub const fn name(&self) -> &'static str {
274                self.0.name
275            }
276
277            /// The secret's current value: see [`Value`].
278            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    /// A secret belonging to the service that declares it, which holds its own
295    /// value for it. Must be declared inside a service.
296    Secret,
297    Scope::Service
298);
299
300secret_type!(
301    /// A secret with one value for the whole app. A service that reads it is
302    /// granted access to it.
303    SharedSecret,
304    Scope::App
305);
306
307secret_type!(
308    /// A secret with one value for the whole app, available to every service
309    /// without being granted.
310    GlobalSecret,
311    Scope::App
312);
313
314mod sealed {
315    /// Who a secret belongs to.
316    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
317    pub enum Scope {
318        /// One value for the app, held in the shared namespace: a
319        /// `SharedSecret` or a `GlobalSecret`.
320        App,
321        /// The declaring service's own: a `Secret`.
322        Service,
323    }
324
325    pub trait Sealed {
326        fn key(&self) -> (Scope, &'static str);
327    }
328}
329
330/// Any of the secret types, whatever its value's type. Sealed: [`Secret`],
331/// [`SharedSecret`] and [`GlobalSecret`] are the only ones.
332pub trait AnySecret: sealed::Sealed {}
333
334/// The scope and name a secret is held under.
335pub(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        // The placeholder's scope says which namespace it is read from.
351        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        // The same name read again is the same interned string.
359        let again: Secret = serde_json::from_value(placeholder).unwrap();
360        assert!(std::ptr::eq(secret.name(), again.name()));
361
362        // A value is no placeholder.
363        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        // Clones share it.
376        let clone = value.clone();
377        assert!(Arc::ptr_eq(&value.0, &clone.0));
378        assert_eq!(format!("{value:?}"), "Value(<secret>)");
379    }
380}