encore-dev 2.0.0-beta.9

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
//!
//! How a secret is declared says who it belongs to:
//!
//! - `Secret::new("ApiKey")` belongs to the service that declares it. Two
//!   services may each declare one of the same name and hold different values
//!   in them, so adding a secret to one service can never collide with — or
//!   silently reuse — a name another already took. It must be declared inside
//!   a service.
//! - `Secret::new("ApiKey").shared()` has one value for the whole app. Any
//!   service may declare it, and each that reads it is granted access to it.
//! - `Secret::new("ApiKey").global()` has one value for the whole app and is
//!   available to every service, without being granted.
//!
//! The scope is written out in the declaration, as the name is: Encore reads
//! both from the source.
//!
//! # Values
//!
//! [`Secret::value`] returns a [`Value`]: a handle to the secret's value,
//! cheap to make and to clone, which reads as the value itself. A secret's
//! value is read once per process and does not change while it runs: a new
//! value reaches a service when it restarts.
//!
//! A secret with no value panics when it is read, as does one whose value is
//! not valid UTF-8: only the request or task that reads it fails. The message
//! names the secret, never its value.
//!
//! A secret is a `String`, the only type a secret can be read as for now.
//!
//! # In a config
//!
//! A field of a [config](crate::config) type may be a secret, naming the
//! secret it reads: `#[config(secret = "StripeKey")] api_key: Secret`. The
//! secret has the config's own scope, and is declared in code as any other.
//! The config's value never holds it; reading the field reads the secret,
//! with `value` as for any other.
//!
//! # Tests
//!
//! Under `encore test` a test can give a secret a value of its own, which no
//! other test sees: [`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 a secret's value can be read as: only `String`, for now. Sealed.
pub trait SecretValue: sealed::Read + 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 what the bytes were: they may be most of the secret.
            Err(_) => panic!("secret {name:?} is not valid UTF-8"),
        }
    }
}

/// A handle to a secret's value. Reads as the value: `&*value`, or any of its
/// methods directly.
///
/// Cheap to clone: the clones share the value. It does not print it: its
/// `Debug` says only that it is a secret.
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>)")
    }
}

/// A secret, declared as a module-level `static`: its name, and its value
/// once read. See the [module documentation](self).
///
/// `new` declares a secret of the service that declares it;
/// [`shared`](Self::shared) and [`global`](Self::global) make it the whole
/// app's. The scope is the declaration's, which Encore reads from the source:
/// a name has one scope across the app, so the value is looked up by name.
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> {
    /// Declare a secret by name. `const` so it can initialize a module-scope
    /// `static`; nothing is resolved until its value is asked for. The name
    /// must be a string literal: Encore reads it from the source.
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            value: OnceLock::new(),
        }
    }

    /// Makes the secret one value for the whole app, rather than the
    /// declaring service's own. Any service may declare it, and each that
    /// reads it is granted access to it. See [scope](self#scope).
    pub const fn shared(self) -> Self {
        self
    }

    /// Makes the secret one value for the whole app, available to every
    /// service without being granted. See [scope](self#scope).
    pub const fn global(self) -> Self {
        self
    }

    /// Documents the secret: what it is, who issues it and how to rotate it,
    /// shown wherever its values are managed. Read by Encore's parser, so it
    /// must be a string literal; the declaration's doc comment wins when there
    /// is one.
    ///
    /// ```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
    }

    /// Tags the secret with `key` and `value`: key/value classification, such
    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
    /// with its own key. Encore reads them from the source, so both are string
    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
    /// a letter and not with `encore`, which is kept for Encore's own tags; a
    /// value is the same characters, or empty. Each is at most 63 characters,
    /// and a secret has at most 32 tags.
    ///
    /// Part of the declaration: it takes the secret by value, so it cannot be
    /// called on the `static`.
    ///
    /// ```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
    }

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

    /// The secret's value: see [`Value`].
    ///
    /// # Panics
    ///
    /// If the secret has no value (`secret "ApiKey" is not set`), or its 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 Some(secret) = core().secrets().get(self.name.into()) else {
                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
        }
    }
}

/// A config's secret field: read from the placeholder the runtime puts where
/// the field goes, which names the secret. Its scope is the config's own (a
/// service's own config reads that service's secret, a shared or global config
/// one of the app's), and a name has one scope across the app, so the name
/// alone says which. See the [`config`](crate::config) module.
impl<'de, T: SecretValue> Deserialize<'de> for Secret<T> {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        // Not serde's error, which would quote what was there instead: a
        // value written where a secret goes may be the secret.
        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(
                "a secret field's placeholder names no secret",
            ));
        }
        Ok(Self::new(intern(placeholder.secret)))
    }
}

/// A config's secret field written back as the placeholder it was read
/// from, never its value: what [`testing::set_config`] leaves out of a value
/// it is given, as config can't set a secret field.
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 {
    /// How a secret's value is read from its bytes. Panics, naming the
    /// secret, on bytes that are no value of the type.
    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>)");
    }
}