rullst-orm 13.0.0-alpha.2

Fast, un-opinionated, database-agnostic ORM and query builder for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use aes_gcm::{
    Aes256Gcm,
    aead::{Aead, Generate, KeyInit, Nonce, Payload},
};
use base64::{
    Engine as _,
    engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD},
};

const ENVELOPE_PREFIX: &str = "RULLST";
const ENVELOPE_VERSION: &str = "v2";
const DEFAULT_KEY_ID: &str = "default";
const KEY_LENGTH: usize = 32;
const NONCE_LENGTH: usize = 12;
const TAG_LENGTH: usize = 16;
const MAX_KEY_ID_LENGTH: usize = 128;
const AAD_DOMAIN: &[u8] = b"rullst-orm:field-encryption:aes-256-gcm";
const KEY_ENV: &str = "RULLST_ENCRYPTION_KEY";
const KEY_ID_ENV: &str = "RULLST_ENCRYPTION_KEY_ID";
const KEYRING_ENV: &str = "RULLST_ENCRYPTION_KEYRING";

mod secret_serde;
#[doc(hidden)]
pub use secret_serde::with_redacted_secrets;
pub use secret_serde::{deserialize_optional_plaintext_secret, deserialize_plaintext_secret};
mod settings;
mod sqlx_codec;

/// A decrypted secret whose `Debug` output and serde form never contain the
/// plaintext.
///
/// SQLx encoding/decoding encrypts and decrypts the column value. `Serialize`
/// emits an authenticated `RULLST:v2` envelope under the configured
/// `RULLST_ENCRYPTION_KEY` (and fails without one); `Deserialize` decrypts such
/// an envelope and still accepts any other string as plaintext input.
/// Because the envelope binds no model, field or owner, `Deserialize` is for
/// trusted stores only: deserialize client input with
/// [`deserialize_plaintext_secret`] or [`deserialize_optional_plaintext_secret`].
/// Generated ORM audit, event and search projections serialize it as `"***"`.
/// Use [`SecretString::reveal_audited`] for deliberate exposure.
#[derive(Clone, PartialEq, Eq)]
pub struct SecretString(String);

impl SecretString {
    pub fn new(val: impl Into<String>) -> Self {
        SecretString(val.into())
    }

    /// Reveals the real value only when explicitly requested.
    /// In a real implementation, this might take an `AuditLogToken` to log the access.
    pub fn reveal_audited(&self) -> &str {
        &self.0
    }
}

// In standard debug, it should never leak.
impl std::fmt::Debug for SecretString {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("[ENCRYPTED_SECRET]")
    }
}

/// Compliance metadata generated by `#[derive(PersonalData)]`.
pub struct PrivacyReport {
    /// The model's table: `#[orm(table = "...")]`, else the ORM's `<struct>s`
    /// default.
    pub table_name: String,
    /// Whether any persisted field is encrypted at rest.
    pub has_encrypted_data: bool,
    /// Persisted `#[orm(encrypted)]` and `SecretString` fields. A `#[privacy]`
    /// tag only redacts `Debug`; see [`ComplianceModel::personal_fields`].
    pub encrypted_fields: Vec<&'static str>,
}

pub trait ComplianceModel {
    fn compliance_schema() -> PrivacyReport;

    /// The fields the application declared as personal data with
    /// `#[privacy]` on `#[derive(PersonalData)]`; empty by default.
    /// Added in v13.
    fn personal_fields() -> Vec<&'static str> {
        Vec::new()
    }
}

/// Strongly-typed error domain for Rullst ORM privacy and column encryption.
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PrivacyError {
    /// The encryption key is missing or not exactly 32 bytes long.
    #[error("RULLST_ENCRYPTION_KEY must be exactly 32 bytes long")]
    InvalidKeyLength,

    /// A prefixed base64 or hexadecimal key could not be decoded.
    #[error("RULLST_ENCRYPTION_KEY has invalid {0} encoding")]
    InvalidKeyEncoding(&'static str),

    /// A key identifier was empty, too long, or contained an envelope delimiter.
    #[error("Invalid field-encryption key identifier")]
    InvalidKeyId,

    /// A versioned encrypted value did not contain the required fields.
    #[error("Invalid field-encryption envelope")]
    InvalidEnvelope,

    /// The encrypted value belongs to an unknown future format.
    #[error("Unsupported field-encryption envelope version: {0}")]
    UnsupportedEnvelopeVersion(String),

    /// The configured keyring does not contain the key selected by the envelope.
    #[error("Field-encryption key `{0}` was not found in the configured keyring")]
    KeyNotFound(String),

    /// The operating system could not provide a cryptographically secure nonce.
    #[error("Operating-system randomness is unavailable")]
    RandomnessUnavailable,

    /// AES-GCM encryption failed.
    #[error("Encryption failed: {0}")]
    EncryptionFailed(String),

    /// AES-GCM decryption failed.
    #[error("Decryption failed: {0}")]
    DecryptionFailed(String),

    /// The payload is shorter than the 12-byte nonce requirement.
    #[error("Invalid encrypted payload (too short)")]
    PayloadTooShort,

    /// Base64 decoding failed.
    #[error("Base64 decode error: {0}")]
    Base64Error(String),

    /// Decrypted payload is not valid UTF-8.
    #[error("UTF-8 decoding error: {0}")]
    Utf8Error(String),

    /// Missing environment variable key.
    #[error("Environment variable error: {0}")]
    EnvError(String),
}

fn validate_key(key: &[u8]) -> Result<(), PrivacyError> {
    if key.len() == KEY_LENGTH {
        Ok(())
    } else {
        Err(PrivacyError::InvalidKeyLength)
    }
}

fn validate_key_id(key_id: &str) -> Result<(), PrivacyError> {
    if key_id.is_empty()
        || key_id.len() > MAX_KEY_ID_LENGTH
        || !key_id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
    {
        Err(PrivacyError::InvalidKeyId)
    } else {
        Ok(())
    }
}

fn authenticated_data(key_id: &str, context: &[u8]) -> Vec<u8> {
    let mut aad = Vec::with_capacity(AAD_DOMAIN.len() + key_id.len() + context.len() + 4);
    aad.extend_from_slice(AAD_DOMAIN);
    aad.push(0);
    aad.extend_from_slice(ENVELOPE_VERSION.as_bytes());
    aad.push(0);
    aad.extend_from_slice(key_id.as_bytes());
    aad.push(0);
    aad.extend_from_slice(context);
    aad
}

fn model_context(table: &str, column: &str) -> Vec<u8> {
    let mut context = Vec::with_capacity(table.len() + column.len() + 1);
    context.extend_from_slice(table.as_bytes());
    context.push(0);
    context.extend_from_slice(column.as_bytes());
    context
}

fn encrypt_with_context(
    plaintext: &str,
    key: &[u8],
    key_id: &str,
    context: &[u8],
) -> Result<String, PrivacyError> {
    validate_key(key)?;
    validate_key_id(key_id)?;
    let cipher = Aes256Gcm::new_from_slice(key)
        .map_err(|error| PrivacyError::EncryptionFailed(error.to_string()))?;
    let nonce =
        Nonce::<Aes256Gcm>::try_generate().map_err(|_| PrivacyError::RandomnessUnavailable)?;
    let aad = authenticated_data(key_id, context);
    let ciphertext = cipher
        .encrypt(
            &nonce,
            Payload {
                msg: plaintext.as_bytes(),
                aad: &aad,
            },
        )
        .map_err(|error| PrivacyError::EncryptionFailed(error.to_string()))?;

    Ok(format!(
        "{ENVELOPE_PREFIX}:{ENVELOPE_VERSION}:{key_id}:{}:{}",
        URL_SAFE_NO_PAD.encode(nonce),
        URL_SAFE_NO_PAD.encode(ciphertext)
    ))
}

struct ParsedEnvelope<'a> {
    key_id: &'a str,
    nonce: Vec<u8>,
    ciphertext: Vec<u8>,
}

fn parse_envelope(encrypted: &str) -> Result<ParsedEnvelope<'_>, PrivacyError> {
    let mut fields = encrypted.split(':');
    if fields.next() != Some(ENVELOPE_PREFIX) {
        return Err(PrivacyError::InvalidEnvelope);
    }
    let version = fields.next().ok_or(PrivacyError::InvalidEnvelope)?;
    if version != ENVELOPE_VERSION {
        return Err(PrivacyError::UnsupportedEnvelopeVersion(
            version.to_string(),
        ));
    }
    let key_id = fields.next().ok_or(PrivacyError::InvalidEnvelope)?;
    validate_key_id(key_id)?;
    let encoded_nonce = fields.next().ok_or(PrivacyError::InvalidEnvelope)?;
    let encoded_ciphertext = fields.next().ok_or(PrivacyError::InvalidEnvelope)?;
    if fields.next().is_some() {
        return Err(PrivacyError::InvalidEnvelope);
    }

    let nonce = URL_SAFE_NO_PAD
        .decode(encoded_nonce)
        .map_err(|error| PrivacyError::Base64Error(error.to_string()))?;
    if nonce.len() != NONCE_LENGTH {
        return Err(PrivacyError::PayloadTooShort);
    }
    let ciphertext = URL_SAFE_NO_PAD
        .decode(encoded_ciphertext)
        .map_err(|error| PrivacyError::Base64Error(error.to_string()))?;
    if ciphertext.len() < TAG_LENGTH {
        return Err(PrivacyError::PayloadTooShort);
    }

    Ok(ParsedEnvelope {
        key_id,
        nonce,
        ciphertext,
    })
}

fn decrypt_envelope(
    envelope: &ParsedEnvelope<'_>,
    key: &[u8],
    context: &[u8],
) -> Result<String, PrivacyError> {
    validate_key(key)?;
    let cipher = Aes256Gcm::new_from_slice(key)
        .map_err(|error| PrivacyError::DecryptionFailed(error.to_string()))?;
    let nonce = Nonce::<Aes256Gcm>::try_from(envelope.nonce.as_slice())
        .map_err(|error| PrivacyError::DecryptionFailed(error.to_string()))?;
    let aad = authenticated_data(envelope.key_id, context);
    let plaintext = cipher
        .decrypt(
            &nonce,
            Payload {
                msg: &envelope.ciphertext,
                aad: &aad,
            },
        )
        .map_err(|error| PrivacyError::DecryptionFailed(error.to_string()))?;
    String::from_utf8(plaintext).map_err(|error| PrivacyError::Utf8Error(error.to_string()))
}

fn current_key_id() -> Result<String, PrivacyError> {
    match settings::setting(KEY_ID_ENV)? {
        Some(key_id) => {
            validate_key_id(&key_id)?;
            Ok(key_id)
        }
        None => Ok(DEFAULT_KEY_ID.to_string()),
    }
}

fn decode_configured_key(value: &str) -> Result<Vec<u8>, PrivacyError> {
    let key = if let Some(encoded) = value.strip_prefix("base64:") {
        STANDARD
            .decode(encoded)
            .map_err(|_| PrivacyError::InvalidKeyEncoding("base64"))?
    } else if let Some(encoded) = value.strip_prefix("hex:") {
        let (pairs, remainder) = encoded.as_bytes().as_chunks::<2>();
        if !remainder.is_empty() {
            return Err(PrivacyError::InvalidKeyEncoding("hex"));
        }
        pairs
            .iter()
            .map(|pair| {
                let pair = std::str::from_utf8(pair)
                    .map_err(|_| PrivacyError::InvalidKeyEncoding("hex"))?;
                u8::from_str_radix(pair, 16).map_err(|_| PrivacyError::InvalidKeyEncoding("hex"))
            })
            .collect::<Result<Vec<_>, _>>()?
    } else {
        value.as_bytes().to_vec()
    };
    validate_key(&key)?;
    Ok(key)
}

fn current_key() -> Result<Vec<u8>, PrivacyError> {
    decode_configured_key(&settings::required_setting(KEY_ENV)?)
}

fn parse_keyring(
    keyring: &str,
) -> Result<serde_json::Map<String, serde_json::Value>, PrivacyError> {
    serde_json::from_str(keyring).map_err(|error| {
        PrivacyError::EnvError(format!(
            "{KEYRING_ENV} must be a JSON object of key IDs to 32-byte keys: {error}"
        ))
    })
}

fn configured_key(key_id: &str) -> Result<Vec<u8>, PrivacyError> {
    if current_key_id()? == key_id {
        return current_key();
    }

    let values = parse_keyring(&settings::required_setting(KEYRING_ENV)?)?;
    let key = values
        .get(key_id)
        .and_then(serde_json::Value::as_str)
        .ok_or_else(|| PrivacyError::KeyNotFound(key_id.to_string()))?
        .to_string();
    decode_configured_key(&key)
}

/// Decrypts a pre-v12 value, which names no key: the current key first, then
/// the `RULLST_ENCRYPTION_KEYRING` keys (`default`, the implicit ID of those
/// values, before the others), so legacy rows stay readable after rotation.
/// AES-GCM authentication rejects every key but the one that wrote the value.
fn decrypt_legacy_configured(encrypted: &str) -> Result<String, PrivacyError> {
    let rejected = match decrypt_legacy_aes_gcm(encrypted, &current_key()?) {
        Err(error @ PrivacyError::DecryptionFailed(_)) => error,
        other => return other,
    };
    let Some(keyring) = settings::setting(KEYRING_ENV)? else {
        return Err(rejected);
    };
    let values = parse_keyring(&keyring)?;
    let candidates = values.get(DEFAULT_KEY_ID).into_iter().chain(
        values
            .iter()
            .filter(|(key_id, _)| key_id.as_str() != DEFAULT_KEY_ID)
            .map(|(_, key)| key),
    );
    for candidate in candidates {
        let key = candidate.as_str().ok_or_else(|| {
            PrivacyError::EnvError(format!("{KEYRING_ENV} values must be key strings"))
        })?;
        match decrypt_legacy_aes_gcm(encrypted, &decode_configured_key(key)?) {
            Err(PrivacyError::DecryptionFailed(_)) => continue,
            other => return other,
        }
    }
    Err(rejected)
}

/// Encrypts an ORM model field using the configured current key and an
/// authenticated table/column context.
///
/// `RULLST_ENCRYPTION_KEY`, `RULLST_ENCRYPTION_KEY_ID` and
/// `RULLST_ENCRYPTION_KEYRING` are each read from the process environment,
/// then from `./.env` (never loaded into the process environment).
pub fn encrypt_model_field(
    plaintext: &str,
    table: &str,
    column: &str,
) -> Result<String, PrivacyError> {
    let key_id = current_key_id()?;
    let key = current_key()?;
    encrypt_with_context(plaintext, &key, &key_id, &model_context(table, column))
}

/// Decrypts an ORM model field and selects its key from the configured current
/// key or `RULLST_ENCRYPTION_KEYRING` JSON object.
pub fn decrypt_model_field(
    encrypted: &str,
    table: &str,
    column: &str,
) -> Result<String, PrivacyError> {
    let envelope = parse_envelope(encrypted)?;
    let key = configured_key(envelope.key_id)?;
    decrypt_envelope(&envelope, &key, &model_context(table, column))
}

pub fn encrypt_aes_gcm(plaintext: &str, key: &str) -> Result<String, PrivacyError> {
    encrypt_with_context(plaintext, key.as_bytes(), DEFAULT_KEY_ID, b"")
}

pub fn decrypt_aes_gcm(encrypted: &str, key: &str) -> Result<String, PrivacyError> {
    let key_bytes = key.as_bytes();
    validate_key(key_bytes)?;
    if encrypted.starts_with(&format!("{ENVELOPE_PREFIX}:")) {
        let envelope = parse_envelope(encrypted)?;
        return decrypt_envelope(&envelope, key_bytes, b"");
    }

    decrypt_legacy_aes_gcm(encrypted, key_bytes)
}

fn decrypt_legacy_aes_gcm(encrypted: &str, key: &[u8]) -> Result<String, PrivacyError> {
    // v12 reads the pre-v12 nonce+ciphertext base64 representation so existing
    // `SecretString` rows can be loaded and rewritten into the versioned format.
    let payload = STANDARD
        .decode(encrypted)
        .map_err(|error| PrivacyError::Base64Error(error.to_string()))?;
    if payload.len() < NONCE_LENGTH + TAG_LENGTH {
        return Err(PrivacyError::PayloadTooShort);
    }

    let cipher = Aes256Gcm::new_from_slice(key)
        .map_err(|error| PrivacyError::DecryptionFailed(error.to_string()))?;
    let nonce = Nonce::<Aes256Gcm>::try_from(&payload[..NONCE_LENGTH])
        .map_err(|error| PrivacyError::DecryptionFailed(error.to_string()))?;
    let ciphertext = &payload[NONCE_LENGTH..];

    let plaintext = cipher
        .decrypt(&nonce, ciphertext)
        .map_err(|error| PrivacyError::DecryptionFailed(error.to_string()))?;

    String::from_utf8(plaintext).map_err(|error| PrivacyError::Utf8Error(error.to_string()))
}

fn encrypt_configured_secret(plaintext: &str) -> Result<String, PrivacyError> {
    let key_id = current_key_id()?;
    let key = current_key()?;
    encrypt_with_context(plaintext, &key, &key_id, b"")
}

fn decrypt_configured_secret(encrypted: &str) -> Result<String, PrivacyError> {
    if encrypted.starts_with(&format!("{ENVELOPE_PREFIX}:")) {
        let envelope = parse_envelope(encrypted)?;
        let key = configured_key(envelope.key_id)?;
        decrypt_envelope(&envelope, &key, b"")
    } else {
        decrypt_legacy_configured(encrypted)
    }
}

#[cfg(test)]
mod tests;