Smeltery
Get started

Security

v0.1

Encryption and random tokens

smeltery::crypto holds the helpers every part of Smeltery uses: random_token(len) (letters and digits from the OS random source, every character equally likely), random_bytes(len), sha256_hex(text) and constant_time_eq(a, b) (compares two secrets of equal length in constant time).

app.derive_key(purpose) is a 32-byte key derived from APP_KEY for purpose: HMAC-SHA256 of APP_KEY over smeltery-app-key:<purpose>, a label that no signature (app.sign) and no key the framework uses for its own messages share, so none of them is ever such a key. Every purpose gives an unrelated key; Smeltery's own crates use dotted purposes (anvil.secret), so plain names are free for apps. app.encrypt(purpose, aad, plaintext) encrypts and authenticates a value with AES-256-GCM under a key of its own for purpose (HMAC-SHA256 of APP_KEY over smeltery-app-enc:<purpose>, never a derive_key key, so a derived key handed out for a purpose never opens values encrypted under it) and a random 96-bit nonce, as base64 of nonce, ciphertext and tag. aad is authenticated but not stored: app.decrypt(purpose, aad, &sealed) returns Ok(Some(plaintext)) only for the same purpose, aad and APP_KEY, and Ok(None) for anything edited, truncated or sealed otherwise. Both fail without a usable APP_KEY. Pass the id of the record a secret belongs to as aad, so a value copied to another row does not open there:

rust
use smeltery::prelude::*;

fn seal_secret(app: &App, user_id: i64, secret: &str) -> Result<String> {
    app.encrypt("api-secrets", user_id.to_string().as_bytes(), secret.as_bytes())
}

fn open_secret(app: &App, user_id: i64, sealed: &str) -> Result<Option<String>> {
    Ok(app
        .decrypt("api-secrets", user_id.to_string().as_bytes(), sealed)?
        .and_then(|bytes| String::from_utf8(bytes).ok()))
}

Rotating APP_KEY makes every encrypted value unreadable.

↑↓ moveEnter openEsc close