uftp 0.2.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
Documentation
//! The `SignedMessage` wrapper, and the two ways across the trust boundary: [`seal`] and
//! [`open`].
//!
//! [`open`] is the only public path from received bytes to a [`Message`]. It
//! works in this order, and each step runs only if the one before it succeeded:
//! 1. parse the wrapper (400)
//! 2. look up the sender's keys (419)
//! 3. verify the body strictly under any of them (401)
//! 4. decode the inner message by the schema (400)
//!
//! From here on the message is valid UFTP from a verified sender, so a failure is a
//! [`RejectKind::Rule`] rejection that carries the message and answers with a Rejected
//! response (`[UFTP App. 4 §4]`):
//! 5. bind the inner sender to the wrapper's (`Invalid Message`)
//! 6. check that the wrapper's role may send this message type (`Invalid Message`)
//! 7. check the specification's rules ([`Message::validate`])
//! 8. check that the recipient is served here (`Unknown Recipient`)

use base64::Engine as _;
use base64::engine::general_purpose::STANDARD;
use jiff::{SignedDuration, Timestamp};

use crate::cs1::{PublicKeys, SigningKey};
use crate::directory::{IntoKeys, KeyLookupError};
use crate::error::{RejectKind, Rejection};
use crate::msg::{DecodeOptions, Message, Reply, decode_payload};
use crate::reason::RejectionReason;
use crate::types::{InternetDomain, MessageUuid, Role};
use crate::xml::attrs::{Attrs, children};
use crate::xml::reader::{self, Limits};

/// The secure wrapper every message travels in `[XSD SignedMessageType]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignedMessage {
    /// The sender's domain; the key is looked up by it.
    pub sender_domain: InternetDomain,
    /// The sender's role; the key is looked up by it too.
    pub sender_role: Role,
    /// The sealed inner message: signature, then the XML.
    pub body: Vec<u8>,
}

impl SignedMessage {
    /// The wrapper as an XML document, ready to POST.
    #[must_use]
    pub fn to_xml(&self) -> String {
        // Domain, role and Base64 never need escaping.
        format!(
            r#"<?xml version="1.0" encoding="UTF-8"?><SignedMessage SenderDomain="{}" SenderRole="{}" Body="{}"/>"#,
            self.sender_domain,
            self.sender_role,
            STANDARD.encode(&self.body)
        )
    }

    fn from_xml(document: &[u8], limits: &Limits) -> Result<Self, Rejection> {
        let root = reader::parse(document, limits)?;
        if root.name != "SignedMessage" {
            return Err(Rejection::schema(
                "[XSD SignedMessageType]",
                format!(
                    "The document is <{}>, not a <SignedMessage>.",
                    crate::error::name(&root.name)
                ),
            ));
        }
        children(&root, "SignedMessage", &[])?;
        let mut a = Attrs::new(&root, "SignedMessage");
        let sender_domain = a.req("SenderDomain")?;
        let sender_role = a.req("SenderRole")?;
        let body64 = a.req_string("Body")?;
        a.finish()?;
        // xs:base64Binary allows whitespace between characters.
        let compact: Vec<u8> = body64
            .bytes()
            .filter(|b| !b.is_ascii_whitespace())
            .collect();
        // No size check here: the whole document is within `limits.max_bytes()`, so the
        // Body decodes to at most three quarters of it.
        let body = STANDARD.decode(&compact).map_err(|_| {
            Rejection::schema(
                "[XSD SignedMessageType] Body is xs:base64Binary",
                "The Body is not valid Base64.",
            )
            .at("SignedMessage/@Body")
        })?;
        Ok(Self {
            sender_domain,
            sender_role,
            body,
        })
    }
}

/// Encodes `message`, signs it with `key` and wraps it.
///
/// # Errors
/// - If `role` may not send this message type.
/// - If the message breaks a rule the types cannot express; see [`Message::encode`].
pub fn seal(message: &Message, role: Role, key: &SigningKey) -> Result<SignedMessage, Rejection> {
    check_role(message, role)?;
    let xml = message.encode()?;
    Ok(SignedMessage {
        sender_domain: message.meta().sender_domain.clone(),
        sender_role: role,
        body: key.seal(xml.as_bytes()),
    })
}

fn check_role(message: &Message, role: Role) -> Result<(), Rejection> {
    if message.allowed_senders().contains(&role) {
        Ok(())
    } else {
        Err(Rejection::rule(
            RejectionReason::InvalidMessage,
            "[UFTP §3.5 Invalid Message] message type by sender role",
            format!("The {} role may not send a {}.", role, message.type_name()),
        ))
    }
}

/// How [`open`] reads: limits, XSD relaxations and the domains this endpoint serves.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct OpenOptions {
    /// Bounds on the wrapper and on the decoded body.
    pub limits: Limits,
    /// Relaxations of recorded XSD defects; all off by default.
    pub decode: DecodeOptions,
    /// The RecipientDomains this endpoint serves. A message for another domain is rejected
    /// with `Unknown Recipient`. Empty means any domain; set it in production.
    pub recipients: Vec<InternetDomain>,
}

impl OpenOptions {
    /// Options that accept messages for `domain` only.
    #[must_use]
    pub fn for_recipient(domain: InternetDomain) -> Self {
        Self {
            recipients: vec![domain],
            ..Self::default()
        }
    }

    /// Adds a served domain, for an endpoint shared by several participants.
    #[must_use]
    pub fn also_for(mut self, domain: InternetDomain) -> Self {
        self.recipients.push(domain);
        self
    }

    /// Replaces the limits.
    #[must_use]
    pub fn with_limits(mut self, limits: Limits) -> Self {
        self.limits = limits;
        self
    }

    /// Replaces the decode options.
    #[must_use]
    pub fn with_decode(mut self, decode: DecodeOptions) -> Self {
        self.decode = decode;
        self
    }

    fn serves(&self, domain: &InternetDomain) -> bool {
        self.recipients.is_empty() || self.recipients.contains(domain)
    }
}

/// A message whose signature verified and whose XML is valid UFTP from the sender it
/// claims, as [`open`] returns it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Opened {
    message: Message,
    sender_domain: InternetDomain,
    sender_role: Role,
    responder: InternetDomain,
    sealed: Vec<u8>,
    signature: [u8; 64],
}

impl Opened {
    /// The message.
    #[must_use]
    pub fn message(&self) -> &Message {
        &self.message
    }

    /// The message, consuming the rest.
    #[must_use]
    pub fn into_message(self) -> Message {
        self.message
    }

    /// The sender's domain, verified by the signature.
    #[must_use]
    pub fn sender_domain(&self) -> &InternetDomain {
        &self.sender_domain
    }

    /// The sender's role, verified by the signature.
    #[must_use]
    pub fn sender_role(&self) -> Role {
        self.sender_role
    }

    /// The exact sealed bytes received: keep them as evidence of what the sender signed.
    #[must_use]
    pub fn sealed(&self) -> &[u8] {
        &self.sealed
    }

    /// The 64-byte Ed25519 signature. Ed25519 is deterministic, so two deliveries of the
    /// same signed bytes carry the same signature: [`ReplayGuard`](crate::ReplayGuard)
    /// uses it as the content fingerprint.
    #[must_use]
    pub fn signature(&self) -> &[u8; 64] {
        &self.signature
    }

    /// The message id.
    #[must_use]
    pub fn message_id(&self) -> MessageUuid {
        self.message.meta().message_id
    }

    /// The conversation id.
    #[must_use]
    pub fn conversation_id(&self) -> MessageUuid {
        self.message.meta().conversation_id
    }

    /// When the sender says it created the message.
    #[must_use]
    pub fn timestamp(&self) -> Timestamp {
        self.message.meta().timestamp
    }

    /// Whether the timestamp lies within `max_skew` of `now`, in either direction. For a
    /// complete replay defence use [`ReplayGuard`](crate::ReplayGuard).
    #[must_use]
    pub fn is_fresh(&self, now: Timestamp, max_skew: SignedDuration) -> bool {
        now.duration_since(self.timestamp()).abs() <= max_skew.abs()
    }

    /// The response to this message (see [`Message::reply`]), addressed to the verified
    /// sender and sent from the domain this endpoint answers as. Seal it with
    /// your key and POST it to the sender.
    #[must_use]
    pub fn reply(&self, reply: Reply) -> Option<Message> {
        let mut request = self.message.clone();
        let meta = request.meta_mut();
        meta.sender_domain = self.sender_domain.clone();
        meta.recipient_domain = self.responder.clone();
        request.reply(reply)
    }

    /// Attaches this message to a rejection the application raised itself (an unknown
    /// congestion point, a revoked offer, a replay), so that
    /// [`Rejection::response`] answers it. Only [`RejectKind::Rule`] rejections are
    /// answered; others are returned unchanged.
    #[must_use]
    pub fn reject(&self, rejection: Rejection) -> Rejection {
        rejection.with_bounce(self.clone())
    }
}

/// Opens a received `SignedMessage` document.
///
/// `lookup` returns the published keys of the participant with the given domain and role,
/// one or the two of a rollover ([`IntoKeys`]): `directory.lookup()` over a
/// [`Directory`](crate::Directory), or a closure over DNSSEC-validated DNS. It runs before
/// anything else is trusted.
///
/// # Errors
/// Before the message is trusted, the rejection is a transport error and
/// [`Rejection::response`] is `None`:
/// - [`RejectKind::Schema`] or [`RejectKind::Limits`] (400): the wrapper or the body is
///   not valid UFTP XML or is too large.
/// - [`RejectKind::KeyLookup`] (419): `lookup` failed.
/// - [`RejectKind::Signature`] (401): the body does not verify.
///
/// After that, [`RejectKind::Rule`] (HTTP 200): the inner sender is not the wrapper's, the
/// role may not send this type, a rule of the specification is broken, or the recipient
/// is not served here. Send back [`Rejection::response`].
pub fn open<F, K>(document: &[u8], options: &OpenOptions, lookup: F) -> Result<Opened, Rejection>
where
    F: FnOnce(&InternetDomain, Role) -> Result<K, KeyLookupError>,
    K: IntoKeys,
{
    let wrapper = SignedMessage::from_xml(document, &options.limits)?;
    let keys = lookup(&wrapper.sender_domain, wrapper.sender_role)
        .map_err(|e| key_lookup_failed(&wrapper, &e.to_string()))?
        .into_keys();
    if keys.is_empty() {
        return Err(key_lookup_failed(&wrapper, "the lookup returned no key"));
    }
    let plaintext = verify_any(&keys, &wrapper.body)?;
    let mut signature = [0; 64];
    signature.copy_from_slice(&wrapper.body[..64]); // verify_any refused anything shorter
    let message = decode_payload(plaintext, &options.limits, options.decode)?;

    let inner_recipient = &message.meta().recipient_domain;
    let responder = if options.serves(inner_recipient) {
        inner_recipient.clone()
    } else {
        options.recipients[0].clone()
    };
    let inner_sender = message.meta().sender_domain.clone();
    let opened = Opened {
        message,
        sender_domain: wrapper.sender_domain,
        sender_role: wrapper.sender_role,
        responder,
        sealed: wrapper.body,
        signature,
    };
    let message = &opened.message;
    let checks = || -> Result<(), Rejection> {
        if inner_sender != opened.sender_domain {
            return Err(Rejection::rule(
                RejectionReason::InvalidMessage,
                "[UFTP §4.2.2 SenderDomain] must match the SignedMessage wrapper",
                format!(
                    "The wrapper's SenderDomain is {} but the message's is {inner_sender}.",
                    opened.sender_domain
                ),
            )
            .at(format!("{}/@SenderDomain", message.type_name())));
        }
        check_role(message, opened.sender_role)?;
        message.validate()?;
        let recipient = &message.meta().recipient_domain;
        if !options.serves(recipient) {
            return Err(Rejection::rule(
                RejectionReason::UnknownRecipient,
                "[UFTP §3.5 Unknown Recipient]",
                format!("This endpoint does not handle messages for {recipient}."),
            )
            .at(format!("{}/@RecipientDomain", message.type_name())));
        }
        Ok(())
    };
    match checks() {
        Ok(()) => Ok(opened),
        Err(e) => Err(opened.reject(e)),
    }
}

fn key_lookup_failed(wrapper: &SignedMessage, why: &str) -> Rejection {
    Rejection::new(
        RejectKind::KeyLookup,
        "[UFTP App. 4 §4] sender key lookup",
        format!(
            "No public key for {} as {}: {why}.",
            wrapper.sender_domain, wrapper.sender_role
        ),
    )
}

/// Verifies under each key in turn; the TXT record may list two during a rollover.
fn verify_any<'a>(keys: &[PublicKeys], sealed: &'a [u8]) -> Result<&'a [u8], Rejection> {
    let mut last = None;
    for k in keys {
        match k.signing().open(sealed) {
            Ok(m) => return Ok(m),
            Err(e) => last = Some(e),
        }
    }
    Err(last.expect("keys is not empty"))
}