glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Encrypted columns: stored as ciphertext, read as plain text. Hidden
//! columns: never in JSON.

use glacier::db::migration::{Migration, Schema};
use glacier::db::{self, Repo};
use glacier::prelude::*;

#[glacier::model]
pub struct Account {
    email: String,
    #[glacier(encrypted)]
    otp_secret: Option<String>,
    #[glacier(encrypted)]
    note: String,
    token_digest: Option<String>,
    #[glacier(hidden)]
    api_key: Option<String>,
}

fn schema(s: &mut Schema) {
    s.create_table("accounts", |t| {
        t.string("email").not_null();
        t.string("otp_secret");
        t.text("note").not_null();
        t.string("token_digest");
        t.string("api_key");
        t.timestamps();
    });
}

/// The tests install different keys, which are process-wide: one at a time.
static KEYS: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

async fn stored(column: &str) -> Vec<Option<String>> {
    db::sql(&format!("SELECT {column} FROM accounts ORDER BY id"))
        .fetch_all()
        .await
        .unwrap()
        .iter()
        .map(|r| r.get(column).unwrap())
        .collect()
}

#[tokio::test]
async fn stores_ciphertext_and_reads_plain_text() {
    let _keys = KEYS.lock().await;
    glacier::encryption::install("a test secret for encrypted columns", &[]);
    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    db::sandbox(&repo, async {
        for statement in Migration::new("m1", schema, |_| {}).up_sql(repo.dialect()) {
            db::sql(&statement).execute().await.unwrap();
        }
        let mut account = Account::new();
        account.email = "ada@example.com".into();
        account.otp_secret = Some("JBSWY3DPEHPK3PXP".into());
        account.note = "private".into();
        assert!(account.save().await.unwrap());

        let secret = stored("otp_secret").await[0].clone().unwrap();
        assert!(secret.starts_with("gl1:"), "{secret}");
        assert!(!secret.contains("JBSWY3DPEHPK3PXP"));
        assert!(
            stored("note").await[0]
                .as_deref()
                .unwrap()
                .starts_with("gl1:")
        );
        assert_eq!(stored("email").await[0].as_deref(), Some("ada@example.com"));

        let mut found = Account::find(account.id).await.unwrap();
        assert_eq!(found.otp_secret.as_deref(), Some("JBSWY3DPEHPK3PXP"));
        assert_eq!(found.note, "private");
        // Unchanged, so not written again (a new nonce would look changed).
        assert!(found.changes().is_empty());
        found.email = "ada@example.org".into();
        assert!(found.save().await.unwrap());
        assert_eq!(
            stored("otp_secret").await[0].as_deref(),
            Some(secret.as_str())
        );

        // NULL stays NULL; a plain value from before is read as it is.
        found.otp_secret = None;
        assert!(found.save().await.unwrap());
        assert_eq!(stored("otp_secret").await[0], None);
        db::sql("UPDATE accounts SET otp_secret = 'plain'")
            .execute()
            .await
            .unwrap();
        let found = Account::find(account.id).await.unwrap();
        assert_eq!(found.otp_secret.as_deref(), Some("plain"));

        // A value the Rails app this one replaces encrypted (ActiveRecord
        // 8.1's `encrypts`), with its keys from `encryption.rails`.
        glacier::encryption::legacy::install_rails(&["test primary key"], "test salt");
        db::sql(
            r#"UPDATE accounts SET otp_secret = '{"p":"DkXCjHIod9nRdCl4lbQ9hQ==","h":{"iv":"CpMuY9YwDEA4YvGC","at":"q675ALYa604oZ/HqJnSifg=="}}'"#,
        )
        .execute()
        .await
        .unwrap();
        let mut found = Account::find(account.id).await.unwrap();
        assert_eq!(found.otp_secret.as_deref(), Some("JBSWY3DPEHPK3PXP"));
        // Changed and saved, it's encrypted the Glacier way.
        found.otp_secret = Some("NEWSECRET".into());
        assert!(found.save().await.unwrap());
        assert!(stored("otp_secret").await[0].as_deref().unwrap().starts_with("gl1:"));
    })
    .await
    .unwrap();
}

#[test]
fn hidden_columns_stay_out_of_json() {
    let account = Account {
        email: "ada@example.com".into(),
        otp_secret: Some("secret".into()),
        note: "private".into(),
        token_digest: Some("abc".into()),
        api_key: Some("key".into()),
        ..Default::default()
    };
    let shown = ["email", "id", "inserted_at", "updated_at"];
    let serde = serde_json::to_value(&account).unwrap();
    let attributes = glacier::serialize::attributes(&account);
    let schema = <Account as glacier::serialize::Schema>::schema();
    for json in [&serde, &attributes, &schema["properties"]] {
        let mut keys: Vec<&str> = json
            .as_object()
            .unwrap()
            .keys()
            .map(String::as_str)
            .collect();
        keys.sort();
        assert_eq!(keys, shown, "{json}");
    }
    assert_eq!(
        <Account as Model>::HIDDEN,
        ["otp_secret", "note", "token_digest", "api_key"]
    );
}

#[glacier::model]
pub struct Contact {
    #[validate(unique)]
    #[glacier(deterministic)]
    email: String,
}

fn contacts(s: &mut Schema) {
    s.create_table("contacts", |t| {
        t.string("email").not_null();
        t.timestamps();
    });
}

#[tokio::test]
async fn finds_deterministically_encrypted_values() {
    let _keys = KEYS.lock().await;
    glacier::encryption::install("the first secret", &[]);
    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    db::sandbox(&repo, async {
        for statement in Migration::new("m2", contacts, |_| {}).up_sql(repo.dialect()) {
            db::sql(&statement).execute().await.unwrap();
        }
        let mut ada = Contact::new();
        ada.email = "ada@example.com".into();
        assert!(ada.save().await.unwrap());

        let stored: String = db::sql("SELECT email FROM contacts")
            .fetch_all()
            .await
            .unwrap()[0]
            .get("email")
            .unwrap();
        assert!(stored.starts_with("gl1d:"), "{stored}");
        assert_eq!(
            stored,
            glacier::encryption::encrypt_deterministic("ada@example.com").unwrap(),
            "the same text, the same way"
        );

        let found = Contact::filter(|c| c.email.eq_field("ada@example.com"))
            .first()
            .await
            .unwrap()
            .unwrap();
        assert_eq!(found.email, "ada@example.com");
        let none = Contact::filter(|c| c.email.eq_field("bob@example.com"))
            .first()
            .await;
        assert!(none.unwrap().is_none());

        // `unique` compares the stored values too.
        let mut again = Contact::new();
        again.email = "ada@example.com".into();
        assert!(!again.save().await.unwrap());

        // After the key changes, rows written with the old one are found.
        glacier::encryption::install("the second secret", &["the first secret".to_owned()]);
        let found = Contact::filter(|c| c.email.eq_field("ada@example.com"))
            .first()
            .await
            .unwrap();
        assert!(found.is_some());
    })
    .await
    .unwrap();
}