Encryption
Introduction
Sometimes you need to store a secret that you'll read back later, such as a user's API token for another service. A hash won't do, because you can't get the value back from it. The dust::crypt module encrypts values with AES-256 and signs each one with a message authentication code (MAC), so a value that someone has changed fails to decrypt.
dust-framework also uses the encrypter for your cookies, including the session cookie, so your application depends on it even if you never call the module yourself.
Configuration
The encrypter uses the key in the APP_KEY variable of your .env file. The dust-framework CLI sets it when you create your application. If you don't have a .env file yet, such as after you clone your application onto another machine, run the key:generate command. It creates .env from .env.example and writes a secure random key:
dust key:generateKeep the key secret. Anyone who has it can read your encrypted values, forge your cookies, and create signed URLs that your application trusts.
Use a different key for each application and each environment, and store it in your platform's secret manager rather than in source control. Encryption protects data at rest: it does not hide a value from your own logs, from a backup made with the key, or from code that can read APP_KEY. Never log a decrypted secret, and treat the key itself as the most sensitive value in the application.
By default, dust-framework encrypts with AES-256-CBC. You can select AES-128-CBC, AES-128-GCM, or AES-256-GCM using APP_CIPHER. Configure your cipher before generating APP_KEY, since AES-128 ciphers require a shorter key. Changing the cipher later makes existing ciphertext unreadable, even with old keys listed in APP_PREVIOUS_KEYS.
Rotating your encryption key
If you change your application's key, every encrypted cookie becomes unreadable, including the session cookie, so all your users are logged out. Anything else you encrypted with the old key can't be decrypted either.
To avoid this, list your old keys in APP_PREVIOUS_KEYS, separated by commas, exactly as they were set in APP_KEY:
APP_KEY="base64:J63qRTDLub5NuZvP+kb8YIorGS6qFYHKVo6u7179stY="
APP_PREVIOUS_KEYS="base64:2nLsGFGzyoae2ax3EF2Lyq/hH6QghBGLIq5uL+Gp8/w="dust-framework always encrypts with the current key. To decrypt, it tries the current key first, then each previous key, so your users stay logged in, and the signed URLs and password reset links you've already sent keep working.
To rotate the key, copy the current APP_KEY into APP_PREVIOUS_KEYS, then generate a new key. key:generate refuses to replace a key that's already set, so pass --force:
dust key:generate --forceExisting database values remain encrypted under the old key until they are rewritten, so keep old keys in APP_PREVIOUS_KEYS until you migrate those rows. To learn how, check out Re-encrypting columns with a new key.
Using the encrypter
The dust::crypt module provides functions for encrypting and decrypting strings and serializable values directly. If you want dust-framework to handle encryption and decryption automatically on a model field, check out Encrypting model columns.
| Use | Function or type |
|---|---|
| A string you read back yourself | encrypt_string and decrypt_string |
| A struct, list, or map | encrypt and decrypt |
| A model column, handled for you | Encrypted<T> |
Encrypting a value
You may encrypt a string with encrypt_string. Suppose your users table has a nullable github_token column stored in a String field and your settings page lets users paste a GitHub token. This handler encrypts the GitHub token before storing it:
use dust::crypt;use dust::model::update;use dust::prelude::*;#[dust::input]#[validate(authenticated)]pub struct GitHubToken { #[validate(required)] token: String,}pub async fn store( Authenticated(mut user): Authenticated<User>, Valid(form): Valid<GitHubToken>,) -> dust::Result<Redirect> { let github_token = crypt::encrypt_string(&form.token)?; update!(user { github_token: Some(github_token) }).await?; Ok(Redirect::to("/settings"))}Decrypting a value
You may decrypt a value with decrypt_string. It returns an error when the value can't be decrypted, such as when someone changed it, or when it was encrypted with a key you no longer have. This handler decrypts the token that the handler above stored, to sync the user's repositories:
use dust::crypt;use dust::prelude::*;pub async fn sync(user: Authenticated<User>) -> dust::Result<Redirect> { let Some(encrypted) = &user.github_token else { return Ok(Redirect::to("/settings")); }; let Ok(token) = crypt::decrypt_string(encrypted) else { return Ok( Redirect::to("/settings") .with("status", "Please connect your GitHub account again."), ); }; // Call GitHub with the token... Ok(Redirect::to("/repositories"))}When you don't need to handle the failure, return it with crypt::decrypt_string(encrypted)?, and the request gets a server error instead.
Encrypting other types
To encrypt a value that isn't a string, such as a struct, use encrypt. It encrypts any value that implements Serialize, as JSON, and decrypt turns it back into your type. This social login callback stores the tokens GitHub issues, in a nullable github_token column:
use dust::auth::social::{self, Provider};use dust::crypt;use dust::model::update;use dust::prelude::*;pub async fn github_callback( Authenticated(mut user): Authenticated<User>,) -> dust::Result<Redirect> { let token = social::user(Provider::GITHUB).await?.token; let github_token = crypt::encrypt(token)?; update!(user { github_token: Some(github_token) }).await?; Ok(Redirect::to("/repositories"))}When you read the column back, name the type that decrypt should return:
if let Some(encrypted) = &user.github_token { let token: social::Token = crypt::decrypt(encrypted)?; // Call GitHub with token.access...}Encrypting model columns
When storing sensitive values on a model, such as a third-party API token entered on a settings page, declare the field as Encrypted<String>. dust-framework encrypts the value automatically on create and update, and decrypts it when loading the model so your application code works with plaintext while the database stores only ciphertext.
Ciphertext is longer than the value it encrypts, and its length varies, so give the column a text type in its migration, such as table.text("github_token").nullable(). Then declare the field on the model:
// src/models/user.rsuse dust::crypt::Encrypted;use dust::model::model;#[model]pub struct User { pub id: i64, pub name: String, #[serde(skip)] pub github_token: Option<Encrypted<String>>,}Like a password hash, encrypted values stay off serialized responses by default. Encrypted<T> redacts its Debug output as Encrypted([redacted]) and does not implement Serialize, so models will not compile unless the field is marked #[serde(skip)]. When a response explicitly needs the plaintext value, pass it manually.
A create or update accepts the plain value. For example, this handler stores an API token submitted from a settings form:
use dust::model::update;use dust::prelude::*;#[dust::input]#[validate(authenticated)]pub struct GitHubToken { #[validate(required)] token: String,}pub async fn store( Authenticated(mut user): Authenticated<User>, Valid(form): Valid<GitHubToken>,) -> dust::Result<Redirect> { update!(user { github_token: &form.token }).await?; Ok(Redirect::to("/settings"))}A loaded model holds the decrypted value. Encrypted<String> derefs to String (and &str) and implements AsRef<str>, so you can pass it directly to functions expecting &str or impl AsRef<str>:
use dust::http::client;use dust::prelude::*;pub async fn sync(user: Authenticated<User>) -> dust::Result<Redirect> { let Some(token) = &user.github_token else { return Ok(Redirect::to("/settings")); }; let response = client::get("https://api.github.com/user/repos") .token(token) .await?; // ... Ok(Redirect::to("/repositories"))}Loading decrypts with your current key, then with each key in APP_PREVIOUS_KEYS. When no key decrypts a value, such as one you encrypted with a key you no longer have, the query fails with an error that names the column.
Lists and structs
To encrypt a list or a map, declare the field as Encrypted<Vec<T>>, Encrypted<HashMap<K, V>>, or Encrypted<serde_json::Value>, and dust-framework encrypts its JSON. This field holds a user's two-factor recovery codes:
use dust::crypt::Encrypted;#[serde(skip)]pub recovery_codes: Option<Encrypted<Vec<String>>>,A create or an update takes the plain list, as in update!(user { recovery_codes: codes }), and the loaded field derefs to it, so user.recovery_codes.as_ref().map(|codes| codes.len()) counts the codes.
To encrypt a struct of your own, derive db::Json on it, as you would for a JSON column. Here, a project stores the URL and signing secret of a webhook it calls after each deployment:
use dust::crypt::Encrypted;use dust::db;use dust::model::{model, update};use serde::{Deserialize, Serialize};#[derive(Clone, Debug, Serialize, Deserialize, db::Json)]pub struct DeployHook { pub url: String, pub secret: String,}#[model]pub struct Project { pub id: i64, #[serde(skip)] pub deploy_hook: Option<Encrypted<DeployHook>>,}let hook = DeployHook { url, secret };update!(project { deploy_hook: hook }).await?;The social login Token type also works inside Encrypted<Token> for storing OAuth tokens. Encrypted<String> encrypts the raw string, while other types are serialized to JSON first.
Querying encrypted columns
Because encrypting the same value twice produces different ciphertexts, databases cannot filter directly by an encrypted value. As a result, typed columns like User::github_token do not expose value comparison methods (User::github_token.eq(token) will not compile), though is_null() still works on Option columns. When you need to look up a record by a secret such as an API key, store a one-way hash alongside it in a separate indexed column and query that column instead.
Re-encrypting columns with a new key
After rotating your encryption key, existing database rows remain encrypted under the old key until rewritten. Assigning the column in an update re-encrypts it with the current key, whereas leaving it unchanged skips writing. Check uses_previous_key() to identify rows that still need re-encryption before removing the old key from APP_PREVIOUS_KEYS:
use dust::console::{Console, command};use dust::model::update;use dust::stream::TryStreamExt;use crate::models::User;/// Encrypt every user's GitHub token with the current key.#[command("users:reencrypt-tokens")]pub async fn reencrypt_tokens(console: &mut Console) -> dust::Result<()> { let mut users = User::query().filter(!User::github_token.is_null()).lazy_by_id(100); while let Some(mut user) = users.try_next().await? { let Some(token) = user.github_token.clone() else { continue; }; if token.uses_previous_key() { update!(user { github_token: token.into_inner() }).await?; } } console.success("Tokens re-encrypted."); Ok(())}