use crate::error::{GarrisonError, GarrisonResult};
use aes_gcm::aead::{Aead, Nonce, Payload};
use aes_gcm::{Aes256Gcm, Key, KeyInit};
use base64::{engine::general_purpose::STANDARD, Engine};
pub const CRYPTO_VALUE_PREFIX: &str = "enc:v1:";
pub const KEY_LEN: usize = 32;
#[cfg(test)]
pub(crate) const fn test_key(seed: u8) -> [u8; KEY_LEN] {
let mut k = [0u8; KEY_LEN];
let mut i = 0;
while i < KEY_LEN {
k[i] = seed.wrapping_add(i as u8);
i += 1;
}
k
}
pub const NONCE_LEN: usize = 12;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AadBinding {
pub tenant: String,
pub table: String,
pub key: String,
}
impl AadBinding {
pub fn new(
tenant: impl Into<String>,
table: impl Into<String>,
key: impl Into<String>,
) -> Self {
Self {
tenant: tenant.into(),
table: table.into(),
key: key.into(),
}
}
fn aad_bytes(&self) -> Vec<u8> {
format!("garrison:{}:{}:{}", self.tenant, self.table, self.key).into_bytes()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CryptoValue {
pub key_id: String,
pub nonce: [u8; NONCE_LEN],
pub ciphertext: Vec<u8>,
}
impl CryptoValue {
pub const PREFIX: &str = CRYPTO_VALUE_PREFIX;
pub fn seal(
key_id: &str,
key: &[u8; KEY_LEN],
aad: &AadBinding,
plaintext: &[u8],
) -> GarrisonResult<Self> {
validate_key_id(key_id, "seal")?;
let mut nonce = [0u8; NONCE_LEN];
getrandom::fill(&mut nonce).unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("secure-csprng-unavailable", &[],)
)
});
let cipher = Aes256Gcm::new(key_view(key));
let ciphertext = cipher
.encrypt(
nonce_view(&nonce),
Payload {
msg: plaintext,
aad: &aad.aad_bytes(),
},
)
.map_err(|e| GarrisonError::Internal(format!("secure-field-encryption-seal::{e}")))?;
Ok(Self {
key_id: key_id.to_string(),
nonce,
ciphertext,
})
}
pub fn open(&self, key: &[u8; KEY_LEN], aad: &AadBinding) -> GarrisonResult<Vec<u8>> {
let cipher = Aes256Gcm::new(key_view(key));
cipher
.decrypt(
nonce_view(&self.nonce),
Payload {
msg: &self.ciphertext,
aad: &aad.aad_bytes(),
},
)
.map_err(|_| {
GarrisonError::Internal(
"secure-field-encryption-open::aad-or-key-or-tag-mismatch".to_string(),
)
})
}
pub fn encode(&self) -> String {
let mut payload = Vec::with_capacity(NONCE_LEN + self.ciphertext.len());
payload.extend_from_slice(&self.nonce);
payload.extend_from_slice(&self.ciphertext);
format!(
"{}{}:{}",
CRYPTO_VALUE_PREFIX,
self.key_id,
STANDARD.encode(payload)
)
}
pub fn decode(encoded: &str) -> GarrisonResult<Self> {
let rest = encoded
.strip_prefix(CRYPTO_VALUE_PREFIX)
.ok_or_else(|| decode_err("missing-enc-v1-prefix"))?;
let (key_id, payload_b64) = rest
.split_once(':')
.ok_or_else(|| decode_err("missing-key-id-segment"))?;
validate_key_id(key_id, "decode")?;
if payload_b64.is_empty() {
return Err(decode_err("empty-payload"));
}
let payload = STANDARD
.decode(payload_b64)
.map_err(|e| decode_err(&format!("base64:{}", e)))?;
if payload.len() < NONCE_LEN + 16 {
return Err(decode_err(&format!(
"payload-too-short:len={}",
payload.len()
)));
}
let mut nonce = [0u8; NONCE_LEN];
nonce.copy_from_slice(&payload[..NONCE_LEN]);
Ok(Self {
key_id: key_id.to_string(),
nonce,
ciphertext: payload[NONCE_LEN..].to_vec(),
})
}
}
pub(crate) fn validate_key_id(key_id: &str, op: &str) -> GarrisonResult<()> {
if key_id.is_empty() {
return Err(op_err(op, "empty-key-id"));
}
if key_id.contains(':') {
return Err(op_err(op, "key-id-contains-colon"));
}
Ok(())
}
fn decode_err(detail: &str) -> GarrisonError {
GarrisonError::Internal(format!("secure-field-encryption-decode::{detail}"))
}
fn op_err(op: &str, detail: &str) -> GarrisonError {
GarrisonError::Internal(format!("secure-field-encryption-{op}::{detail}"))
}
fn key_view(key: &[u8; KEY_LEN]) -> &Key<Aes256Gcm> {
key.as_slice().try_into().unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("secure-aes-key-len-static", &[],)
)
})
}
fn nonce_view(nonce: &[u8; NONCE_LEN]) -> &Nonce<Aes256Gcm> {
nonce.as_slice().try_into().unwrap_or_else(|e| {
panic!(
"{}: {e}",
crate::i18n::translate_detail("secure-gcm-nonce-len-static", &[],)
)
})
}
#[cfg(test)]
mod tests {
use super::*;
const KEY: [u8; KEY_LEN] = test_key(7);
const OTHER_KEY: [u8; KEY_LEN] = test_key(9);
fn row_aad(row: &str) -> AadBinding {
AadBinding::new("tenant-1", "oauth2:atoken", row)
}
#[test]
fn roundtrip_preserves_plaintext() {
let v1 = CryptoValue::seal("k1", &KEY, &row_aad("row-1"), b"secret-value").unwrap();
let decoded = CryptoValue::decode(&v1.encode()).unwrap();
let plaintext = decoded.open(&KEY, &row_aad("row-1")).unwrap();
assert_eq!(plaintext, b"secret-value");
let v2 = CryptoValue::seal("k1", &KEY, &row_aad("row-1"), b"secret-value").unwrap();
assert_ne!(v1.nonce, v2.nonce, "每值 nonce 必须独立随机");
}
#[test]
fn ciphertext_moved_to_other_row_fails() {
let v = CryptoValue::seal("k1", &KEY, &row_aad("row-1"), b"secret-value").unwrap();
let decoded = CryptoValue::decode(&v.encode()).unwrap();
let moved_row = decoded.open(&KEY, &row_aad("row-2")).unwrap_err();
assert!(matches!(moved_row, GarrisonError::Internal(_)));
let moved_table =
decoded.open(&KEY, &AadBinding::new("tenant-1", "oauth2:client", "row-1"));
assert!(moved_table.is_err());
let moved_tenant =
decoded.open(&KEY, &AadBinding::new("tenant-2", "oauth2:atoken", "row-1"));
assert!(moved_tenant.is_err());
}
#[test]
fn wrong_key_material_fails() {
let v = CryptoValue::seal("k1", &KEY, &row_aad("row-1"), b"secret-value").unwrap();
let err = v.open(&OTHER_KEY, &row_aad("row-1")).unwrap_err();
assert!(matches!(err, GarrisonError::Internal(_)));
}
#[test]
fn encode_format_matches_spec() {
let plaintext = b"secret-value";
let v = CryptoValue::seal("k1", &KEY, &row_aad("row-1"), plaintext).unwrap();
let encoded = v.encode();
assert!(encoded.starts_with("enc:v1:"));
let rest = encoded.strip_prefix("enc:v1:").unwrap();
let (key_id, payload_b64) = rest.split_once(':').unwrap();
assert_eq!(key_id, "k1");
use base64::Engine as _;
let payload = STANDARD.decode(payload_b64).unwrap();
assert_eq!(payload.len(), NONCE_LEN + plaintext.len() + 16);
assert_eq!(&payload[..NONCE_LEN], &v.nonce);
}
#[test]
fn decode_rejects_malformed_values() {
let valid = CryptoValue::seal("k1", &KEY, &row_aad("row-1"), b"x")
.unwrap()
.encode();
assert!(CryptoValue::decode("plain-text-value").is_err());
assert!(CryptoValue::decode("enc:v2:k1:AAAA").is_err());
assert!(CryptoValue::decode("enc:v1::AAAA").is_err());
assert!(CryptoValue::decode("enc:v1:k:1:AAAA").is_err());
assert!(CryptoValue::decode("enc:v1:k1:not-base64!!!").is_err());
assert!(CryptoValue::decode("enc:v1:k1:AAAA").is_err());
assert!(CryptoValue::decode(&valid).is_ok());
}
#[test]
fn seal_rejects_invalid_key_id() {
assert!(CryptoValue::seal("", &KEY, &row_aad("r"), b"x").is_err());
assert!(CryptoValue::seal("k:1", &KEY, &row_aad("r"), b"x").is_err());
}
}