glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Encrypted columns: a model field declared `encrypted`
//! (`#[glacier(encrypted)]` in Rust) is stored encrypted with AES-256-GCM
//! and read back as plain text, as Rails' `encrypts` does. A leaked
//! database, backup or log of SQL shows only ciphertext.
//!
//! The key comes from the config: `encryption.key`, or else the app's
//! `secret_key_base`. To change it, put the old one in
//! `encryption.previous_keys`; values encrypted with any of them are read,
//! and saved again with the current one.
//!
//! ```toml
//! [encryption]
//! key = "…"                      # GLACIER__ENCRYPTION__KEY
//! previous_keys = ["…"]
//! ```
//!
//! Values Rails or Laravel encrypted are read too, with their keys in the
//! config (see [`legacy`]), so an app ports with its encrypted data.
//!
//! A stored value is `gl1:` and the base64 of a random nonce and the
//! ciphertext, so the same text encrypts differently each time: an
//! encrypted column can't be searched (`where(otp_secret: …)` finds
//! nothing). A value without the `gl1:` prefix is read as it is, so a
//! column can start encrypted with plain values already in it; each is
//! encrypted when its record is next saved with it changed.

use std::sync::{Arc, RwLock};

pub mod legacy;

use aes_gcm::aead::{Aead, KeyInit};
use aes_gcm::{Aes256Gcm, Nonce};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use hmac::{Hmac, Mac};
use sha2::Sha256;

use crate::db::Value;
use crate::{Error, Result};

const PREFIX: &str = "gl1:";
/// A value encrypted the same way every time, so a query can find it.
const DETERMINISTIC_PREFIX: &str = "gl1d:";
const NONCE_LEN: usize = 12;

/// The current key, then any previous ones.
static KEYS: RwLock<Option<Arc<Vec<[u8; 32]>>>> = RwLock::new(None);

/// Uses `key` (any secret text, as `secret_key_base` is) to encrypt, and it
/// and `previous` to decrypt. `App::config` calls this from the config.
pub fn install(key: &str, previous: &[String]) {
    let keys = std::iter::once(key)
        .chain(previous.iter().map(String::as_str))
        .map(derive)
        .collect();
    *KEYS.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(keys));
}

pub(crate) fn configure(config: &crate::Config) -> Result<()> {
    let key = match config.get_opt::<String>("encryption.key")? {
        Some(key) => Some(key),
        None => config.get_opt::<String>("secret_key_base")?,
    };
    if let Some(key) = key {
        let previous: Vec<String> = config
            .get_opt("encryption.previous_keys")?
            .unwrap_or_default();
        install(&key, &previous);
    }
    legacy::configure(config)
}

/// 32 bytes for AES-256 from a secret of any length, for this purpose
/// only: the same `secret_key_base` signs cookies with other keys.
fn derive(secret: &str) -> [u8; 32] {
    let mut mac = <Hmac<Sha256> as Mac>::new_from_slice(secret.as_bytes())
        .expect("HMAC takes a key of any length");
    mac.update(b"glacier column encryption");
    mac.finalize().into_bytes().into()
}

fn keys() -> Result<Arc<Vec<[u8; 32]>>> {
    KEYS.read()
        .unwrap_or_else(|e| e.into_inner())
        .clone()
        .ok_or_else(|| {
            Error::internal(
                "no key for encrypted columns: set `secret_key_base` or `encryption.key` in the config",
            )
        })
}

/// `plain`, encrypted with the current key, as it's stored.
///
/// # Errors
///
/// Without a key.
///
/// # Panics
///
/// If the system's random number generator fails.
pub fn encrypt(plain: &str) -> Result<String> {
    let keys = keys()?;
    let cipher = Aes256Gcm::new((&keys[0]).into());
    let mut nonce = [0u8; NONCE_LEN];
    getrandom::fill(&mut nonce).expect("the system's random number generator failed");
    let sealed = cipher
        .encrypt(Nonce::from_slice(&nonce), plain.as_bytes())
        .map_err(|_| Error::internal("encrypting a column failed"))?;
    let mut bytes = nonce.to_vec();
    bytes.extend(sealed);
    Ok(format!("{PREFIX}{}", STANDARD.encode(bytes)))
}

/// `plain`, encrypted the same way every time with the current key, for a
/// field declared `encrypted(deterministic)`: the nonce comes from an HMAC
/// of the text, so equal texts are stored equal and `where` finds them.
/// That shows which rows hold the same value, so keep it for what needs
/// finding, such as an email address.
///
/// # Errors
///
/// Without a key.
pub fn encrypt_deterministic(plain: &str) -> Result<String> {
    Ok(deterministic_with(&keys()?[0], plain))
}

/// `plain` encrypted deterministically with each key, current first: what
/// a query compares a deterministic column with, so rows written before a
/// key changed are still found.
pub(crate) fn deterministic_variants(plain: &str) -> Result<Vec<String>> {
    Ok(keys()?
        .iter()
        .map(|key| deterministic_with(key, plain))
        .collect())
}

fn deterministic_with(key: &[u8; 32], plain: &str) -> String {
    let mut mac =
        <Hmac<Sha256> as Mac>::new_from_slice(key).expect("HMAC takes a key of any length");
    mac.update(b"glacier deterministic|");
    mac.update(plain.as_bytes());
    let nonce: [u8; NONCE_LEN] = mac.finalize().into_bytes()[..NONCE_LEN]
        .try_into()
        .expect("a SHA-256 MAC is longer than a nonce");
    let sealed = Aes256Gcm::new(key.into())
        .encrypt(Nonce::from_slice(&nonce), plain.as_bytes())
        .expect("AES-GCM encrypts any text this size");
    let mut bytes = nonce.to_vec();
    bytes.extend(sealed);
    format!("{DETERMINISTIC_PREFIX}{}", STANDARD.encode(bytes))
}

/// A stored value as plain text: decrypted with whichever key encrypted
/// it, or as it is when it was never encrypted (no `gl1:` prefix).
///
/// # Errors
///
/// Without a key, or when no key decrypts it (it was changed, or
/// encrypted with a key that isn't in `previous_keys`).
pub fn decrypt(stored: &str) -> Result<String> {
    let Some(encoded) = stored
        .strip_prefix(PREFIX)
        .or_else(|| stored.strip_prefix(DETERMINISTIC_PREFIX))
    else {
        // Rails' or Laravel's, from the app this one was ported from, or
        // a plain value from before the column was encrypted.
        return legacy::decrypt(stored).unwrap_or_else(|| Ok(stored.to_owned()));
    };
    let bytes = STANDARD
        .decode(encoded)
        .map_err(|_| Error::internal("an encrypted column isn't base64"))?;
    if bytes.len() < NONCE_LEN {
        return Err(Error::internal("an encrypted column is too short"));
    }
    let (nonce, sealed) = bytes.split_at(NONCE_LEN);
    for key in keys()?.iter() {
        let cipher = Aes256Gcm::new(key.into());
        if let Ok(plain) = cipher.decrypt(Nonce::from_slice(nonce), sealed) {
            return String::from_utf8(plain)
                .map_err(|_| Error::internal("an encrypted column isn't UTF-8"));
        }
    }
    Err(Error::internal(
        "no key decrypts an encrypted column: was `secret_key_base` or `encryption.key` changed without adding the old one to `encryption.previous_keys`?",
    ))
}

/// A column's value as it's written: encrypted when the model declares
/// the column `encrypted`.
#[doc(hidden)]
pub fn stored<M: crate::model::Model>(column: &str, value: Value) -> Result<Value> {
    if !M::ENCRYPTED.contains(&column) {
        return Ok(value);
    }
    match value {
        Value::Null => Ok(Value::Null),
        other if M::DETERMINISTIC.contains(&column) => {
            Ok(Value::Text(encrypt_deterministic(&other.to_text())?))
        }
        other => Ok(Value::Text(encrypt(&other.to_text())?)),
    }
}

/// A query's condition with the values it compares deterministic columns
/// with encrypted, as they're stored: `where(email: …)` on an encrypted
/// email finds it. An `=` matches what any key, current or previous,
/// encrypted. Without a key the condition stays as it is, and finds
/// nothing.
pub(crate) fn query_condition<M: crate::model::Model>(expr: crate::db::Expr) -> crate::db::Expr {
    use crate::db::Expr;
    if M::DETERMINISTIC.is_empty() {
        return expr;
    }
    let variants = |value: &Value| -> Option<Vec<Value>> {
        if value.is_null() {
            return None;
        }
        let texts = deterministic_variants(&value.to_text()).ok()?;
        Some(texts.into_iter().map(Value::Text).collect())
    };
    match expr {
        Expr::Compare { column, op, value } if M::DETERMINISTIC.contains(&column) => {
            match (op, variants(&value)) {
                ("=", Some(values)) => Expr::In { column, values },
                ("!=" | "<>", Some(values)) => Expr::Not(Box::new(Expr::In { column, values })),
                _ => Expr::Compare { column, op, value },
            }
        }
        Expr::In { column, values } if M::DETERMINISTIC.contains(&column) => Expr::In {
            column,
            values: values
                .iter()
                .flat_map(|v| variants(v).unwrap_or_else(|| vec![v.clone()]))
                .collect(),
        },
        Expr::And(a, b) => Expr::And(
            Box::new(query_condition::<M>(*a)),
            Box::new(query_condition::<M>(*b)),
        ),
        Expr::Or(a, b) => Expr::Or(
            Box::new(query_condition::<M>(*a)),
            Box::new(query_condition::<M>(*b)),
        ),
        Expr::Not(inner) => Expr::Not(Box::new(query_condition::<M>(*inner))),
        other => other,
    }
}

/// An encrypted field's type, read back from its stored text: `String` or
/// `Option<String>`.
#[doc(hidden)]
pub trait Decrypted: Sized {
    fn decrypted(stored: Option<String>) -> Result<Self>;
}

impl Decrypted for String {
    fn decrypted(stored: Option<String>) -> Result<Self> {
        stored
            .map(|s| decrypt(&s))
            .unwrap_or_else(|| Ok(String::new()))
    }
}

impl Decrypted for Option<String> {
    fn decrypted(stored: Option<String>) -> Result<Self> {
        stored.map(|s| decrypt(&s)).transpose()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encrypts_and_rotates_keys() {
        install("the old secret", &[]);
        let old = encrypt("JBSWY3DPEHPK3PXP").unwrap();
        assert!(old.starts_with("gl1:"));
        assert!(!old.contains("JBSWY3DPEHPK3PXP"));
        assert_ne!(
            old,
            encrypt("JBSWY3DPEHPK3PXP").unwrap(),
            "a nonce each time"
        );
        assert_eq!(decrypt(&old).unwrap(), "JBSWY3DPEHPK3PXP");

        install("the new secret", &["the old secret".to_owned()]);
        assert_eq!(decrypt(&old).unwrap(), "JBSWY3DPEHPK3PXP");
        let new = encrypt("x").unwrap();
        install("the new secret", &[]);
        assert_eq!(decrypt(&new).unwrap(), "x");
        assert!(
            decrypt(&old)
                .unwrap_err()
                .to_string()
                .contains("previous_keys")
        );

        // Plain values from before the column was encrypted.
        assert_eq!(decrypt("plain").unwrap(), "plain");
        let mut bytes = STANDARD.decode(&new[PREFIX.len()..]).unwrap();
        bytes[NONCE_LEN] ^= 1;
        let tampered = format!("{PREFIX}{}", STANDARD.encode(bytes));
        assert!(decrypt(&tampered).is_err());
    }
}