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