encore-dev 2.0.0-beta.7

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() -> Result<String, encore::Error> {
//!     Ok(format!("Bearer {}", *API_KEY.value()?))
//! }
//! ```
//!
//! # Scope
//!
//! Which of the three types a secret is declared with says who it belongs to:
//!
//! - A [`Secret`] 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.
//! - A [`SharedSecret`] has one value for the whole app. Any service may
//!   declare it, and each that reads it is granted access to it.
//! - A [`GlobalSecret`] has one value for the whole app and is available to
//!   every service, without being granted.
//!
//! # Values
//!
//! [`Secret::value`] returns a [`Value`]: a handle to the secret's current
//! value, cheap to make and to clone, which reads as the value itself. A
//! secret's value can change while the app runs; a handle keeps the value it
//! was made with, and the next call to `value` gives the new one. So take a
//! handle where the value is used, rather than keeping one.
//!
//! A secret is a `String` unless its type says otherwise: `Secret<Vec<u8>>`
//! for bytes, `Secret<Json<T>>` for a value stored as JSON.
//!
//! # 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, RwLock};

use encore_sdk_core::secrets as core_secrets;
use serde::de::{DeserializeOwned, Error as _};
use serde::{Deserialize, Deserializer};

use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::testing;

/// A type a secret's value can be read as.
pub trait SecretValue: Sized + Send + Sync + 'static {
    /// Reads the value from the secret's bytes.
    fn from_bytes(bytes: &[u8]) -> Result<Self, Error>;
}

impl SecretValue for String {
    fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        String::from_utf8(bytes.to_vec())
            .map_err(|_| Error::new(ErrCode::Internal, "the secret's value is not valid UTF-8"))
    }
}

impl SecretValue for Vec<u8> {
    fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        Ok(bytes.to_vec())
    }
}

/// A secret value stored as JSON: `Secret<Json<Credentials>>`. Reads as the
/// `T` inside.
pub struct Json<T>(pub T);

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

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

impl<T: DeserializeOwned + Send + Sync + 'static> SecretValue for Json<T> {
    fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
        // The error says where the JSON is wrong, never what it holds.
        serde_json::from_slice(bytes).map(Json).map_err(|e| {
            Error::new(
                ErrCode::Internal,
                format!(
                    "the secret's value is not the JSON expected: {:?} at line {} column {}",
                    e.classify(),
                    e.line(),
                    e.column()
                ),
            )
        })
    }
}

/// A handle to a secret's value, as it was when the handle was made. 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>)")
    }
}

pub(crate) use sealed::Scope;

/// A secret's name and scope, and its value as last read: what the three
/// secret types are.
struct Inner<T> {
    name: &'static str,
    scope: Scope,
    /// The value, with the runtime's secret it was read from: the runtime
    /// gives a secret a new one when its value changes.
    current: RwLock<Option<(Arc<core_secrets::Secret>, Arc<T>)>>,
}

impl<T: SecretValue> Inner<T> {
    const fn new(name: &'static str, scope: Scope) -> Self {
        Self {
            name,
            scope,
            current: RwLock::new(None),
        }
    }

    fn value(&self) -> Result<Value<T>, Error> {
        // 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.scope, self.name) {
                return T::from_bytes(&bytes).map(|value| Value(Arc::new(value)));
            }
        }

        // A name has one scope across the app, so the lookup is by name.
        let secret = core().secrets().get(self.name.into()).ok_or_else(|| {
            Error::not_found(format!(
                "secret {:?} is not configured for this service",
                self.name
            ))
        })?;

        let current = self.current.read().unwrap_or_else(|e| e.into_inner());
        if let Some((read_from, value)) = current.as_ref() {
            if Arc::ptr_eq(read_from, &secret) {
                return Ok(Value(value.clone()));
            }
        }
        drop(current);

        let bytes = secret
            .get()
            .map_err(|e| Error::wrap(ErrCode::Internal, e))?;
        let value = Arc::new(T::from_bytes(bytes)?);
        *self.current.write().unwrap_or_else(|e| e.into_inner()) = Some((secret, value.clone()));
        Ok(Value(value))
    }
}

/// 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.
    #[serde(rename = "$encore_secret")]
    secret: PlaceholderSecret,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PlaceholderSecret {
    name: String,
    scope: 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 and its scope — the config's own:
/// a service's own config reads that service's secret, a shared or global
/// config one of the app's. 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")
        })?;
        let scope = match placeholder.secret.scope.as_str() {
            "service" => Scope::Service,
            "shared" | "global" => Scope::App,
            other => {
                return Err(D::Error::custom(format!(
                    "the secret {:?} has no scope {other:?}",
                    placeholder.secret.name
                )))
            }
        };
        Ok(Self(Inner::new(intern(placeholder.secret.name), scope)))
    }
}

macro_rules! secret_type {
    ($(#[$doc:meta])* $name:ident, $scope:expr) => {
        $(#[$doc])*
        pub struct $name<T = String>(Inner<T>);

        impl<T: SecretValue> $name<T> {
            /// Declare a secret by name. `const` so it can initialize a
            /// module-scope `static`; nothing is resolved until its value is
            /// asked for.
            pub const fn new(name: &'static str) -> Self {
                Self(Inner::new(name, $scope))
            }

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

            /// The secret's current value: see [`Value`].
            pub fn value(&self) -> Result<Value<T>, Error> {
                self.0.value()
            }
        }

        impl<T> sealed::Sealed for $name<T> {
            fn key(&self) -> (Scope, &'static str) {
                (self.0.scope, self.0.name)
            }
        }

        impl<T> AnySecret for $name<T> {}
    };
}

secret_type!(
    /// A secret belonging to the service that declares it, which holds its own
    /// value for it. Must be declared inside a service.
    Secret,
    Scope::Service
);

secret_type!(
    /// A secret with one value for the whole app. A service that reads it is
    /// granted access to it.
    SharedSecret,
    Scope::App
);

secret_type!(
    /// A secret with one value for the whole app, available to every service
    /// without being granted.
    GlobalSecret,
    Scope::App
);

mod sealed {
    /// Who a secret belongs to.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub enum Scope {
        /// One value for the app, held in the shared namespace: a
        /// `SharedSecret` or a `GlobalSecret`.
        App,
        /// The declaring service's own: a `Secret`.
        Service,
    }

    pub trait Sealed {
        fn key(&self) -> (Scope, &'static str);
    }
}

/// Any of the secret types, whatever its value's type. Sealed: [`Secret`],
/// [`SharedSecret`] and [`GlobalSecret`] are the only ones.
pub trait AnySecret: sealed::Sealed {}

/// The scope and name a secret is held under.
pub(crate) fn key_of(secret: &impl AnySecret) -> (Scope, &'static str) {
    secret.key()
}

#[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": {"name": "StripeKey", "scope": "shared"}});
        let secret: Secret = serde_json::from_value(placeholder.clone()).unwrap();
        assert_eq!(secret.name(), "StripeKey");
        // The placeholder's scope says which namespace it is read from.
        assert_eq!(key_of(&secret), (Scope::App, "StripeKey"));
        let own: Secret = serde_json::from_value(
            serde_json::json!({"$encore_secret": {"name": "StripeKey", "scope": "service"}}),
        )
        .unwrap();
        assert_eq!(key_of(&own), (Scope::Service, "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}");
    }

    #[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>)");
    }
}