encore-dev 0.1.0

Rust SDK for Encore applications
Documentation
//! SharedSecret declarations and value types. Nothing here reads a secret, which
//! needs a runtime: the declarations are checked, and how a value is read from
//! a secret's bytes.

use encore::secrets::{GlobalSecret, Json, Secret, SecretValue, SharedSecret, Value};
use serde::Deserialize;

#[derive(Deserialize)]
struct Credentials {
    user: String,
    password: String,
}

// A string unless the type says otherwise.
static API_KEY: SharedSecret = SharedSecret::new("ApiKey");
static SIGNING_KEY: Secret<Vec<u8>> = Secret::new("SigningKey");
static LICENSE: GlobalSecret = GlobalSecret::new("License");
static DATABASE: SharedSecret<Json<Credentials>> = SharedSecret::new("Database");

#[test]
fn a_secret_is_declared_with_its_scope_and_type() {
    assert_eq!(API_KEY.name(), "ApiKey");
    assert_eq!(SIGNING_KEY.name(), "SigningKey");
    assert_eq!(LICENSE.name(), "License");
    assert_eq!(DATABASE.name(), "Database");
    // What `value` gives, for each.
    type Read<S, T> = fn(&S) -> Result<Value<T>, encore::Error>;
    let _: Read<SharedSecret, String> = SharedSecret::value;
    let _: Read<Secret<Vec<u8>>, Vec<u8>> = Secret::value;
    let _: Read<SharedSecret<Json<Credentials>>, Json<Credentials>> = SharedSecret::value;
}

#[test]
fn a_value_is_read_from_the_secrets_bytes() {
    assert_eq!(String::from_bytes(b"hunter2").unwrap(), "hunter2");
    assert_eq!(
        Vec::<u8>::from_bytes(&[0, 159, 146]).unwrap(),
        [0, 159, 146]
    );
    let credentials =
        Json::<Credentials>::from_bytes(br#"{"user":"ada","password":"hunter2"}"#).unwrap();
    // Reads as what is inside.
    assert_eq!(credentials.user, "ada");
    assert_eq!(credentials.password, "hunter2");
}

#[test]
fn a_value_that_cannot_be_read_does_not_say_what_it_was() {
    let err = String::from_bytes(&[0xff, b'h', b'u', b'n', b't', b'e', b'r']).unwrap_err();
    assert!(!err.message.contains("hunter"), "{err}");

    let err = match Json::<Credentials>::from_bytes(br#"{"user":"ada","password":hunter2}"#) {
        Err(err) => err,
        Ok(_) => panic!("malformed JSON was read"),
    };
    assert!(err.message.contains("column"), "{err}");
    assert!(!err.message.contains("hunter2"), "{err}");
    assert!(!err.message.contains("ada"), "{err}");
}