use quick_xml::events::BytesText;
use quick_xml::Writer;
use serde::Deserialize;
use std::io::{self, Write};
use crate::crypto::{Crypto, CryptoProvider};
use crate::key_info::{EncryptedKeyInfo, KeyInfo};
use crate::schema::Assertion;
use crate::service_provider::Error;
use crate::signature::DigestMethod;
use crate::traits::ToXml;
const NAME: &str = "saml2:EncryptedAssertion";
const SCHEMA: (&str, &str) = ("xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion");
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct EncryptedAssertion {
#[serde(rename = "EncryptedData")]
pub data: Option<EncryptedData>,
#[serde(rename = "EncryptedKey")]
pub encrypted_key: Option<EncryptedKey>,
}
impl EncryptedAssertion {
pub fn encrypted_key_info(&self) -> Option<(&CipherValue, &String)> {
self.data.as_ref().and_then(|ed| ed.key_info()).or_else(|| {
self.encrypted_key
.as_ref()
.and_then(|e| e.cipher_data.as_ref().zip(e.encryption_method.as_ref()))
.and_then(|(cd, em)| cd.cipher_value.as_ref().zip(em.algorithm.as_ref()))
})
}
pub fn encrypted_value_info(&self) -> Option<(&CipherValue, &String)> {
self.data.as_ref().and_then(|ed| ed.value_info())
}
pub fn decrypt(
&self,
decryption_key: &<Crypto as CryptoProvider>::PrivateKey,
) -> Result<Assertion, Error> {
let (ekey, method) = self
.encrypted_key_info()
.ok_or(Error::MissingEncryptedKeyInfo)?;
let decrypted_key = Crypto::decrypt_assertion_key_info(ekey, method, decryption_key)?;
let (evalue, method) = self
.encrypted_value_info()
.ok_or(Error::MissingEncryptedValueInfo)?;
let plaintext = Crypto::decrypt_assertion_value_info(evalue, method, &decrypted_key)?;
let assertion_string = match String::from_utf8(plaintext) {
Ok(s) => s,
Err(e) => {
let i = e.utf8_error().valid_up_to();
let mut plaintext = e.into_bytes();
plaintext.truncate(i);
let s =
String::from_utf8(plaintext).map_err(|_| Error::EncryptedAssertionInvalid)?;
let fi = s.find("<").unwrap();
let li = s.rfind(">").unwrap();
s[fi..li + 1].to_owned()
}
};
quick_xml::de::from_str(&assertion_string).map_err(|_e| Error::FailedToDecryptAssertion)
}
}
impl ToXml for EncryptedAssertion {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(NAME)
.with_attribute(SCHEMA)
.write_inner_content(|writer| {
if let Some(encrypted_data) = &self.data {
encrypted_data.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
const ED_NAME: &str = "xenc:EncryptedData";
const ED_SCHEMA: (&str, &str) = ("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct EncryptedData {
#[serde(rename = "@Id")]
pub id: Option<String>,
#[serde(rename = "@Type")]
pub ty: Option<String>,
#[serde(rename = "EncryptionMethod")]
pub encryption_method: Option<EncryptionMethod>,
#[serde(alias = "KeyInfo", alias = "ds:KeyInfo")]
pub key_info: Option<EncryptedKeyInfo>,
#[serde(rename = "CipherData")]
pub cipher_data: Option<CipherData>,
}
impl EncryptedData {
pub fn key_info(&self) -> Option<(&CipherValue, &String)> {
self.key_info
.as_ref()
.and_then(|k| k.encrypted_key.as_ref())
.and_then(|e| e.cipher_data.as_ref().zip(e.encryption_method.as_ref()))
.and_then(|(cd, em)| cd.cipher_value.as_ref().zip(em.algorithm.as_ref()))
}
pub fn value_info(&self) -> Option<(&CipherValue, &String)> {
self.cipher_data
.as_ref()
.zip(self.encryption_method.as_ref())
.and_then(|(cd, em)| cd.cipher_value.as_ref().zip(em.algorithm.as_ref()))
}
}
impl ToXml for EncryptedData {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(ED_NAME)
.with_attribute(ED_SCHEMA)
.with_attributes(self.id.as_deref().map(|id| ("Id", id)))
.with_attributes(self.ty.as_deref().map(|ty| ("Type", ty)))
.write_inner_content(|writer| {
if let Some(encryption_method) = &self.encryption_method {
encryption_method.write_xml(writer)?;
}
if let Some(key_info) = &self.key_info {
key_info.write_xml(writer)?;
}
if let Some(cipher_data) = &self.cipher_data {
cipher_data.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
const EM_NAME: &str = "xenc:EncryptionMethod";
const EM_SCHEMA: (&str, &str) = ("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct EncryptionMethod {
#[serde(rename = "@Algorithm")]
pub algorithm: Option<String>,
#[serde(rename = "DigestMethod")]
pub digest_method: Option<DigestMethod>,
}
impl ToXml for EncryptionMethod {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(EM_NAME)
.with_attribute(EM_SCHEMA)
.with_attributes(self.algorithm.as_deref().map(|a| ("Algorithm", a)))
.write_inner_content(|writer| {
if let Some(digest_method) = &self.digest_method {
digest_method.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
const CD_NAME: &str = "xenc:CipherData";
const CD_SCHEMA: (&str, &str) = ("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct CipherData {
#[serde(rename = "CipherValue")]
pub cipher_value: Option<CipherValue>,
}
impl ToXml for CipherData {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(CD_NAME)
.with_attribute(CD_SCHEMA)
.write_inner_content(|writer| {
if let Some(cipher_value) = &self.cipher_value {
cipher_value.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
const CV_NAME: &str = "xenc:CipherValue";
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct CipherValue {
#[serde(rename = "$value")]
pub value: String,
}
impl ToXml for CipherValue {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(CV_NAME)
.write_text_content(BytesText::new(&self.value))?;
Ok(())
}
}
const EK_NAME: &str = "xenc:EncryptedKey";
const EK_SCHEMA: (&str, &str) = ("xmlns:xenc", "http://www.w3.org/2001/04/xmlenc#");
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct EncryptedKey {
#[serde(rename = "@Id")]
pub id: Option<String>,
#[serde(rename = "@Recipient")]
pub recipient: Option<String>,
#[serde(rename = "EncryptionMethod")]
pub encryption_method: Option<EncryptionMethod>,
#[serde(rename = "KeyInfo")]
pub key_info: Option<KeyInfo>,
#[serde(rename = "CipherData")]
pub cipher_data: Option<CipherData>,
}
impl ToXml for EncryptedKey {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(EK_NAME)
.with_attribute(EK_SCHEMA)
.with_attributes(self.id.as_deref().map(|id| ("Id", id)))
.with_attributes(self.recipient.as_deref().map(|r| ("Recipient", r)))
.write_inner_content(|writer| {
if let Some(encryption_method) = &self.encryption_method {
encryption_method.write_xml(writer)?;
}
if let Some(key_info) = &self.key_info {
key_info.write_xml(writer)?;
}
if let Some(cipher_data) = &self.cipher_data {
cipher_data.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
#[cfg(test)]
mod test {
use crate::schema::Response;
#[test]
fn test_encrypted_assertion_key_info() {
let response_xml = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/test_vectors/response_encrypted.xml",
));
let response: Response = response_xml
.parse()
.expect("failed to parse response_encrypted.xml");
let encrypted_assertion = response
.encrypted_assertion
.expect("EncryptedAssertion missing");
let key_info = encrypted_assertion.encrypted_key_info();
let key_info_exists = key_info.is_some();
assert!(key_info_exists, "KeyInfo missing on EncryptedAssertion");
}
}