use crate::policy::{Policy, PolicyError};
use opentdf_crypto::{
PayloadKey, calculate_policy_binding, calculate_root_signature, verify_root_signature,
};
pub use opentdf_protocol::{
EncryptionInformation, EncryptionMethod, IntegrityInformation, KeyAccess, Payload,
PolicyBinding, RootSignature, Segment, TdfManifest,
};
pub trait IntegrityInformationExt {
fn generate_root_signature(
&mut self,
gmac_tags: &[Vec<u8>],
payload_key: &[u8],
) -> Result<(), String>;
fn verify_root_signature(
&self,
gmac_tags: &[Vec<u8>],
payload_key: &[u8],
) -> Result<(), String>;
}
impl IntegrityInformationExt for IntegrityInformation {
fn generate_root_signature(
&mut self,
gmac_tags: &[Vec<u8>],
payload_key: &[u8],
) -> Result<(), String> {
let payload_key = PayloadKey::from_slice(payload_key)
.map_err(|e| format!("Invalid payload key: {}", e))?;
let signature = calculate_root_signature(gmac_tags, &payload_key)
.map_err(|e| format!("Failed to calculate root signature: {}", e))?;
self.root_signature.sig = signature;
self.root_signature.alg = "HS256".to_string();
Ok(())
}
fn verify_root_signature(
&self,
gmac_tags: &[Vec<u8>],
payload_key: &[u8],
) -> Result<(), String> {
let payload_key = PayloadKey::from_slice(payload_key)
.map_err(|e| format!("Invalid payload key: {}", e))?;
verify_root_signature(gmac_tags, &payload_key, &self.root_signature.sig)
.map_err(|e| format!("Signature verification failed: {}", e))
}
}
pub trait KeyAccessExt {
fn generate_policy_binding_raw(&mut self, policy: &str, key: &[u8]) -> Result<(), String>;
fn generate_policy_binding(&mut self, policy: &Policy, key: &[u8]) -> Result<(), PolicyError>;
}
impl KeyAccessExt for KeyAccess {
fn generate_policy_binding_raw(&mut self, policy: &str, key: &[u8]) -> Result<(), String> {
let binding = calculate_policy_binding(policy, key)
.map_err(|e| format!("Failed to calculate policy binding: {}", e))?;
self.policy_binding.hash = binding;
self.policy_binding.alg = "HS256".to_string();
Ok(())
}
fn generate_policy_binding(&mut self, policy: &Policy, key: &[u8]) -> Result<(), PolicyError> {
let policy_json = policy.to_json()?;
self.generate_policy_binding_raw(&policy_json, key)
.map_err(|e| PolicyError::EvaluationError {
reason: format!("Failed to generate policy binding: {}", e),
attribute: None,
})?;
Ok(())
}
}
pub trait TdfManifestExt {
fn set_policy(&mut self, policy: &Policy) -> Result<(), PolicyError>;
fn get_policy(&self) -> Result<Policy, PolicyError>;
}
impl TdfManifestExt for TdfManifest {
fn set_policy(&mut self, policy: &Policy) -> Result<(), PolicyError> {
let policy_json = policy.to_json()?;
self.set_policy_raw(&policy_json);
Ok(())
}
fn get_policy(&self) -> Result<Policy, PolicyError> {
let policy_json = match self.get_policy_raw() {
Ok(json) => json,
Err(e) => {
return Err(PolicyError::SerializationError(serde_json::Error::io(
std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()),
)));
}
};
Policy::from_json(&policy_json)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_key_access_metadata() {
let mut key_access = KeyAccess::new("http://example.com".to_string());
assert!(key_access.encrypted_metadata.is_none());
key_access.set_encrypted_metadata("test metadata");
assert!(key_access.encrypted_metadata.is_some());
key_access.clear_encrypted_metadata();
assert!(key_access.encrypted_metadata.is_none());
}
#[test]
fn test_key_access_policy_binding_raw() {
use crate::manifest::KeyAccessExt;
let mut key_access = KeyAccess::new("http://kas.example.com:4000".to_string());
let policy = r#"{"uuid":"test","body":{"attributes":[],"dissem":["user@example.com"]}}"#;
let key = b"test-key-for-hmac";
key_access.generate_policy_binding_raw(policy, key).unwrap();
assert!(!key_access.policy_binding.hash.is_empty());
assert_eq!(key_access.policy_binding.alg, "HS256");
}
#[test]
fn test_key_access_policy_binding_object() {
use crate::manifest::KeyAccessExt;
use crate::policy::{Policy, PolicyBody};
let mut key_access = KeyAccess::new("http://kas.example.com:4000".to_string());
let policy = Policy {
uuid: "test".to_string(),
valid_from: None,
valid_to: None,
body: PolicyBody {
attributes: vec![],
dissem: vec!["user@example.com".to_string()],
},
};
let key = b"test-key-for-hmac";
key_access.generate_policy_binding(&policy, key).unwrap();
assert!(!key_access.policy_binding.hash.is_empty());
assert_eq!(key_access.policy_binding.alg, "HS256");
}
#[test]
fn test_manifest_serialization() {
let manifest = TdfManifest::new(
"0.payload".to_string(),
"http://kas.example.com:4000".to_string(),
);
let json = serde_json::to_string_pretty(&manifest).unwrap();
let deserialized: TdfManifest = serde_json::from_str(&json).unwrap();
assert_eq!(manifest.payload.url, deserialized.payload.url);
assert_eq!(
manifest.encryption_information.key_access[0].url,
deserialized.encryption_information.key_access[0].url
);
}
#[test]
fn test_payload_omits_tdf_spec_version_by_default() {
let manifest = TdfManifest::new(
"0.payload".to_string(),
"http://kas.example.com:4000".to_string(),
);
assert!(manifest.payload.tdf_spec_version.is_none());
let value = serde_json::to_value(&manifest).unwrap();
let payload = value.get("payload").expect("payload object");
assert!(
payload.get("tdf_spec_version").is_none(),
"default encrypt path must not serialize payload.tdf_spec_version: {payload}"
);
assert_eq!(
value.get("schemaVersion").and_then(|v| v.as_str()),
Some("3.0.0")
);
let with_spec = r#"{
"payload": {
"type": "reference",
"url": "0.payload",
"protocol": "zip",
"isEncrypted": true,
"tdf_spec_version": "4.3.0"
},
"encryptionInformation": {
"type": "split",
"keyAccess": [],
"method": {"algorithm": "AES-256-GCM", "isStreamable": true, "iv": ""},
"integrityInformation": {
"rootSignature": {"alg": "HS256", "sig": ""},
"segmentHashAlg": "GMAC",
"segments": [],
"segmentSizeDefault": 0,
"encryptedSegmentSizeDefault": 0
},
"policy": ""
},
"schemaVersion": "4.3.0"
}"#;
let read: TdfManifest = serde_json::from_str(with_spec).unwrap();
assert_eq!(read.payload.tdf_spec_version.as_deref(), Some("4.3.0"));
}
#[test]
fn test_policy_raw_encoding() {
let mut manifest = TdfManifest::new(
"0.payload".to_string(),
"http://kas.example.com:4000".to_string(),
);
let policy = r#"{"uuid":"test","body":{"attributes":[],"dissem":["user@example.com"]}}"#;
manifest.set_policy_raw(policy);
let decoded_policy = manifest.get_policy_raw().unwrap();
assert_eq!(policy, decoded_policy);
}
#[test]
fn test_policy_object_encoding() {
use crate::manifest::TdfManifestExt;
use crate::policy::{Policy, PolicyBody};
let mut manifest = TdfManifest::new(
"0.payload".to_string(),
"http://kas.example.com:4000".to_string(),
);
let policy = Policy {
uuid: "test".to_string(),
valid_from: None,
valid_to: None,
body: PolicyBody {
attributes: vec![],
dissem: vec!["user@example.com".to_string()],
},
};
manifest.set_policy(&policy).unwrap();
let retrieved_policy = manifest.get_policy().unwrap();
assert_eq!(policy.uuid, retrieved_policy.uuid);
assert_eq!(policy.body.dissem, retrieved_policy.body.dissem);
}
}