#![allow(deprecated)]
use crate::manifest::{
Assertion, EncryptionInformation, EncryptionMethod, IntegrityInformation,
IntegrityInformationExt, KeyAccess, Payload, RootSignature, Segment, TDF_SPEC_VERSION,
TdfManifest,
};
use crate::policy::Policy;
use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64};
use opentdf_crypto::{EncryptionError, TdfEncryption, calculate_policy_binding};
use serde::{Deserialize, Serialize};
const GCM_NONCE_LENGTH: usize = 12;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TdfJson {
pub tdf: String,
pub version: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub created: Option<String>,
pub manifest: TdfJsonManifest,
pub payload: JsonPayload,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TdfJsonManifest {
#[serde(rename = "encryptionInformation")]
pub encryption_information: EncryptionInformation,
#[serde(skip_serializing_if = "Option::is_none")]
pub assertions: Option<Vec<Assertion>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JsonPayload {
#[serde(rename = "type")]
pub payload_type: String,
pub protocol: String,
#[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
pub mime_type: Option<String>,
#[serde(rename = "isEncrypted")]
pub is_encrypted: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub length: Option<u64>,
pub value: String,
}
#[deprecated(
since = "0.12.0",
note = "Use TdfJson instead, which follows the TDF-JSON specification. Will be removed in 1.0.0"
)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TdfJsonRpc {
pub manifest: TdfManifestInline,
pub version: String,
}
#[deprecated(
since = "0.12.0",
note = "Use TdfJsonManifest instead. Will be removed in 1.0.0"
)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TdfManifestInline {
pub payload: InlinePayload,
#[serde(rename = "encryptionInformation")]
pub encryption_information: EncryptionInformation,
#[serde(rename = "schemaVersion", skip_serializing_if = "Option::is_none")]
pub schema_version: Option<String>,
}
#[deprecated(
since = "0.12.0",
note = "Use JsonPayload instead. Will be removed in 1.0.0"
)]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InlinePayload {
#[serde(rename = "type")]
pub payload_type: String,
#[serde(rename = "mimeType")]
pub mime_type: String,
pub protocol: String,
pub value: String,
#[serde(rename = "isEncrypted")]
pub is_encrypted: bool,
}
#[cfg(feature = "kas-client")]
pub struct TdfJsonBuilder {
data: Vec<u8>,
kas_url: Option<String>,
kas_public_key_pem: Option<String>,
policy: Option<Policy>,
mime_type: Option<String>,
include_created: bool,
}
impl TdfJson {
#[cfg(feature = "kas-client")]
pub fn encrypt(data: &[u8]) -> TdfJsonBuilder {
TdfJsonBuilder {
data: data.to_vec(),
kas_url: None,
kas_public_key_pem: None,
policy: None,
mime_type: None,
include_created: true,
}
}
pub fn format_id(&self) -> &str {
&self.tdf
}
pub fn decrypt_with_key(&self, payload_key: &[u8]) -> Result<Vec<u8>, EncryptionError> {
use aes_gcm::{
Aes256Gcm, Nonce,
aead::{Aead, KeyInit},
};
let ciphertext = BASE64.decode(&self.payload.value)?;
let iv_bytes = BASE64.decode(&self.manifest.encryption_information.method.iv)?;
if iv_bytes.len() < GCM_NONCE_LENGTH {
return Err(EncryptionError::InvalidIvLength(iv_bytes.len()));
}
let payload_iv = &iv_bytes[0..GCM_NONCE_LENGTH];
let cipher = Aes256Gcm::new_from_slice(payload_key)
.map_err(|_| EncryptionError::InvalidKeyLength)?;
let nonce = Nonce::from_slice(payload_iv);
let plaintext = cipher
.decrypt(nonce, ciphertext.as_ref())
.map_err(EncryptionError::AeadError)?;
Ok(plaintext)
}
pub fn to_standard_manifest(&self) -> TdfManifest {
TdfManifest {
payload: Payload {
payload_type: "reference".to_string(),
url: "inline".to_string(),
protocol: "base64".to_string(),
is_encrypted: true,
mime_type: self.payload.mime_type.clone(),
tdf_spec_version: None,
},
encryption_information: self.manifest.encryption_information.clone(),
schema_version: Some(TDF_SPEC_VERSION.to_string()),
tdf_spec_version: None,
gguf: None,
assertions: self.manifest.assertions.clone().unwrap_or_default(),
}
}
pub fn to_bytes(&self) -> Result<Vec<u8>, serde_json::Error> {
serde_json::to_vec(self)
}
}
#[cfg(feature = "kas-client")]
impl TdfJsonBuilder {
#[must_use]
pub fn kas_url(mut self, url: &str) -> Self {
self.kas_url = Some(url.to_string());
self
}
#[must_use]
pub fn kas_public_key(mut self, pem: &str) -> Self {
self.kas_public_key_pem = Some(pem.to_string());
self
}
#[must_use]
pub fn policy(mut self, policy: Policy) -> Self {
self.policy = Some(policy);
self
}
#[must_use]
pub fn mime_type(mut self, mime_type: &str) -> Self {
self.mime_type = Some(mime_type.to_string());
self
}
#[must_use]
pub fn include_created(mut self, include: bool) -> Self {
self.include_created = include;
self
}
pub fn build(self) -> Result<TdfJson, EncryptionError> {
let kas_url = self.kas_url.ok_or(EncryptionError::KeyGenerationError)?;
let policy = self.policy.ok_or(EncryptionError::KeyGenerationError)?;
let tdf_encryption = TdfEncryption::new()?;
let encrypted_payload = tdf_encryption.encrypt(&self.data)?;
let payload_key = tdf_encryption.payload_key();
let policy_json =
serde_json::to_string(&policy).map_err(|_| EncryptionError::KeyGenerationError)?;
let policy_b64 = BASE64.encode(policy_json.as_bytes());
let policy_hash = calculate_policy_binding(&policy_json, payload_key)
.map_err(|_| EncryptionError::KeyGenerationError)?;
let kas_pem = self
.kas_public_key_pem
.ok_or(EncryptionError::KeyGenerationError)?;
let ec_result = opentdf_crypto::wrap_key_with_ec(&kas_pem, payload_key)
.map_err(|_| EncryptionError::KeyGenerationError)?;
let (wrapped_key, ephemeral_public_key) =
(ec_result.wrapped_key, Some(ec_result.ephemeral_public_key));
let key_access = KeyAccess {
access_type: "wrapped".to_string(),
url: kas_url,
kid: None,
sid: None,
protocol: "kas".to_string(),
wrapped_key,
policy_binding: crate::manifest::PolicyBinding {
alg: "HS256".to_string(),
hash: policy_hash,
},
encrypted_metadata: None,
schema_version: Some("1.0".to_string()),
ephemeral_public_key,
};
let ciphertext_bytes = BASE64.decode(&encrypted_payload.ciphertext)?;
let encrypted_size = ciphertext_bytes.len() as u64;
let gmac_tag = if ciphertext_bytes.len() >= 16 {
ciphertext_bytes[ciphertext_bytes.len() - 16..].to_vec()
} else {
return Err(EncryptionError::KeyGenerationError);
};
let mut integrity_info = IntegrityInformation {
root_signature: RootSignature {
alg: "HS256".to_string(),
sig: String::new(),
},
segment_hash_alg: "GMAC".to_string(),
segments: vec![Segment {
hash: BASE64.encode(&gmac_tag),
segment_size: Some(self.data.len() as u64),
encrypted_segment_size: Some(encrypted_size),
}],
segment_size_default: self.data.len() as u64,
encrypted_segment_size_default: encrypted_size,
};
integrity_info
.generate_root_signature(&[gmac_tag], payload_key)
.map_err(|_| EncryptionError::KeyGenerationError)?;
let encryption_info = EncryptionInformation {
encryption_type: "split".to_string(),
key_access: vec![key_access],
method: EncryptionMethod {
algorithm: "AES-256-GCM".to_string(),
is_streamable: true,
iv: encrypted_payload.iv.clone(),
},
integrity_information: integrity_info,
policy: policy_b64,
};
let manifest = TdfJsonManifest {
encryption_information: encryption_info,
assertions: None,
};
let payload = JsonPayload {
payload_type: "inline".to_string(),
protocol: "base64".to_string(),
mime_type: self.mime_type,
is_encrypted: true,
length: Some(encrypted_size),
value: encrypted_payload.ciphertext,
};
let created = if self.include_created {
Some(chrono::Utc::now().to_rfc3339())
} else {
None
};
Ok(TdfJson {
tdf: "json".to_string(),
version: "1.0.0".to_string(),
created,
manifest,
payload,
})
}
}
#[deprecated(
since = "0.12.0",
note = "Use TdfJsonBuilder instead. Will be removed in 1.0.0"
)]
pub struct TdfJsonRpcBuilder {
data: Vec<u8>,
kas_url: Option<String>,
policy: Option<Policy>,
mime_type: String,
}
impl TdfJsonRpc {
pub fn encrypt(data: &[u8]) -> TdfJsonRpcBuilder {
TdfJsonRpcBuilder {
data: data.to_vec(),
kas_url: None,
policy: None,
mime_type: "application/octet-stream".to_string(),
}
}
pub fn decrypt_with_key(&self, payload_key: &[u8]) -> Result<Vec<u8>, EncryptionError> {
use aes_gcm::{
Aes256Gcm, Nonce,
aead::{Aead, KeyInit},
};
let ciphertext = BASE64.decode(&self.manifest.payload.value)?;
let iv_bytes = BASE64.decode(&self.manifest.encryption_information.method.iv)?;
if iv_bytes.len() < GCM_NONCE_LENGTH {
return Err(EncryptionError::InvalidIvLength(iv_bytes.len()));
}
let payload_iv = &iv_bytes[0..GCM_NONCE_LENGTH];
let cipher = Aes256Gcm::new_from_slice(payload_key)
.map_err(|_| EncryptionError::InvalidKeyLength)?;
let nonce = Nonce::from_slice(payload_iv);
let plaintext = cipher
.decrypt(nonce, ciphertext.as_ref())
.map_err(EncryptionError::AeadError)?;
Ok(plaintext)
}
pub fn to_standard_manifest(&self) -> TdfManifest {
TdfManifest {
payload: Payload {
payload_type: "reference".to_string(),
url: "inline".to_string(),
protocol: "base64".to_string(),
is_encrypted: true,
mime_type: Some(self.manifest.payload.mime_type.clone()),
tdf_spec_version: None,
},
encryption_information: self.manifest.encryption_information.clone(),
schema_version: self.manifest.schema_version.clone(),
tdf_spec_version: None,
gguf: None,
assertions: Vec::new(),
}
}
}
impl From<&TdfManifest> for TdfManifestInline {
fn from(manifest: &TdfManifest) -> Self {
Self {
payload: InlinePayload {
payload_type: "inline".to_string(),
mime_type: manifest
.payload
.mime_type
.clone()
.unwrap_or_else(|| "application/octet-stream".to_string()),
protocol: "base64".to_string(),
value: String::new(), is_encrypted: manifest.payload.is_encrypted,
},
encryption_information: manifest.encryption_information.clone(),
schema_version: manifest.schema_version.clone(),
}
}
}
impl From<TdfManifest> for TdfManifestInline {
fn from(manifest: TdfManifest) -> Self {
Self {
payload: InlinePayload {
payload_type: "inline".to_string(),
mime_type: manifest
.payload
.mime_type
.unwrap_or_else(|| "application/octet-stream".to_string()),
protocol: "base64".to_string(),
value: String::new(), is_encrypted: manifest.payload.is_encrypted,
},
encryption_information: manifest.encryption_information,
schema_version: manifest.schema_version,
}
}
}
impl From<&TdfManifestInline> for TdfManifest {
fn from(inline: &TdfManifestInline) -> Self {
Self {
payload: Payload {
payload_type: "reference".to_string(),
url: "inline".to_string(),
protocol: "base64".to_string(),
is_encrypted: inline.payload.is_encrypted,
mime_type: Some(inline.payload.mime_type.clone()),
tdf_spec_version: None,
},
encryption_information: inline.encryption_information.clone(),
schema_version: inline.schema_version.clone(),
tdf_spec_version: None,
gguf: None,
assertions: Vec::new(),
}
}
}
impl From<TdfManifestInline> for TdfManifest {
fn from(inline: TdfManifestInline) -> Self {
Self {
payload: Payload {
payload_type: "reference".to_string(),
url: "inline".to_string(),
protocol: "base64".to_string(),
is_encrypted: inline.payload.is_encrypted,
mime_type: Some(inline.payload.mime_type),
tdf_spec_version: None,
},
encryption_information: inline.encryption_information,
schema_version: inline.schema_version,
tdf_spec_version: None,
gguf: None,
assertions: Vec::new(),
}
}
}
impl From<&InlinePayload> for Payload {
fn from(inline: &InlinePayload) -> Self {
Self {
payload_type: "reference".to_string(),
url: "inline".to_string(),
protocol: "base64".to_string(),
is_encrypted: inline.is_encrypted,
mime_type: Some(inline.mime_type.clone()),
tdf_spec_version: None,
}
}
}
impl From<InlinePayload> for Payload {
fn from(inline: InlinePayload) -> Self {
Self {
payload_type: "reference".to_string(),
url: "inline".to_string(),
protocol: "base64".to_string(),
is_encrypted: inline.is_encrypted,
mime_type: Some(inline.mime_type),
tdf_spec_version: None,
}
}
}
impl TdfJsonRpcBuilder {
#[must_use]
pub fn kas_url(mut self, url: &str) -> Self {
self.kas_url = Some(url.to_string());
self
}
#[must_use]
pub fn policy(mut self, policy: Policy) -> Self {
self.policy = Some(policy);
self
}
#[must_use]
pub fn mime_type(mut self, mime_type: &str) -> Self {
self.mime_type = mime_type.to_string();
self
}
pub fn build(self) -> Result<TdfJsonRpc, EncryptionError> {
let kas_url = self.kas_url.ok_or(EncryptionError::KeyGenerationError)?;
let policy = self.policy.ok_or(EncryptionError::KeyGenerationError)?;
let tdf_encryption = TdfEncryption::new()?;
let encrypted_payload = tdf_encryption.encrypt(&self.data)?;
let payload_key = tdf_encryption.payload_key();
let policy_json =
serde_json::to_string(&policy).map_err(|_| EncryptionError::KeyGenerationError)?;
let policy_b64 = BASE64.encode(policy_json.as_bytes());
let policy_hash = calculate_policy_binding(&policy_json, payload_key)
.map_err(|_| EncryptionError::KeyGenerationError)?;
let key_access = KeyAccess {
access_type: "wrapped".to_string(),
url: kas_url,
kid: None,
sid: None,
protocol: "kas".to_string(),
wrapped_key: encrypted_payload.encrypted_key.clone(),
policy_binding: crate::manifest::PolicyBinding {
alg: "HS256".to_string(),
hash: policy_hash,
},
encrypted_metadata: None,
schema_version: Some("1.0".to_string()),
ephemeral_public_key: None, };
let encrypted_size = ((encrypted_payload.ciphertext.len() * 3) / 4) as u64;
let ciphertext_bytes = BASE64.decode(&encrypted_payload.ciphertext)?;
let gmac_tag = if ciphertext_bytes.len() >= 16 {
ciphertext_bytes[ciphertext_bytes.len() - 16..].to_vec()
} else {
return Err(EncryptionError::KeyGenerationError);
};
let mut integrity_info = IntegrityInformation {
root_signature: RootSignature {
alg: "HS256".to_string(),
sig: String::new(), },
segment_hash_alg: "GMAC".to_string(),
segments: vec![Segment {
hash: BASE64.encode(&gmac_tag), segment_size: Some(self.data.len() as u64),
encrypted_segment_size: Some(encrypted_size),
}],
segment_size_default: self.data.len() as u64,
encrypted_segment_size_default: encrypted_size,
};
integrity_info
.generate_root_signature(&[gmac_tag], payload_key)
.map_err(|_| EncryptionError::KeyGenerationError)?;
let encryption_info = EncryptionInformation {
encryption_type: "split".to_string(),
key_access: vec![key_access],
method: EncryptionMethod {
algorithm: "AES-256-GCM".to_string(),
is_streamable: true,
iv: encrypted_payload.iv.clone(),
},
integrity_information: integrity_info,
policy: policy_b64,
};
let inline_payload = InlinePayload {
payload_type: "inline".to_string(),
mime_type: self.mime_type,
protocol: "base64".to_string(),
value: encrypted_payload.ciphertext,
is_encrypted: true,
};
let manifest = TdfManifestInline {
payload: inline_payload,
encryption_information: encryption_info,
schema_version: Some("1.1.0".to_string()),
};
Ok(TdfJsonRpc {
manifest,
version: "3.0.0".to_string(),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn test_kas_url() -> String {
std::env::var("TEST_KAS_URL").unwrap_or_else(|_| "https://platform.arkavo.net".to_string())
}
fn generate_test_ec_key_pair() -> (String, String) {
use p256::SecretKey;
use p256::elliptic_curve::Generate;
use p256::pkcs8::{EncodePrivateKey, EncodePublicKey, LineEnding};
let secret_key = SecretKey::generate();
let public_key = secret_key.public_key();
let private_pem = secret_key
.to_pkcs8_pem(LineEnding::LF)
.expect("Failed to encode private key")
.to_string();
let public_pem = public_key
.to_public_key_pem(LineEnding::LF)
.expect("Failed to encode public key");
(private_pem, public_pem)
}
#[test]
fn test_create_jsonrpc_envelope() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let envelope = TdfJsonRpc::encrypt(b"Hello, World!")
.kas_url(&test_kas_url())
.policy(policy)
.mime_type("text/plain")
.build()
.expect("Failed to create envelope");
assert_eq!(envelope.version, "3.0.0");
assert_eq!(envelope.manifest.payload.payload_type, "inline");
assert_eq!(envelope.manifest.payload.mime_type, "text/plain");
assert_eq!(envelope.manifest.payload.protocol, "base64");
assert!(envelope.manifest.payload.is_encrypted);
}
#[test]
fn test_serialize_deserialize() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let envelope = TdfJsonRpc::encrypt(b"Test data")
.kas_url(&test_kas_url())
.policy(policy)
.build()
.expect("Failed to create envelope");
let json = serde_json::to_string(&envelope).expect("Failed to serialize");
let deserialized: TdfJsonRpc = serde_json::from_str(&json).expect("Failed to deserialize");
assert_eq!(envelope.version, deserialized.version);
assert_eq!(
envelope.manifest.payload.value,
deserialized.manifest.payload.value
);
}
#[test]
fn test_decrypt_with_key() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let original_data = b"Secret message";
let tdf_encryption = TdfEncryption::new().expect("Failed to create encryption");
let payload_key = tdf_encryption.payload_key().to_vec();
let encrypted_payload = tdf_encryption
.encrypt(original_data)
.expect("Failed to encrypt");
let policy_json = serde_json::to_string(&policy).expect("Failed to serialize policy");
let policy_b64 = BASE64.encode(policy_json.as_bytes());
let policy_hash = calculate_policy_binding(&policy_json, &payload_key)
.expect("Failed to calculate policy binding");
let key_access = KeyAccess {
access_type: "wrapped".to_string(),
url: test_kas_url(),
kid: None,
sid: None,
protocol: "kas".to_string(),
wrapped_key: encrypted_payload.encrypted_key.clone(),
policy_binding: crate::manifest::PolicyBinding {
alg: "HS256".to_string(),
hash: policy_hash,
},
encrypted_metadata: None,
schema_version: Some("1.0".to_string()),
ephemeral_public_key: None,
};
let integrity_info = IntegrityInformation {
root_signature: RootSignature {
alg: "HS256".to_string(),
sig: String::new(),
},
segment_hash_alg: "GMAC".to_string(),
segments: vec![Segment {
hash: String::new(),
segment_size: Some(original_data.len() as u64),
encrypted_segment_size: Some(
BASE64.decode(&encrypted_payload.ciphertext).unwrap().len() as u64,
),
}],
segment_size_default: original_data.len() as u64,
encrypted_segment_size_default: BASE64
.decode(&encrypted_payload.ciphertext)
.unwrap()
.len() as u64,
};
let encryption_info = EncryptionInformation {
encryption_type: "split".to_string(),
key_access: vec![key_access],
method: EncryptionMethod {
algorithm: "AES-256-GCM".to_string(),
is_streamable: true,
iv: encrypted_payload.iv.clone(),
},
integrity_information: integrity_info,
policy: policy_b64,
};
let inline_payload = InlinePayload {
payload_type: "inline".to_string(),
mime_type: "text/plain".to_string(),
protocol: "base64".to_string(),
value: encrypted_payload.ciphertext,
is_encrypted: true,
};
let manifest = TdfManifestInline {
payload: inline_payload,
encryption_information: encryption_info,
schema_version: Some("1.1.0".to_string()),
};
let envelope = TdfJsonRpc {
manifest,
version: "3.0.0".to_string(),
};
let decrypted = envelope
.decrypt_with_key(&payload_key)
.expect("Failed to decrypt");
assert_eq!(original_data, decrypted.as_slice());
}
#[test]
fn test_decrypt_with_wrong_key() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let envelope = TdfJsonRpc::encrypt(b"Secret data")
.kas_url(&test_kas_url())
.policy(policy)
.build()
.expect("Failed to create envelope");
let wrong_key = vec![0u8; 32];
let result = envelope.decrypt_with_key(&wrong_key);
assert!(result.is_err(), "Decryption should fail with wrong key");
}
#[test]
fn test_decrypt_with_invalid_key_length() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let envelope = TdfJsonRpc::encrypt(b"Secret data")
.kas_url(&test_kas_url())
.policy(policy)
.build()
.expect("Failed to create envelope");
let invalid_key = vec![0u8; 16]; let result = envelope.decrypt_with_key(&invalid_key);
assert!(
result.is_err(),
"Decryption should fail with invalid key length"
);
match result {
Err(EncryptionError::InvalidKeyLength) => (),
_ => panic!("Expected InvalidKeyLength error"),
}
}
#[test]
fn test_builder_missing_kas_url() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let result = TdfJsonRpc::encrypt(b"Data").policy(policy).build();
assert!(result.is_err(), "Build should fail without KAS URL");
}
#[test]
fn test_builder_missing_policy() {
let result = TdfJsonRpc::encrypt(b"Data")
.kas_url(&test_kas_url())
.build();
assert!(result.is_err(), "Build should fail without policy");
}
#[test]
fn test_roundtrip_encryption_decryption() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let original_data =
b"This is a roundtrip test with longer data to ensure everything works correctly!";
let tdf_encryption = TdfEncryption::new().expect("Failed to create encryption");
let _payload_key = tdf_encryption.payload_key().to_vec();
let envelope = TdfJsonRpc::encrypt(original_data)
.kas_url(&test_kas_url())
.policy(policy)
.mime_type("text/plain")
.build()
.expect("Failed to encrypt");
let json = serde_json::to_string(&envelope).expect("Failed to serialize");
let deserialized: TdfJsonRpc = serde_json::from_str(&json).expect("Failed to deserialize");
assert_eq!(deserialized.version, "3.0.0");
assert_eq!(deserialized.manifest.payload.payload_type, "inline");
assert_eq!(deserialized.manifest.payload.mime_type, "text/plain");
assert!(deserialized.manifest.payload.is_encrypted);
}
#[test]
fn test_empty_payload() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let envelope = TdfJsonRpc::encrypt(b"")
.kas_url(&test_kas_url())
.policy(policy)
.build()
.expect("Failed to create envelope with empty payload");
assert_eq!(envelope.manifest.payload.payload_type, "inline");
}
#[test]
fn test_large_payload() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let large_data = vec![0u8; 1024 * 1024];
let envelope = TdfJsonRpc::encrypt(&large_data)
.kas_url(&test_kas_url())
.policy(policy)
.build()
.expect("Failed to create envelope with large payload");
assert_eq!(envelope.manifest.payload.payload_type, "inline");
assert!(!envelope.manifest.payload.value.is_empty());
}
#[test]
fn test_custom_mime_type() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let envelope = TdfJsonRpc::encrypt(b"JSON data")
.kas_url(&test_kas_url())
.policy(policy)
.mime_type("application/json")
.build()
.expect("Failed to create envelope");
assert_eq!(envelope.manifest.payload.mime_type, "application/json");
}
#[cfg(feature = "kas-client")]
#[test]
fn test_tdf_json_create_envelope() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let (_private_pem, public_pem) = generate_test_ec_key_pair();
let envelope = TdfJson::encrypt(b"Hello, World!")
.kas_url(&test_kas_url())
.kas_public_key(&public_pem)
.policy(policy)
.mime_type("text/plain")
.build()
.expect("Failed to create envelope");
assert_eq!(envelope.tdf, "json");
assert_eq!(envelope.version, "1.0.0");
assert!(envelope.created.is_some()); assert_eq!(envelope.payload.payload_type, "inline");
assert_eq!(envelope.payload.protocol, "base64");
assert_eq!(envelope.payload.mime_type, Some("text/plain".to_string()));
assert!(envelope.payload.is_encrypted);
assert!(envelope.payload.length.is_some());
}
#[cfg(feature = "kas-client")]
#[test]
fn test_tdf_json_policy_binding_matches_manifest_policy() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let (private_pem, public_pem) = generate_test_ec_key_pair();
let envelope = TdfJson::encrypt(b"binding")
.kas_url(&test_kas_url())
.kas_public_key(&public_pem)
.policy(policy)
.build()
.expect("Failed to create envelope");
let info = &envelope.manifest.encryption_information;
let kao = &info.key_access[0];
let dek = opentdf_crypto::unwrap_key_with_ec(
&private_pem,
&kao.wrapped_key,
kao.ephemeral_public_key.as_deref().unwrap(),
)
.unwrap();
let expected =
BASE64.encode(opentdf_crypto::calculate_hmac(&dek, info.policy.as_bytes()).unwrap());
assert_eq!(kao.policy_binding.hash, expected);
}
#[cfg(feature = "kas-client")]
#[test]
fn test_tdf_json_serialize_deserialize() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let (_private_pem, public_pem) = generate_test_ec_key_pair();
let envelope = TdfJson::encrypt(b"Test data")
.kas_url(&test_kas_url())
.kas_public_key(&public_pem)
.policy(policy)
.include_created(false) .build()
.expect("Failed to create envelope");
let json = serde_json::to_string_pretty(&envelope).expect("Failed to serialize");
assert!(json.contains("\"tdf\": \"json\""));
assert!(json.contains("\"version\": \"1.0.0\""));
assert!(json.contains("\"manifest\":"));
assert!(json.contains("\"payload\":"));
let deserialized: TdfJson = serde_json::from_str(&json).expect("Failed to deserialize");
assert_eq!(envelope.tdf, deserialized.tdf);
assert_eq!(envelope.version, deserialized.version);
assert_eq!(envelope.payload.value, deserialized.payload.value);
}
#[test]
fn test_tdf_json_decrypt_with_key() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let original_data = b"Secret message for TDF-JSON";
let tdf_encryption = TdfEncryption::new().expect("Failed to create encryption");
let payload_key = tdf_encryption.payload_key().to_vec();
let encrypted_payload = tdf_encryption
.encrypt(original_data)
.expect("Failed to encrypt");
let policy_json = serde_json::to_string(&policy).expect("Failed to serialize policy");
let policy_b64 = BASE64.encode(policy_json.as_bytes());
let policy_hash = calculate_policy_binding(&policy_json, &payload_key)
.expect("Failed to calculate policy binding");
let key_access = KeyAccess {
access_type: "wrapped".to_string(),
url: test_kas_url(),
kid: None,
sid: None,
protocol: "kas".to_string(),
wrapped_key: encrypted_payload.encrypted_key.clone(),
policy_binding: crate::manifest::PolicyBinding {
alg: "HS256".to_string(),
hash: policy_hash,
},
encrypted_metadata: None,
schema_version: Some("1.0".to_string()),
ephemeral_public_key: None,
};
let ciphertext_len = BASE64.decode(&encrypted_payload.ciphertext).unwrap().len() as u64;
let integrity_info = IntegrityInformation {
root_signature: RootSignature {
alg: "HS256".to_string(),
sig: String::new(),
},
segment_hash_alg: "GMAC".to_string(),
segments: vec![Segment {
hash: String::new(),
segment_size: Some(original_data.len() as u64),
encrypted_segment_size: Some(ciphertext_len),
}],
segment_size_default: original_data.len() as u64,
encrypted_segment_size_default: ciphertext_len,
};
let encryption_info = EncryptionInformation {
encryption_type: "split".to_string(),
key_access: vec![key_access],
method: EncryptionMethod {
algorithm: "AES-256-GCM".to_string(),
is_streamable: true,
iv: encrypted_payload.iv.clone(),
},
integrity_information: integrity_info,
policy: policy_b64,
};
let manifest = TdfJsonManifest {
encryption_information: encryption_info,
assertions: None,
};
let payload = JsonPayload {
payload_type: "inline".to_string(),
protocol: "base64".to_string(),
mime_type: Some("text/plain".to_string()),
is_encrypted: true,
length: Some(ciphertext_len),
value: encrypted_payload.ciphertext,
};
let envelope = TdfJson {
tdf: "json".to_string(),
version: "1.0.0".to_string(),
created: None,
manifest,
payload,
};
let decrypted = envelope
.decrypt_with_key(&payload_key)
.expect("Failed to decrypt");
assert_eq!(original_data, decrypted.as_slice());
}
#[cfg(feature = "kas-client")]
#[test]
fn test_tdf_json_format_id() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let (_private_pem, public_pem) = generate_test_ec_key_pair();
let envelope = TdfJson::encrypt(b"Test")
.kas_url(&test_kas_url())
.kas_public_key(&public_pem)
.policy(policy)
.build()
.expect("Failed to create envelope");
assert_eq!(envelope.format_id(), "json");
}
#[cfg(feature = "kas-client")]
#[test]
fn test_tdf_json_to_bytes() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let (_private_pem, public_pem) = generate_test_ec_key_pair();
let envelope = TdfJson::encrypt(b"Test")
.kas_url(&test_kas_url())
.kas_public_key(&public_pem)
.policy(policy)
.include_created(false)
.build()
.expect("Failed to create envelope");
let bytes = envelope.to_bytes().expect("Failed to serialize");
assert!(!bytes.is_empty());
let parsed: TdfJson = serde_json::from_slice(&bytes).expect("Failed to parse");
assert_eq!(parsed.tdf, "json");
}
#[cfg(feature = "kas-client")]
#[test]
fn test_tdf_json_no_created_timestamp() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let (_private_pem, public_pem) = generate_test_ec_key_pair();
let envelope = TdfJson::encrypt(b"Test")
.kas_url(&test_kas_url())
.kas_public_key(&public_pem)
.policy(policy)
.include_created(false)
.build()
.expect("Failed to create envelope");
assert!(envelope.created.is_none());
let json = serde_json::to_string(&envelope).expect("Failed to serialize");
assert!(!json.contains("created"));
}
#[cfg(feature = "kas-client")]
#[test]
fn test_tdf_json_to_standard_manifest() {
let policy = Policy::new(
"test-policy".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let (_private_pem, public_pem) = generate_test_ec_key_pair();
let envelope = TdfJson::encrypt(b"Test")
.kas_url(&test_kas_url())
.kas_public_key(&public_pem)
.policy(policy)
.mime_type("text/plain")
.build()
.expect("Failed to create envelope");
let manifest = envelope.to_standard_manifest();
assert_eq!(manifest.payload.payload_type, "reference");
assert_eq!(manifest.payload.url, "inline");
assert_eq!(manifest.payload.protocol, "base64");
assert!(manifest.payload.is_encrypted);
}
const TDF_JSON_WITH_SID_AND_ASSERTION: &str = r#"{
"tdf": "json",
"version": "1.0.0",
"manifest": {
"encryptionInformation": {
"type": "split",
"keyAccess": [{
"type": "wrapped",
"url": "https://kas.example.com",
"sid": "split-id-1",
"protocol": "kas",
"wrappedKey": "AAAA",
"policyBinding": {"alg": "HS256", "hash": "BBBB"}
}],
"method": {"algorithm": "AES-256-GCM", "isStreamable": true, "iv": ""},
"integrityInformation": {
"rootSignature": {"alg": "HS256", "sig": ""},
"segmentHashAlg": "GMAC",
"segments": [],
"segmentSizeDefault": 0,
"encryptedSegmentSizeDefault": 0
},
"policy": ""
},
"assertions": [{
"id": "a1",
"type": "handling",
"scope": "payload",
"appliesToState": "encrypted",
"statement": {"format": "json-structured", "value": {"k": ["v", 1]}},
"binding": {"method": "jws", "signature": "x.y.z"}
}]
},
"payload": {"type": "inline", "protocol": "base64", "isEncrypted": true, "value": ""}
}"#;
#[test]
fn test_tdf_json_to_standard_manifest_uses_spec_version_and_keeps_sid_and_assertions() {
let envelope: TdfJson = serde_json::from_str(TDF_JSON_WITH_SID_AND_ASSERTION).unwrap();
assert_eq!(envelope.version, "1.0.0");
let manifest = envelope.to_standard_manifest();
assert_eq!(manifest.schema_version.as_deref(), Some(TDF_SPEC_VERSION));
assert_eq!(manifest.spec_version(), Some(TDF_SPEC_VERSION));
assert_eq!(
manifest.encryption_information.key_access[0].sid.as_deref(),
Some("split-id-1")
);
assert_eq!(manifest.assertions.len(), 1);
assert_eq!(manifest.assertions[0].id, "a1");
assert_eq!(
manifest.assertions[0].statement.value,
serde_json::json!({"k": ["v", 1]})
);
let input: serde_json::Value =
serde_json::from_str(TDF_JSON_WITH_SID_AND_ASSERTION).unwrap();
let output = serde_json::to_value(&envelope).unwrap();
assert_eq!(output, input);
}
#[test]
fn tdf_json_decrypt_with_key_rejects_missing_iv_instead_of_panicking() {
let doc = r#"{
"tdf": "json",
"version": "1.0.0",
"manifest": {
"encryptionInformation": {
"type": "split",
"keyAccess": [],
"method": {"algorithm": "AES-256-GCM"},
"integrityInformation": {
"rootSignature": {"alg": "HS256", "sig": ""},
"segmentHashAlg": "GMAC",
"segments": [],
"segmentSizeDefault": 0,
"encryptedSegmentSizeDefault": 0
},
"policy": ""
}
},
"payload": {"type": "inline", "protocol": "base64", "isEncrypted": true, "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="}
}"#;
let envelope: TdfJson = serde_json::from_str(doc).unwrap();
assert_eq!(envelope.manifest.encryption_information.method.iv, "");
let result = envelope.decrypt_with_key(TdfEncryption::new().unwrap().payload_key());
assert!(
matches!(result, Err(EncryptionError::InvalidIvLength(0))),
"expected InvalidIvLength(0), got {result:?}"
);
}
#[test]
fn tdf_json_rpc_decrypt_with_key_rejects_missing_iv_instead_of_panicking() {
let doc = r#"{
"version": "3.0.0",
"manifest": {
"payload": {"type": "inline", "mimeType": "text/plain", "protocol": "base64", "isEncrypted": true, "value": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="},
"encryptionInformation": {
"type": "split",
"keyAccess": [],
"method": {"algorithm": "AES-256-GCM"},
"integrityInformation": {
"rootSignature": {"alg": "HS256", "sig": ""},
"segmentHashAlg": "GMAC",
"segments": [],
"segmentSizeDefault": 0,
"encryptedSegmentSizeDefault": 0
},
"policy": ""
}
}
}"#;
let envelope: TdfJsonRpc = serde_json::from_str(doc).unwrap();
let result = envelope.decrypt_with_key(TdfEncryption::new().unwrap().payload_key());
assert!(
matches!(result, Err(EncryptionError::InvalidIvLength(0))),
"expected InvalidIvLength(0), got {result:?}"
);
}
}