use crate::archive::{TdfArchiveBuilder, TdfArchiveMemoryBuilder, TdfError};
use crate::manifest::{IntegrityInformationExt, KeyAccessExt, TdfManifest, TdfManifestExt};
use crate::policy::Policy;
use opentdf_crypto::TdfEncryption;
use std::path::Path;
#[cfg(feature = "kas-client")]
use crate::archive::{DEFAULT_MAX_PAYLOAD_SIZE, TdfArchive};
#[cfg(feature = "kas-client")]
use crate::kas::KasClient;
pub struct Tdf;
impl Tdf {
pub fn encrypt(data: impl Into<Vec<u8>>) -> TdfEncryptBuilder {
TdfEncryptBuilder::new(data.into())
}
pub fn encrypt_file(
input: impl AsRef<Path>,
output: impl AsRef<Path>,
) -> TdfEncryptFileBuilder {
TdfEncryptFileBuilder::new(input.as_ref().to_path_buf(), output.as_ref().to_path_buf())
}
#[cfg(feature = "kas-client")]
pub fn decrypt(data: impl Into<Vec<u8>>) -> TdfDecryptBuilder {
TdfDecryptBuilder::new(data.into())
}
#[cfg(feature = "kas-client")]
pub fn decrypt_file(path: impl AsRef<Path>) -> TdfDecryptFileBuilder {
TdfDecryptFileBuilder::new(path.as_ref().to_path_buf())
}
}
pub struct TdfEncryptBuilder {
data: Vec<u8>,
kas_url: Option<String>,
policy: Option<Policy>,
mime_type: Option<String>,
segment_size: usize,
}
impl TdfEncryptBuilder {
pub(crate) fn new(data: Vec<u8>) -> Self {
const DEFAULT_SEGMENT_SIZE: usize = 2 * 1024 * 1024; Self {
data,
kas_url: None,
policy: None,
mime_type: None,
segment_size: DEFAULT_SEGMENT_SIZE,
}
}
#[must_use]
pub fn kas_url(mut self, url: impl Into<String>) -> Self {
self.kas_url = Some(url.into());
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: impl Into<String>) -> Self {
self.mime_type = Some(mime_type.into());
self
}
#[must_use]
pub fn segment_size(mut self, size: usize) -> Self {
self.segment_size = size;
self
}
pub fn to_bytes(self) -> Result<Vec<u8>, TdfError> {
let (manifest, segments, _encryption) = self.prepare_tdf()?;
let mut builder = TdfArchiveMemoryBuilder::new();
builder.add_entry_with_segments(&manifest, &segments, 0)?;
builder.finish()
}
pub fn to_file(self, path: impl AsRef<Path>) -> Result<(), TdfError> {
let (manifest, segments, _encryption) = self.prepare_tdf()?;
let mut builder = TdfArchiveBuilder::new(path.as_ref())?;
builder.add_entry_with_segments(&manifest, &segments, 0)?;
builder.finish()?;
Ok(())
}
fn prepare_tdf(self) -> Result<(TdfManifest, Vec<Vec<u8>>, TdfEncryption), TdfError> {
let kas_url = self
.kas_url
.ok_or_else(|| TdfError::MissingRequiredField { field: "kas_url" })?;
let tdf_encryption = TdfEncryption::new().map_err(|e| TdfError::CryptoError {
algorithm: "AES-256-GCM".to_string(),
reason: "Encryption setup failed".to_string(),
source: Some(Box::new(e)),
})?;
let segmented = tdf_encryption
.encrypt_with_segments(&self.data, self.segment_size)
.map_err(|e| TdfError::CryptoError {
algorithm: "AES-256-GCM".to_string(),
reason: "Encryption failed".to_string(),
source: Some(Box::new(e)),
})?;
let mut manifest = TdfManifest::new("0.payload".to_string(), kas_url);
manifest.encryption_information.method.algorithm = "AES-256-GCM".to_string();
manifest.encryption_information.method.iv = String::new();
if let Some(mime_type) = self.mime_type {
manifest.payload.mime_type = Some(mime_type);
}
if let Some(policy) = self.policy {
manifest
.set_policy(&policy)
.map_err(|e| TdfError::PolicyValidationFailed {
policy_id: policy.uuid.clone(),
errors: vec![e.to_string()],
})?;
let policy_json = policy
.to_json()
.map_err(|e| TdfError::PolicyValidationFailed {
policy_id: policy.uuid.clone(),
errors: vec![format!("Policy serialization failed: {}", e)],
})?;
manifest.encryption_information.key_access[0]
.generate_policy_binding_raw(&policy_json, tdf_encryption.payload_key())
.map_err(|e| TdfError::PolicyValidationFailed {
policy_id: policy.uuid.clone(),
errors: vec![format!("Policy binding generation failed: {}", e)],
})?;
}
use crate::manifest::Segment;
for seg_info in &segmented.segment_info {
manifest
.encryption_information
.integrity_information
.segments
.push(Segment {
hash: seg_info.hash.clone(),
segment_size: Some(seg_info.plaintext_size),
encrypted_segment_size: Some(seg_info.encrypted_size),
});
}
if let Some(first_seg) = segmented.segment_info.first() {
manifest
.encryption_information
.integrity_information
.segment_size_default = first_seg.plaintext_size;
manifest
.encryption_information
.integrity_information
.encrypted_segment_size_default = first_seg.encrypted_size;
}
manifest
.encryption_information
.integrity_information
.generate_root_signature(&segmented.gmac_tags, tdf_encryption.payload_key())
.map_err(|e| TdfError::CryptoError {
algorithm: "HMAC-SHA256".to_string(),
reason: format!("Root signature generation failed: {}", e),
source: None,
})?;
Ok((manifest, segmented.segments, tdf_encryption))
}
}
pub struct TdfEncryptFileBuilder {
input_path: std::path::PathBuf,
output_path: std::path::PathBuf,
kas_url: Option<String>,
policy: Option<Policy>,
mime_type: Option<String>,
segment_size: usize,
}
impl TdfEncryptFileBuilder {
pub(crate) fn new(input_path: std::path::PathBuf, output_path: std::path::PathBuf) -> Self {
const DEFAULT_SEGMENT_SIZE: usize = 2 * 1024 * 1024; Self {
input_path,
output_path,
kas_url: None,
policy: None,
mime_type: None,
segment_size: DEFAULT_SEGMENT_SIZE,
}
}
#[must_use]
pub fn kas_url(mut self, url: impl Into<String>) -> Self {
self.kas_url = Some(url.into());
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: impl Into<String>) -> Self {
self.mime_type = Some(mime_type.into());
self
}
#[must_use]
pub fn segment_size(mut self, size: usize) -> Self {
self.segment_size = size;
self
}
pub fn build(self) -> Result<(), TdfError> {
let data = std::fs::read(&self.input_path)?;
let mut builder = TdfEncryptBuilder::new(data);
if let Some(kas_url) = self.kas_url {
builder = builder.kas_url(kas_url);
}
if let Some(policy) = self.policy {
builder = builder.policy(policy);
}
if let Some(mime_type) = self.mime_type {
builder = builder.mime_type(mime_type);
}
builder = builder.segment_size(self.segment_size);
builder.to_file(self.output_path)
}
}
#[cfg(feature = "kas-client")]
pub struct TdfDecryptBuilder {
data: Vec<u8>,
kas_client: Option<KasClient>,
max_payload_size: u64,
}
#[cfg(feature = "kas-client")]
impl TdfDecryptBuilder {
pub(crate) fn new(data: Vec<u8>) -> Self {
Self {
data,
kas_client: None,
max_payload_size: DEFAULT_MAX_PAYLOAD_SIZE,
}
}
#[must_use]
pub fn kas_client(mut self, client: KasClient) -> Self {
self.kas_client = Some(client);
self
}
#[must_use]
pub fn max_payload_size(mut self, limit: u64) -> Self {
self.max_payload_size = limit;
self
}
pub async fn to_bytes(self) -> Result<Vec<u8>, TdfError> {
let kas_client = self
.kas_client
.ok_or_else(|| TdfError::MissingRequiredField {
field: "kas_client",
})?;
let cursor = std::io::Cursor::new(self.data);
let mut archive = TdfArchive::new(cursor)?.with_max_payload_size(self.max_payload_size);
let entry = archive.by_index()?;
entry.decrypt_with_kas(&kas_client).await
}
pub async fn to_file(self, path: impl AsRef<Path>) -> Result<(), TdfError> {
let plaintext = self.to_bytes().await?;
std::fs::write(path, plaintext)?;
Ok(())
}
}
#[cfg(feature = "kas-client")]
pub struct TdfDecryptFileBuilder {
input_path: std::path::PathBuf,
kas_client: Option<KasClient>,
max_payload_size: u64,
}
#[cfg(feature = "kas-client")]
impl TdfDecryptFileBuilder {
pub(crate) fn new(input_path: std::path::PathBuf) -> Self {
Self {
input_path,
kas_client: None,
max_payload_size: DEFAULT_MAX_PAYLOAD_SIZE,
}
}
#[must_use]
pub fn kas_client(mut self, client: KasClient) -> Self {
self.kas_client = Some(client);
self
}
#[must_use]
pub fn max_payload_size(mut self, limit: u64) -> Self {
self.max_payload_size = limit;
self
}
pub async fn to_bytes(self) -> Result<Vec<u8>, TdfError> {
let kas_client = self
.kas_client
.ok_or_else(|| TdfError::MissingRequiredField {
field: "kas_client",
})?;
let mut archive =
TdfArchive::open(self.input_path)?.with_max_payload_size(self.max_payload_size);
let entry = archive.by_index()?;
entry.decrypt_with_kas(&kas_client).await
}
pub async fn to_file(self, output_path: impl AsRef<Path>) -> Result<(), TdfError> {
let plaintext = self.to_bytes().await?;
std::fs::write(output_path, plaintext)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::NamedTempFile;
#[test]
fn test_encrypt_to_bytes() -> Result<(), Box<dyn std::error::Error>> {
let data = b"Hello, TDF!";
let encrypted = Tdf::encrypt(data)
.kas_url("https://kas.example.com")
.to_bytes()?;
assert!(!encrypted.is_empty());
Ok(())
}
#[test]
fn test_encrypt_to_file() -> Result<(), Box<dyn std::error::Error>> {
let temp_file = NamedTempFile::new()?;
let data = b"Hello, TDF!";
Tdf::encrypt(data)
.kas_url("https://kas.example.com")
.to_file(temp_file.path())?;
assert!(temp_file.path().exists());
Ok(())
}
#[test]
fn test_encrypt_file() -> Result<(), Box<dyn std::error::Error>> {
let input_file = NamedTempFile::new()?;
let output_file = NamedTempFile::new()?;
std::fs::write(input_file.path(), b"File contents")?;
Tdf::encrypt_file(input_file.path(), output_file.path())
.kas_url("https://kas.example.com")
.build()?;
assert!(output_file.path().exists());
Ok(())
}
#[test]
fn test_missing_kas_url_error() {
let data = b"Hello, TDF!";
let result = Tdf::encrypt(data).to_bytes();
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.error_code(), "OPENTDF_E_FIELD_REQUIRED");
assert!(err.to_string().contains("kas_url"));
}
#[test]
fn test_with_policy() -> Result<(), Box<dyn std::error::Error>> {
let policy = Policy::new(
"test-uuid".to_string(),
vec![],
vec!["user@example.com".to_string()],
);
let temp_file = NamedTempFile::new()?;
Tdf::encrypt(b"Test data")
.kas_url("https://kas.example.com")
.policy(policy)
.mime_type("text/plain")
.to_file(temp_file.path())?;
assert!(temp_file.path().exists());
Ok(())
}
#[cfg(feature = "kas-client")]
#[tokio::test]
async fn decrypt_builders_honour_max_payload_size() -> Result<(), Box<dyn std::error::Error>> {
fn kas_client() -> KasClient {
let config = crate::kas_discovery::OpentdfConfiguration::for_kas_connect(
"https://kas.example.com",
);
match KasClient::new(&config, "token") {
Ok(client) => client,
Err(e) => panic!("KAS client: {e}"),
}
}
let encrypted = Tdf::encrypt(b"more than eight bytes of payload")
.kas_url("https://kas.example.com")
.to_bytes()?;
let err = Tdf::decrypt(encrypted.clone())
.kas_client(kas_client())
.max_payload_size(8)
.to_bytes()
.await
.expect_err("payload is over the limit");
assert!(
matches!(&err, TdfError::MemberTooLarge { limit: 8, .. }),
"{err:?}"
);
let temp_file = NamedTempFile::new()?;
std::fs::write(temp_file.path(), &encrypted)?;
let err = Tdf::decrypt_file(temp_file.path())
.kas_client(kas_client())
.max_payload_size(8)
.to_bytes()
.await
.expect_err("payload is over the limit");
assert!(
matches!(&err, TdfError::MemberTooLarge { limit: 8, .. }),
"{err:?}"
);
Ok(())
}
}