encore-dev 2.0.0-beta.18

Rust SDK for Encore applications
Documentation
//! Application secrets, declared at module scope and resolved from the runtime.
//!
//! ```no_run
//! use encore::secrets::Secret;
//!
//! static API_KEY: Secret = Secret::new("ApiKey");
//!
//! fn authorization() -> String {
//!     format!("Bearer {}", *API_KEY.value())
//! }
//! ```
//!
//! # Scope
//!
//! A secret's declaration determines which services own and can access it:
//!
//! - `Secret::new("ApiKey")` is private to the service that declares it. Two
//!   services can each declare a secret with the same name and hold different
//!   values, so adding a secret to one service never collides with or silently
//!   reuses another service's secret. Service-scoped secrets must be declared
//!   inside a service.
//! - `Secret::new("ApiKey").shared()` has a single value for the entire
//!   application. Any service can declare it, and Encore grants access to each
//!   service that reads it.
//! - `Secret::new("ApiKey").global()` has a single value for the entire
//!   application and is available to every service without per-service grants.
//!
//! Because Encore parses both the name and scope statically from source code,
//! write them directly in the declaration.
//!
//! # Values
//!
//! [`Secret::value`] returns a [`Value`], a lightweight handle that dereferences
//! to the underlying secret value and is cheap to clone. Each secret is read
//! once per process and does not change while the process runs; updated values
//! take effect on restart.
//!
//! Locally (under `encore run` and `encore test`), an unset secret evaluates to
//! the type's default value (`""`), the same as an empty string. This lets you
//! check `if API_KEY.value().is_empty()` to skip optional integrations that are
//! not configured locally.
//!
//! In all other environments, reading an unset secret panics — as does reading a
//! secret whose value cannot be loaded or is not valid UTF-8. Because the panic
//! occurs on read, only the request or task that accesses the secret fails. The
//! panic message includes the secret's name, never its value.
//!
//! Currently, `String` is the only supported secret value type.
//!
//! # In a config
//!
//! A [config](crate::config) struct can include a secret field by annotating it
//! with the secret name: `#[config(secret = "StripeKey")] api_key: Secret`. The
//! secret inherits the config's scope and is declared in code like any other
//! secret. The config value itself never contains the secret; calling
//! [`Secret::value`] on the field reads the secret at runtime.
//!
//! # Tests
//!
//! Under `encore test`, a test can override a secret's value for itself without
//! affecting other tests using
//! [`testing::set_secret`](crate::testing::set_secret).

use std::collections::HashSet;
use std::fmt;
use std::ops::Deref;
use std::sync::{Arc, Mutex, OnceLock};

use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::runtime::core;
use crate::testing;

/// A type that a secret value can be decoded into.
///
/// Currently implemented only for `String`. This trait is sealed.
pub trait SecretValue: sealed::Read + Default + Sized + Send + Sync + 'static {}

impl SecretValue for String {}

impl sealed::Read for String {
    fn read(name: &str, bytes: &[u8]) -> Self {
        match std::str::from_utf8(bytes) {
            Ok(text) => text.to_string(),
            // Never include the bytes in the message: they may contain the secret.
            Err(_) => panic!("secret {name:?} is not valid UTF-8"),
        }
    }
}

/// A handle to a secret's value.
///
/// Dereferences directly to `T` (so you can use `&*value` or call `T`'s methods
/// directly) and is cheap to clone because clones share the underlying value.
/// Its [`Debug`](fmt::Debug) implementation redacts the contents.
pub struct Value<T>(Arc<T>);

impl<T> Deref for Value<T> {
    type Target = T;

    fn deref(&self) -> &T {
        &self.0
    }
}

impl<T> Clone for Value<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T> fmt::Debug for Value<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Value(<secret>)")
    }
}

/// An application secret declared as a module-level `static`.
///
/// See the [module documentation](self) for details on scoping and resolution.
///
/// [`Secret::new`] declares a secret scoped to the declaring service, while
/// [`Secret::shared`] and [`Secret::global`] scope it across the application.
/// Encore reads the scope statically from source code.
pub struct Secret<T: SecretValue = String> {
    name: &'static str,
    /// The runtime's value, read at first use.
    value: OnceLock<Arc<T>>,
}

impl<T: SecretValue> Secret<T> {
    /// Declares a secret by name.
    ///
    /// This function is `const` so it can initialize a module-level `static`;
    /// the secret value is not resolved until [`Secret::value`] is called.
    /// `name` must be a string literal so Encore can parse it statically.
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            value: OnceLock::new(),
        }
    }

    /// Scopes the secret to the entire application instead of only the
    /// declaring service.
    ///
    /// Any service may declare the secret, and each service that reads it is
    /// granted access. See [Scope](self#scope).
    pub const fn shared(self) -> Self {
        self
    }

    /// Scopes the secret to the entire application and makes it available to
    /// every service without per-service grants. See [Scope](self#scope).
    pub const fn global(self) -> Self {
        self
    }

    /// Adds a human-readable description for the secret (such as what it is for,
    /// who issues it, and how to rotate it), displayed wherever secret values
    /// are managed.
    ///
    /// `_description` must be a string literal so Encore can parse it
    /// statically. If the `static` declaration also has a doc comment, the doc
    /// comment takes precedence.
    ///
    /// ```no_run
    /// # use encore::secrets::Secret;
    /// static API_KEY: Secret = Secret::new("ApiKey")
    ///     .description("Issued by Acme Pay. Rotate it in their portal.");
    /// ```
    pub const fn description(self, _description: &'static str) -> Self {
        self
    }

    /// Attaches a key/value classification tag (such as `.tag("data", "pci")`)
    /// for policy evaluation.
    ///
    /// Call `.tag` once per tag with unique keys. Both arguments must be string
    /// literals so Encore can parse them statically. Keys must start with a
    /// lowercase letter, contain only lowercase letters, digits, `_`, and `-`,
    /// and must not start with `encore` (reserved for Encore's own tags).
    /// Values use the same character set or may be empty. Each key and value
    /// may be at most 63 characters, and a secret may have at most 32 tags.
    ///
    /// This method takes `self` by value so it can only be used as part of the
    /// `static` declaration.
    ///
    /// ```no_run
    /// # use encore::secrets::Secret;
    /// static API_KEY: Secret = Secret::new("ApiKey").tag("data", "pci");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// Returns the name the secret was declared with.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// Returns a handle to the secret's value.
    ///
    /// Locally (`encore run`, `encore test`), an unset secret returns the
    /// default value (`""`). See [`Value`].
    ///
    /// # Panics
    ///
    /// Panics if the secret is unset in a non-local environment
    /// (`secret "ApiKey" is not set`), if its value cannot be read
    /// (`secret "ApiKey" could not be read: …`), or if the value is not valid
    /// UTF-8 (`secret "ApiKey" is not valid UTF-8`).
    pub fn value(&self) -> Value<T> {
        // A test's own value for the secret, if it set one. A thread that is no
        // test's reads the app's, like any other code.
        if let Some(test) = testing::active().ok().flatten() {
            if let Some(bytes) = test.secret(self.name) {
                return Value(Arc::new(T::read(self.name, &bytes)));
            }
        }

        let value = self.value.get_or_init(|| {
            // A name has one scope across the app, so the lookup is by name.
            let secrets = core().secrets();
            let Some(secret) = secrets.get(self.name.into()) else {
                // Unset locally: it reads as one set empty.
                if secrets.unset_reads_empty() {
                    return Arc::new(T::default());
                }
                panic!("secret {:?} is not set", self.name);
            };
            let bytes = secret
                .get()
                .unwrap_or_else(|err| panic!("secret {:?} could not be read: {err}", self.name));
            Arc::new(T::read(self.name, bytes))
        });
        Value(value.clone())
    }
}

/// Where a secret field goes in a config's value: the runtime puts this
/// placeholder there, naming the secret the type says the field reads.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Placeholder {
    // `encore_sdk_core::config::PLACEHOLDER_KEY`, checked in the tests. The
    // secret's name: a name has one scope across the app.
    #[serde(rename = "$encore_secret")]
    secret: String,
}

/// The `'static` name a deserialized secret is declared with. Interned, so the
/// same names read in every new config value are kept once.
fn intern(name: String) -> &'static str {
    static NAMES: OnceLock<Mutex<HashSet<&'static str>>> = OnceLock::new();
    let mut names = NAMES
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    match names.get(name.as_str()) {
        Some(interned) => interned,
        None => {
            let interned: &'static str = Box::leak(name.into_boxed_str());
            names.insert(interned);
            interned
        }
    }
}

/// Deserializes a secret field in a [config](crate::config) from the runtime
/// placeholder naming the secret.
///
/// The secret inherits the config's scope (a service config reads that
/// service's secret, while a shared or global config reads an app-level
/// secret).
impl<'de, T: SecretValue> Deserialize<'de> for Secret<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Avoid serde's default error, which could quote a raw secret value
        // accidentally placed in config.
        let placeholder = Placeholder::deserialize(deserializer).map_err(|_| {
            D::Error::custom("a secret field reads a secret, and is not set in config")
        })?;
        if placeholder.secret.is_empty() {
            return Err(D::Error::custom(
                "secret field placeholder must specify a secret name",
            ));
        }
        Ok(Self::new(intern(placeholder.secret)))
    }
}

/// Serializes a config's secret field back as its placeholder (never its value),
/// so [`testing::set_config`] can strip secret fields from typed config values.
impl<T: SecretValue> Serialize for Secret<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap as _;
        let mut map = serializer.serialize_map(Some(1))?;
        map.serialize_entry(encore_sdk_core::config::PLACEHOLDER_KEY, self.name)?;
        map.end()
    }
}

mod sealed {
    /// Decodes a secret's value from raw bytes, panicking with the secret's
    /// name (never its bytes) if decoding fails.
    pub trait Read {
        fn read(name: &str, bytes: &[u8]) -> Self;
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_secret_field_reads_its_placeholder() {
        assert_eq!(encore_sdk_core::config::PLACEHOLDER_KEY, "$encore_secret");
        let placeholder = serde_json::json!({"$encore_secret": "StripeKey"});
        let secret: Secret = serde_json::from_value(placeholder.clone()).unwrap();
        assert_eq!(secret.name(), "StripeKey");

        // The same name read again is the same interned string.
        let again: Secret = serde_json::from_value(placeholder).unwrap();
        assert!(std::ptr::eq(secret.name(), again.name()));

        // A value is no placeholder.
        let err = serde_json::from_value::<Secret>(serde_json::json!("sk_live"))
            .err()
            .unwrap();
        assert!(err.to_string().contains("not set in config"), "{err}");
        assert!(!err.to_string().contains("sk_live"), "{err}");
        // Nor is a placeholder of another shape.
        for other in [
            serde_json::json!({"$encore_secret": {"name": "StripeKey", "scope": "shared"}}),
            serde_json::json!({"$encore_secret": ""}),
        ] {
            assert!(serde_json::from_value::<Secret>(other).is_err());
        }
    }

    #[test]
    fn the_scope_is_the_declarations_and_the_name_says_which_secret() {
        static OWN: Secret = Secret::new("ApiKey");
        static SHARED: Secret = Secret::new("ApiKey").shared();
        static GLOBAL: Secret = Secret::new("ApiKey").global();
        for secret in [&OWN, &SHARED, &GLOBAL] {
            assert_eq!(secret.name(), "ApiKey");
        }
    }

    #[test]
    fn a_string_is_read_from_the_secrets_bytes() {
        assert_eq!(
            <String as sealed::Read>::read("ApiKey", b"hunter2"),
            "hunter2"
        );
    }

    #[test]
    fn bytes_that_are_not_utf8_panic_without_saying_what_they_were() {
        let bytes = [0xff, b'h', b'u', b'n', b't', b'e', b'r'];
        let panic = std::panic::catch_unwind(|| <String as sealed::Read>::read("ApiKey", &bytes))
            .unwrap_err();
        let message = panic.downcast_ref::<String>().unwrap();
        assert_eq!(message, r#"secret "ApiKey" is not valid UTF-8"#);
    }

    #[test]
    fn a_value_reads_as_what_it_holds_and_does_not_print_it() {
        let value = Value(Arc::new("hunter2".to_string()));
        assert_eq!(*value, "hunter2");
        assert!(value.starts_with("hunter"));
        // Clones share it.
        let clone = value.clone();
        assert!(Arc::ptr_eq(&value.0, &clone.0));
        assert_eq!(format!("{value:?}"), "Value(<secret>)");
    }
}