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