encore-dev 2.0.0-beta.21

Rust SDK for Encore applications
Documentation
//! Secrets in a runtime that is not local: a deploy gives each service every
//! secret it uses, so one with no value fails where it is read. Its own test
//! binary, as the runtime config is read once per process.

use std::sync::Once;

use encore::secrets::Secret;
use encore_runtimecfg::pb;

/// Points the runtime at a deployment on AWS before anything starts it.
fn setup() {
    static SETUP: Once = Once::new();
    SETUP.call_once(|| {
        let cfg = pb::RuntimeConfig {
            environment: Some(pb::Environment {
                app_id: "app".into(),
                env_name: "prod".into(),
                cloud: pb::environment::Cloud::Aws as i32,
                ..Default::default()
            }),
            deployment: Some(pb::Deployment {
                hosted_services: vec![pb::HostedService {
                    name: "orders".into(),
                    ..Default::default()
                }],
                ..Default::default()
            }),
            infra: Some(pb::Infrastructure {
                resources: Some(pb::infrastructure::Resources {
                    app_secrets: vec![pb::AppSecret {
                        rid: "secret:StripeKey".into(),
                        encore_name: "StripeKey".into(),
                        data: Some(pb::SecretData {
                            source: Some(pb::secret_data::Source::Embedded(
                                b"sk_live_123".to_vec(),
                            )),
                            sub_path: None,
                            encoding: pb::secret_data::Encoding::None as i32,
                        }),
                        services: vec!["*".into()],
                    }],
                    ..Default::default()
                }),
                ..Default::default()
            }),
            ..Default::default()
        };
        // Before any thread reads the environment: every test comes here first.
        std::env::set_var(
            "ENCORE_RUNTIME_CONFIG",
            encore_runtimecfg::encoding::encode_env_value(&cfg),
        );
    });
}

#[test]
fn a_secret_with_a_value_reads_as_it() {
    setup();
    static STRIPE_KEY: Secret = Secret::new("StripeKey").global();
    assert_eq!(*STRIPE_KEY.value(), "sk_live_123");
}

#[test]
fn a_secret_with_no_value_panics_naming_it() {
    setup();
    static MISSING: Secret = Secret::new("NotGiven").global();
    let panic = std::panic::catch_unwind(|| MISSING.value()).unwrap_err();
    let message = panic.downcast_ref::<String>().unwrap();
    assert_eq!(message, r#"secret "NotGiven" is not set"#);
}