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() -> String {
9//!     format!("Bearer {}", *API_KEY.value())
10//! }
11//! ```
12//!
13//! # Scope
14//!
15//! A secret's declaration determines which services own and can access it:
16//!
17//! - `Secret::new("ApiKey")` is private to the service that declares it. Two
18//!   services can each declare a secret with the same name and hold different
19//!   values, so adding a secret to one service never collides with or silently
20//!   reuses another service's secret. Service-scoped secrets must be declared
21//!   inside a service.
22//! - `Secret::new("ApiKey").shared()` has a single value for the entire
23//!   application. Any service can declare it, and Encore grants access to each
24//!   service that reads it.
25//! - `Secret::new("ApiKey").global()` has a single value for the entire
26//!   application and is available to every service without per-service grants.
27//!
28//! Because Encore parses both the name and scope statically from source code,
29//! write them directly in the declaration.
30//!
31//! # Values
32//!
33//! [`Secret::value`] returns a [`Value`], a lightweight handle that dereferences
34//! to the underlying secret value and is cheap to clone. Each secret is read
35//! once per process and does not change while the process runs; updated values
36//! take effect on restart.
37//!
38//! Locally (under `encore run` and `encore test`), an unset secret evaluates to
39//! the type's default value (`""`), the same as an empty string. This lets you
40//! check `if API_KEY.value().is_empty()` to skip optional integrations that are
41//! not configured locally.
42//!
43//! In all other environments, reading an unset secret panics — as does reading a
44//! secret whose value cannot be loaded or is not valid UTF-8. Because the panic
45//! occurs on read, only the request or task that accesses the secret fails. The
46//! panic message includes the secret's name, never its value.
47//!
48//! Currently, `String` is the only supported secret value type.
49//!
50//! # In a config
51//!
52//! A [config](crate::config) struct can include a secret field by annotating it
53//! with the secret name: `#[config(secret = "StripeKey")] api_key: Secret`. The
54//! secret inherits the config's scope and is declared in code like any other
55//! secret. The config value itself never contains the secret; calling
56//! [`Secret::value`] on the field reads the secret at runtime.
57//!
58//! # Tests
59//!
60//! Under `encore test`, a test can override a secret's value for itself without
61//! affecting other tests using
62//! [`testing::set_secret`](crate::testing::set_secret).
63
64use std::collections::HashSet;
65use std::fmt;
66use std::ops::Deref;
67use std::sync::{Arc, Mutex, OnceLock};
68
69use serde::de::Error as _;
70use serde::{Deserialize, Deserializer, Serialize, Serializer};
71
72use crate::runtime::core;
73use crate::testing;
74
75/// A type that a secret value can be decoded into.
76///
77/// Currently implemented only for `String`. This trait is sealed.
78pub trait SecretValue: sealed::Read + Default + Sized + Send + Sync + 'static {}
79
80impl SecretValue for String {}
81
82impl sealed::Read for String {
83    fn read(name: &str, bytes: &[u8]) -> Self {
84        match std::str::from_utf8(bytes) {
85            Ok(text) => text.to_string(),
86            // Never include the bytes in the message: they may contain the secret.
87            Err(_) => panic!("secret {name:?} is not valid UTF-8"),
88        }
89    }
90}
91
92/// A handle to a secret's value.
93///
94/// Dereferences directly to `T` (so you can use `&*value` or call `T`'s methods
95/// directly) and is cheap to clone because clones share the underlying value.
96/// Its [`Debug`](fmt::Debug) implementation redacts the contents.
97pub struct Value<T>(Arc<T>);
98
99impl<T> Deref for Value<T> {
100    type Target = T;
101
102    fn deref(&self) -> &T {
103        &self.0
104    }
105}
106
107impl<T> Clone for Value<T> {
108    fn clone(&self) -> Self {
109        Self(self.0.clone())
110    }
111}
112
113impl<T> fmt::Debug for Value<T> {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str("Value(<secret>)")
116    }
117}
118
119/// An application secret declared as a module-level `static`.
120///
121/// See the [module documentation](self) for details on scoping and resolution.
122///
123/// [`Secret::new`] declares a secret scoped to the declaring service, while
124/// [`Secret::shared`] and [`Secret::global`] scope it across the application.
125/// Encore reads the scope statically from source code.
126pub struct Secret<T: SecretValue = String> {
127    name: &'static str,
128    /// The runtime's value, read at first use.
129    value: OnceLock<Arc<T>>,
130}
131
132impl<T: SecretValue> Secret<T> {
133    /// Declares a secret by name.
134    ///
135    /// This function is `const` so it can initialize a module-level `static`;
136    /// the secret value is not resolved until [`Secret::value`] is called.
137    /// `name` must be a string literal so Encore can parse it statically.
138    pub const fn new(name: &'static str) -> Self {
139        Self {
140            name,
141            value: OnceLock::new(),
142        }
143    }
144
145    /// Scopes the secret to the entire application instead of only the
146    /// declaring service.
147    ///
148    /// Any service may declare the secret, and each service that reads it is
149    /// granted access. See [Scope](self#scope).
150    pub const fn shared(self) -> Self {
151        self
152    }
153
154    /// Scopes the secret to the entire application and makes it available to
155    /// every service without per-service grants. See [Scope](self#scope).
156    pub const fn global(self) -> Self {
157        self
158    }
159
160    /// Adds a human-readable description for the secret (such as what it is for,
161    /// who issues it, and how to rotate it), displayed wherever secret values
162    /// are managed.
163    ///
164    /// `_description` must be a string literal so Encore can parse it
165    /// statically. If the `static` declaration also has a doc comment, the doc
166    /// comment takes precedence.
167    ///
168    /// ```no_run
169    /// # use encore::secrets::Secret;
170    /// static API_KEY: Secret = Secret::new("ApiKey")
171    ///     .description("Issued by Acme Pay. Rotate it in their portal.");
172    /// ```
173    pub const fn description(self, _description: &'static str) -> Self {
174        self
175    }
176
177    /// Attaches a key/value classification tag (such as `.tag("data", "pci")`)
178    /// for policy evaluation.
179    ///
180    /// Call `.tag` once per tag with unique keys. Both arguments must be string
181    /// literals so Encore can parse them statically. Keys must start with a
182    /// lowercase letter, contain only lowercase letters, digits, `_`, and `-`,
183    /// and must not start with `encore` (reserved for Encore's own tags).
184    /// Values use the same character set or may be empty. Each key and value
185    /// may be at most 63 characters, and a secret may have at most 32 tags.
186    ///
187    /// This method takes `self` by value so it can only be used as part of the
188    /// `static` declaration.
189    ///
190    /// ```no_run
191    /// # use encore::secrets::Secret;
192    /// static API_KEY: Secret = Secret::new("ApiKey").tag("data", "pci");
193    /// ```
194    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
195        self
196    }
197
198    /// Returns the name the secret was declared with.
199    pub const fn name(&self) -> &'static str {
200        self.name
201    }
202
203    /// Returns a handle to the secret's value.
204    ///
205    /// Locally (`encore run`, `encore test`), an unset secret returns the
206    /// default value (`""`). See [`Value`].
207    ///
208    /// # Panics
209    ///
210    /// Panics if the secret is unset in a non-local environment
211    /// (`secret "ApiKey" is not set`), if its value cannot be read
212    /// (`secret "ApiKey" could not be read: …`), or if the value is not valid
213    /// UTF-8 (`secret "ApiKey" is not valid UTF-8`).
214    pub fn value(&self) -> Value<T> {
215        // A test's own value for the secret, if it set one. A thread that is no
216        // test's reads the app's, like any other code.
217        if let Some(test) = testing::active().ok().flatten()
218            && let Some(bytes) = test.secret(self.name)
219        {
220            return Value(Arc::new(T::read(self.name, &bytes)));
221        }
222
223        let value = self.value.get_or_init(|| {
224            // A name has one scope across the app, so the lookup is by name.
225            let secrets = core().secrets();
226            let Some(secret) = secrets.get(self.name.into()) else {
227                // Unset locally: it reads as one set empty.
228                if secrets.unset_reads_empty() {
229                    return Arc::new(T::default());
230                }
231                panic!("secret {:?} is not set", self.name);
232            };
233            let bytes = secret
234                .get()
235                .unwrap_or_else(|err| panic!("secret {:?} could not be read: {err}", self.name));
236            Arc::new(T::read(self.name, bytes))
237        });
238        Value(value.clone())
239    }
240}
241
242/// Where a secret field goes in a config's value: the runtime puts this
243/// placeholder there, naming the secret the type says the field reads.
244#[derive(Deserialize)]
245#[serde(deny_unknown_fields)]
246struct Placeholder {
247    // `encore_sdk_core::config::PLACEHOLDER_KEY`, checked in the tests. The
248    // secret's name: a name has one scope across the app.
249    #[serde(rename = "$encore_secret")]
250    secret: String,
251}
252
253/// The `'static` name a deserialized secret is declared with. Interned, so the
254/// same names read in every new config value are kept once.
255fn intern(name: String) -> &'static str {
256    static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
257    let mut names = NAMES
258        .get_or_init(Default::default)
259        .lock()
260        .unwrap_or_else(|e| e.into_inner());
261    match names.get(name.as_str()) {
262        Some(interned) => interned,
263        None => {
264            let interned: &'static str = Box::leak(name.into_boxed_str());
265            names.insert(interned);
266            interned
267        }
268    }
269}
270
271/// Deserializes a secret field in a [config](crate::config) from the runtime
272/// placeholder naming the secret.
273///
274/// The secret inherits the config's scope (a service config reads that
275/// service's secret, while a shared or global config reads an app-level
276/// secret).
277impl<'de, T: SecretValue> Deserialize<'de> for Secret<T> {
278    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
279        // Avoid serde's default error, which could quote a raw secret value
280        // accidentally placed in config.
281        let placeholder = Placeholder::deserialize(deserializer).map_err(|_| {
282            D::Error::custom("a secret field reads a secret, and is not set in config")
283        })?;
284        if placeholder.secret.is_empty() {
285            return Err(D::Error::custom(
286                "secret field placeholder must specify a secret name",
287            ));
288        }
289        Ok(Self::new(intern(placeholder.secret)))
290    }
291}
292
293/// Serializes a config's secret field back as its placeholder (never its value),
294/// so [`testing::set_config`] can strip secret fields from typed config values.
295impl<T: SecretValue> Serialize for Secret<T> {
296    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
297        use serde::ser::SerializeMap as _;
298        let mut map = serializer.serialize_map(Some(1))?;
299        map.serialize_entry(encore_sdk_core::config::PLACEHOLDER_KEY, self.name)?;
300        map.end()
301    }
302}
303
304mod sealed {
305    /// Decodes a secret's value from raw bytes, panicking with the secret's
306    /// name (never its bytes) if decoding fails.
307    pub trait Read {
308        fn read(name: &str, bytes: &[u8]) -> Self;
309    }
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn a_secret_field_reads_its_placeholder() {
318        assert_eq!(encore_sdk_core::config::PLACEHOLDER_KEY, "$encore_secret");
319        let placeholder = serde_json::json!({"$encore_secret": "StripeKey"});
320        let secret: Secret = serde_json::from_value(placeholder.clone()).unwrap();
321        assert_eq!(secret.name(), "StripeKey");
322
323        // The same name read again is the same interned string.
324        let again: Secret = serde_json::from_value(placeholder).unwrap();
325        assert!(std::ptr::eq(secret.name(), again.name()));
326
327        // A value is no placeholder.
328        let err = serde_json::from_value::<Secret>(serde_json::json!("sk_live"))
329            .err()
330            .unwrap();
331        assert!(err.to_string().contains("not set in config"), "{err}");
332        assert!(!err.to_string().contains("sk_live"), "{err}");
333        // Nor is a placeholder of another shape.
334        for other in [
335            serde_json::json!({"$encore_secret": {"name": "StripeKey", "scope": "shared"}}),
336            serde_json::json!({"$encore_secret": ""}),
337        ] {
338            assert!(serde_json::from_value::<Secret>(other).is_err());
339        }
340    }
341
342    #[test]
343    fn the_scope_is_the_declarations_and_the_name_says_which_secret() {
344        static OWN: Secret = Secret::new("ApiKey");
345        static SHARED: Secret = Secret::new("ApiKey").shared();
346        static GLOBAL: Secret = Secret::new("ApiKey").global();
347        for secret in [&OWN, &SHARED, &GLOBAL] {
348            assert_eq!(secret.name(), "ApiKey");
349        }
350    }
351
352    #[test]
353    fn a_string_is_read_from_the_secrets_bytes() {
354        assert_eq!(
355            <String as sealed::Read>::read("ApiKey", b"hunter2"),
356            "hunter2"
357        );
358    }
359
360    #[test]
361    fn bytes_that_are_not_utf8_panic_without_saying_what_they_were() {
362        let bytes = [0xff, b'h', b'u', b'n', b't', b'e', b'r'];
363        let panic = std::panic::catch_unwind(|| <String as sealed::Read>::read("ApiKey", &bytes))
364            .unwrap_err();
365        let message = panic.downcast_ref::<String>().unwrap();
366        assert_eq!(message, r#"secret "ApiKey" is not valid UTF-8"#);
367    }
368
369    #[test]
370    fn a_value_reads_as_what_it_holds_and_does_not_print_it() {
371        let value = Value(Arc::new("hunter2".to_string()));
372        assert_eq!(*value, "hunter2");
373        assert!(value.starts_with("hunter"));
374        // Clones share it.
375        let clone = value.clone();
376        assert!(Arc::ptr_eq(&value.0, &clone.0));
377        assert_eq!(format!("{value:?}"), "Value(<secret>)");
378    }
379}