pub mod authn_request;
mod conditions;
mod encrypted_assertion;
mod issuer;
mod name_id_policy;
mod requested_authn_context;
mod response;
mod subject;
pub use authn_request::AuthnRequest;
pub use conditions::*;
pub use encrypted_assertion::{CipherValue, EncryptedAssertion, EncryptedKey};
pub use issuer::Issuer;
pub use name_id_policy::NameIdPolicy;
pub use requested_authn_context::{AuthnContextComparison, RequestedAuthnContext};
pub use response::Response;
pub use subject::*;
use crate::attribute::Attribute;
use crate::signature::Signature;
use crate::traits::ToXml;
use chrono::prelude::*;
use serde::Deserialize;
use quick_xml::events::BytesText;
use quick_xml::Writer;
use std::io::{self, Write};
use std::str::FromStr;
use thiserror::Error;
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct NameID {
#[serde(rename = "Format")]
pub format: Option<String>,
#[serde(rename = "$value")]
pub value: String,
}
impl NameID {
fn name() -> &'static str {
"saml2:NameID"
}
fn schema() -> &'static [(&'static str, &'static str)] {
&[("xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion")]
}
}
impl ToXml for NameID {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(NameID::name())
.with_attributes(NameID::schema().iter().copied())
.with_attributes(self.format.as_deref().map(|format| ("Format", format)))
.write_text_content(BytesText::new(&self.value))?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct LogoutRequest {
#[serde(rename = "@ID")]
pub id: Option<String>,
#[serde(rename = "@Version")]
pub version: Option<String>,
#[serde(rename = "@IssueInstant")]
pub issue_instant: Option<chrono::DateTime<Utc>>,
#[serde(rename = "@Destination")]
pub destination: Option<String>,
#[serde(rename = "Issuer")]
pub issuer: Option<Issuer>,
#[serde(rename = "Signature")]
pub signature: Option<Signature>,
#[serde(rename = "@SessionIndex")]
pub session_index: Option<String>,
#[serde(rename = "NameID")]
pub name_id: Option<NameID>,
}
#[derive(Debug, Error)]
pub enum LogoutRequestError {
#[error("Failed to deserialize LogoutRequest: {:?}", source)]
ParseError {
#[from]
source: quick_xml::DeError,
},
}
impl FromStr for LogoutRequest {
type Err = LogoutRequestError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(quick_xml::de::from_str(s)?)
}
}
const LOGOUT_REQUEST_NAME: &str = "saml2p:LogoutRequest";
const SESSION_INDEX_NAME: &str = "saml2p:SessionIndex";
const PROTOCOL_SCHEMA: (&str, &str) = ("xmlns:saml2p", "urn:oasis:names:tc:SAML:2.0:protocol");
impl ToXml for LogoutRequest {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
let issue_instant = self
.issue_instant
.map(|t| t.to_rfc3339_opts(SecondsFormat::Millis, true));
writer
.create_element(LOGOUT_REQUEST_NAME)
.with_attribute(PROTOCOL_SCHEMA)
.with_attributes(self.id.as_deref().map(|id| ("ID", id)))
.with_attributes(self.version.as_deref().map(|v| ("Version", v)))
.with_attributes(issue_instant.as_deref().map(|v| ("IssueInstant", v)))
.with_attributes(self.destination.as_deref().map(|v| ("Destination", v)))
.write_inner_content(|writer| {
if let Some(issuer) = &self.issuer {
issuer.write_xml(writer)?;
}
if let Some(signature) = &self.signature {
signature.write_xml(writer)?;
}
if let Some(session) = &self.session_index {
writer
.create_element(SESSION_INDEX_NAME)
.write_text_content(BytesText::new(session))?;
}
if let Some(name_id) = &self.name_id {
name_id.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Assertion {
#[serde(rename = "@ID")]
pub id: String,
#[serde(rename = "@IssueInstant")]
pub issue_instant: DateTime<Utc>,
#[serde(rename = "@Version")]
pub version: String,
#[serde(rename = "Issuer")]
pub issuer: Issuer,
#[serde(rename = "Signature")]
pub signature: Option<Signature>,
#[serde(rename = "Subject")]
pub subject: Option<Subject>,
#[serde(rename = "Conditions")]
pub conditions: Option<Conditions>,
#[serde(rename = "AuthnStatement")]
pub authn_statements: Option<Vec<AuthnStatement>>,
#[serde(rename = "AttributeStatement")]
pub attribute_statements: Option<Vec<AttributeStatement>>,
}
impl Assertion {
fn name() -> &'static str {
"saml2:Assertion"
}
fn schema() -> &'static [(&'static str, &'static str)] {
&[
("xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion"),
("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"),
]
}
}
impl FromStr for Assertion {
type Err = Box<dyn std::error::Error>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(quick_xml::de::from_str(s)?)
}
}
impl ToXml for Assertion {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
let issue_instant = self
.issue_instant
.to_rfc3339_opts(SecondsFormat::Millis, true);
writer
.create_element(Assertion::name())
.with_attributes(Assertion::schema().iter().copied())
.with_attribute(("ID", self.id.as_str()))
.with_attribute(("Version", self.version.as_str()))
.with_attribute(("IssueInstant", issue_instant.as_str()))
.write_inner_content(|writer| {
self.issuer.write_xml(writer)?;
if let Some(signature) = &self.signature {
signature.write_xml(writer)?;
}
if let Some(subject) = &self.subject {
subject.write_xml(writer)?;
}
if let Some(conditions) = &self.conditions {
conditions.write_xml(writer)?;
}
if let Some(statements) = &self.authn_statements {
for statement in statements {
statement.write_xml(writer)?;
}
}
if let Some(statements) = &self.attribute_statements {
for statement in statements {
statement.write_xml(writer)?;
}
}
Ok(())
})?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct AttributeStatement {
#[serde(rename = "Attribute", default)]
pub attributes: Vec<Attribute>,
}
impl AttributeStatement {
fn name() -> &'static str {
"saml2:AttributeStatement"
}
fn schema() -> &'static [(&'static str, &'static str)] {
&[("xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion")]
}
}
impl ToXml for AttributeStatement {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(AttributeStatement::name())
.with_attributes(AttributeStatement::schema().iter().copied())
.write_inner_content(|writer| {
for attr in &self.attributes {
attr.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct AuthnStatement {
#[serde(rename = "@AuthnInstant")]
pub authn_instant: Option<chrono::DateTime<Utc>>,
#[serde(rename = "@SessionIndex")]
pub session_index: Option<String>,
#[serde(rename = "@SessionNotOnOrAfter")]
pub session_not_on_or_after: Option<chrono::DateTime<Utc>>,
#[serde(rename = "SubjectLocality")]
pub subject_locality: Option<SubjectLocality>,
#[serde(rename = "AuthnContext")]
pub authn_context: Option<AuthnContext>,
}
impl AuthnStatement {
fn name() -> &'static str {
"saml2:AuthnStatement"
}
}
impl ToXml for AuthnStatement {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
let authn_instant = self
.authn_instant
.map(|t| t.to_rfc3339_opts(SecondsFormat::Millis, true));
let session_not_on_or_after = self
.session_not_on_or_after
.map(|t| t.to_rfc3339_opts(SecondsFormat::Millis, true));
writer
.create_element(AuthnStatement::name())
.with_attributes(self.session_index.as_deref().map(|v| ("SessionIndex", v)))
.with_attributes(authn_instant.as_deref().map(|v| ("AuthnInstant", v)))
.with_attributes(
session_not_on_or_after
.as_deref()
.map(|v| ("SessionNotOnOrAfter", v)),
)
.write_inner_content(|writer| {
if let Some(context) = &self.authn_context {
context.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct SubjectLocality {
#[serde(rename = "@Address")]
pub address: Option<String>,
#[serde(rename = "@DNSName")]
pub dns_name: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct AuthnContext {
#[serde(rename = "AuthnContextClassRef")]
pub value: Option<AuthnContextClassRef>,
}
impl AuthnContext {
fn name() -> &'static str {
"saml2:AuthnContext"
}
}
impl ToXml for AuthnContext {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
if let Some(value) = &self.value {
writer
.create_element(AuthnContext::name())
.write_inner_content(|writer| value.write_xml(writer))?;
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct AuthnContextClassRef {
#[serde(rename = "$value")]
pub value: Option<String>,
}
impl AuthnContextClassRef {
fn name() -> &'static str {
"saml2:AuthnContextClassRef"
}
}
impl ToXml for AuthnContextClassRef {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
if let Some(value) = &self.value {
writer
.create_element(AuthnContextClassRef::name())
.write_text_content(BytesText::new(value))?;
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct AuthnContextDeclRef {
#[serde(rename = "$value")]
pub value: Option<String>,
}
impl AuthnContextDeclRef {
fn name() -> &'static str {
"saml2:AuthnContextDeclRef"
}
}
impl ToXml for AuthnContextDeclRef {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
if let Some(value) = &self.value {
writer
.create_element(AuthnContextDeclRef::name())
.write_text_content(BytesText::new(value))?;
}
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct Status {
#[serde(rename = "StatusCode")]
pub status_code: StatusCode,
#[serde(rename = "StatusMessage")]
pub status_message: Option<StatusMessage>,
#[serde(rename = "StatusDetail")]
pub status_detail: Option<StatusDetail>,
}
impl Status {
fn name() -> &'static str {
"saml2p:Status"
}
}
impl ToXml for Status {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(Status::name())
.write_inner_content(|writer| {
self.status_code.write_xml(writer)?;
if let Some(status_message) = self.status_message.as_ref() {
status_message.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct StatusCode {
#[serde(rename = "@Value")]
pub value: Option<String>,
}
impl StatusCode {
fn name() -> &'static str {
"saml2p:StatusCode"
}
}
impl ToXml for StatusCode {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
writer
.create_element(StatusCode::name())
.with_attributes(self.value.as_deref().map(|value| ("Value", value)))
.write_empty()?;
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct StatusMessage {
#[serde(rename = "$text")]
pub value: Option<String>,
}
impl StatusMessage {
fn name() -> &'static str {
"saml2p:StatusMessage"
}
}
impl ToXml for StatusMessage {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
let element = writer.create_element(StatusMessage::name());
match &self.value {
Some(content) => element.write_text_content(BytesText::new(content))?,
None => element.write_inner_content(|_| Ok(()))?,
};
Ok(())
}
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct StatusDetail {
#[serde(rename = "@Children")]
pub children: Option<String>,
}
#[derive(Clone, Debug, Deserialize, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub struct LogoutResponse {
#[serde(rename = "@ID")]
pub id: Option<String>,
#[serde(rename = "@InResponseTo")]
pub in_response_to: Option<String>,
#[serde(rename = "@Version")]
pub version: Option<String>,
#[serde(rename = "@IssueInstant")]
pub issue_instant: Option<chrono::DateTime<Utc>>,
#[serde(rename = "@Destination")]
pub destination: Option<String>,
#[serde(rename = "@Consent")]
pub consent: Option<String>,
#[serde(rename = "Issuer")]
pub issuer: Option<Issuer>,
#[serde(rename = "Signature")]
pub signature: Option<Signature>,
#[serde(rename = "Status")]
pub status: Option<Status>,
}
#[derive(Debug, Error)]
pub enum LogoutResponseError {
#[error("Failed to deserialize LogoutResponse: {:?}", source)]
ParseError {
#[from]
source: quick_xml::DeError,
},
}
impl FromStr for LogoutResponse {
type Err = LogoutResponseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(quick_xml::de::from_str(s)?)
}
}
const LOGOUT_RESPONSE_NAME: &str = "saml2p:LogoutResponse";
impl ToXml for LogoutResponse {
fn write_xml<W: Write>(&self, writer: &mut Writer<W>) -> io::Result<()> {
let issue_instant = self
.issue_instant
.map(|t| t.to_rfc3339_opts(SecondsFormat::Millis, true));
writer
.create_element(LOGOUT_RESPONSE_NAME)
.with_attribute(PROTOCOL_SCHEMA)
.with_attributes(self.id.as_deref().map(|id| ("ID", id)))
.with_attributes(self.in_response_to.as_deref().map(|v| ("InResponseTo", v)))
.with_attributes(self.version.as_deref().map(|v| ("Version", v)))
.with_attributes(issue_instant.as_deref().map(|v| ("IssueInstant", v)))
.with_attributes(self.destination.as_deref().map(|v| ("Destination", v)))
.with_attributes(self.consent.as_deref().map(|v| ("Consent", v)))
.write_inner_content(|writer| {
if let Some(issuer) = &self.issuer {
issuer.write_xml(writer)?;
}
if let Some(signature) = &self.signature {
signature.write_xml(writer)?;
}
if let Some(status) = &self.status {
status.write_xml(writer)?;
}
Ok(())
})?;
Ok(())
}
}
#[cfg(test)]
mod test {
use super::{LogoutRequest, LogoutResponse};
use crate::traits::ToXml;
#[test]
fn test_deserialize_serialize_logout_request() {
let request_xml = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/test_vectors/logout_request.xml",
));
let expected_request: LogoutRequest = request_xml
.parse()
.expect("failed to parse logout_request.xml");
let serialized_request = expected_request
.to_string()
.expect("failed to convert request to xml");
let actual_request: LogoutRequest = serialized_request
.parse()
.expect("failed to re-parse request");
assert_eq!(expected_request, actual_request);
}
#[test]
fn test_deserialize_serialize_logout_response() {
let response_xml = include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/test_vectors/logout_response.xml",
));
let expected_response: LogoutResponse = response_xml
.parse()
.expect("failed to parse logout_response.xml");
let serialized_response = expected_response
.to_string()
.expect("failed to convert Response to xml");
let actual_response: LogoutResponse = serialized_response
.parse()
.expect("failed to re-parse Response");
assert_eq!(expected_response, actual_response);
}
}