uftp 0.1.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
//! Rejections: why a value, document or message was refused, and how the refusal travels.

use std::fmt;
use std::num::NonZeroU32;

use jiff::{SignedDuration, Timestamp};

use crate::envelope::Opened;
use crate::msg::{Message, Reply};
use crate::reason::RejectionReason;
use crate::types::MessageUuid;

/// What kind of failure a [`Rejection`] is, and so how it travels back to the sender.
///
/// UFTP 3.1.0, Appendix 4 §4: until a message has been validated as UFTP XML, errors travel
/// as HTTP status codes. After that they travel as a response message with
/// `Result="Rejected"`, and the HTTP exchange itself succeeds (200).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RejectKind {
    /// The XML cannot be parsed or does not follow the UFTP schema (400 Bad Request).
    Schema,
    /// The document exceeds a size, depth or element-count limit (400 Bad Request).
    Limits,
    /// The sealed body does not verify under the sender's key (401 Unauthorized).
    Signature,
    /// The sender's public key could not be looked up (419, temporary).
    KeyLookup,
    /// The request has no Content-Length (411 Length Required).
    LengthRequired,
    /// A request header is refused: a Content-Type other than `text/xml` in UTF-8, or a
    /// Content-Length that is unparsable, repeated with another value, or not the body's
    /// length (400 Bad Request).
    Header,
    /// The sender exceeds the receiver's policy (429 Too Many Requests, temporary).
    RateLimited,
    /// A valid UFTP message breaks a rule of the specification, such as an ISP addressed
    /// twice or a type the sender's role may not send. The transport succeeds (200) and
    /// the answer is a Rejected response; see [`Rejection::response`].
    Rule,
}

impl RejectKind {
    /// The HTTP status code to answer the POST that carried the message with.
    #[must_use]
    pub fn http_status(self) -> u16 {
        match self {
            Self::Schema | Self::Limits | Self::Header => 400,
            Self::Signature => 401,
            Self::LengthRequired => 411,
            Self::KeyLookup => 419,
            Self::RateLimited => 429,
            Self::Rule => 200,
        }
    }

    /// Whether the sender may retry the same message later.
    #[must_use]
    pub fn is_temporary(self) -> bool {
        matches!(self, Self::KeyLookup | Self::RateLimited)
    }
}

/// How a rejection reaches the sender `[UFTP App. 4 §4]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Disposition {
    /// Answer the HTTP request with this status and send nothing else.
    Transport(u16),
    /// Answer the HTTP request with 200, then send a Rejected response message, if
    /// [`Rejection::response`] gives one.
    Respond,
}

/// A refusal, with the rule that was broken and, where there is one, the attribute or
/// element that broke it.
///
/// The message never contains key material or the sealed body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rejection {
    kind: RejectKind,
    rule: &'static str,
    reason: Option<RejectionReason>,
    location: Option<String>,
    message: String,
    bounce: Option<Box<Opened>>,
    /// Whole seconds, rounded up, at least 1 (RFC 9110 §10.2.3 delay-seconds).
    retry_after: Option<NonZeroU32>,
}

impl Rejection {
    /// A refusal of the endpoint's own, such as a 429 from a rate limit or a 400 from a
    /// check the integrator adds. `rule` names what was broken (`"[policy] 10 per
    /// minute"`), `message` says it in one sentence. For a rule of the specification
    /// answered with a Rejected response, use [`because`](Self::because).
    pub fn new(kind: RejectKind, rule: &'static str, message: impl Into<String>) -> Self {
        Self {
            kind,
            rule,
            reason: None,
            location: None,
            message: message.into(),
            bounce: None,
            retry_after: None,
        }
    }

    pub(crate) fn schema(rule: &'static str, message: impl Into<String>) -> Self {
        Self::new(RejectKind::Schema, rule, message)
    }

    pub(crate) fn rule(
        reason: RejectionReason,
        rule: &'static str,
        message: impl Into<String>,
    ) -> Self {
        let mut r = Self::new(RejectKind::Rule, rule, message);
        r.reason = Some(reason);
        r
    }

    pub(crate) fn at(mut self, location: impl Into<String>) -> Self {
        let location = location.into();
        self.location = Some(match self.location.take() {
            Some(inner) => format!("{location}/{inner}"),
            None => location,
        });
        self
    }

    /// A rejection the application raises itself, for a reason the library cannot see:
    /// a barred sender, an unknown congestion point, a revoked offer. Pass it to
    /// [`Opened::reject`] to answer the message it concerns.
    #[must_use]
    pub fn because(reason: RejectionReason, message: impl Into<String>) -> Self {
        let rule = reason.source();
        Self::rule(reason, rule, message)
    }

    pub(crate) fn with_bounce(mut self, opened: Opened) -> Self {
        if self.kind == RejectKind::Rule {
            self.bounce = Some(Box::new(opened));
        }
        self
    }

    /// What kind of failure this is.
    #[must_use]
    pub fn kind(&self) -> RejectKind {
        self.kind
    }

    /// How this rejection reaches the sender.
    #[must_use]
    pub fn disposition(&self) -> Disposition {
        match self.kind {
            RejectKind::Rule => Disposition::Respond,
            k => Disposition::Transport(k.http_status()),
        }
    }

    /// The rule that was broken, citing the specification: `[UFTP §…]` or `[XSD …]`.
    #[must_use]
    pub fn rule_ref(&self) -> &'static str {
        self.rule
    }

    /// The `[UFTP §3.5]` reason, for every [`RejectKind::Rule`] rejection.
    #[must_use]
    pub fn reason(&self) -> Option<&RejectionReason> {
        self.reason.as_ref()
    }

    /// Where the problem is: an element path and attribute, such as
    /// `FlexRequest/ISP[3]/@Start`.
    #[must_use]
    pub fn location(&self) -> Option<&str> {
        self.location.as_deref()
    }

    /// The HTTP status code for this rejection; see [`RejectKind::http_status`].
    #[must_use]
    pub fn http_status(&self) -> u16 {
        self.kind.http_status()
    }

    /// The human-readable sentence.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The text for a response's `RejectionReason`: the `[UFTP §3.5]` reason, then the
    /// sentence, such as `ISP conflict: ISP 5 is addressed twice (5 and 5–8).` It carries
    /// no rule reference and nothing the integrator did not put there.
    #[must_use]
    pub fn rejection_reason(&self) -> String {
        match &self.reason {
            Some(r) => format!("{r}: {}", self.message),
            None => self.message.clone(),
        }
    }

    /// How long a sender should wait before it retries: set on the 429 of a full
    /// [`ReplayGuard`](crate::ReplayGuard) quota, until its oldest entry leaves the
    /// window. `http::response` sends it as `Retry-After`.
    #[must_use]
    pub fn retry_after(&self) -> Option<SignedDuration> {
        self.retry_after
            .map(|s| SignedDuration::from_secs(i64::from(s.get())))
    }

    /// Records `delay`, rounded up to whole seconds, at least 1.
    pub(crate) fn with_retry_after(mut self, delay: SignedDuration) -> Self {
        let ms = u64::try_from(delay.as_millis()).unwrap_or(0);
        let seconds = u32::try_from(ms.div_ceil(1000)).unwrap_or(u32::MAX).max(1);
        self.retry_after = NonZeroU32::new(seconds);
        self
    }

    /// The verified message this rejection is about, when it was raised after the
    /// signature verified: with its sealed bytes, as evidence of what was rejected
    /// (`[UFTP §3.5]`).
    #[must_use]
    pub fn opened(&self) -> Option<&Opened> {
        self.bounce.as_deref()
    }

    /// The signed-to-be Rejected response to send back, addressed to the verified sender
    /// (`[UFTP §4.2.2 SenderDomain]`). `None` when the rejection was raised before the signature verified
    /// (`[UFTP App. 4 §4]`), and for responses and TestMessages, which are never answered.
    #[must_use]
    pub fn response(&self, message_id: MessageUuid, timestamp: Timestamp) -> Option<Message> {
        let opened = self.bounce.as_deref()?;
        opened.reply(Reply::rejected(message_id, timestamp, self))
    }
}

impl fmt::Display for Rejection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(loc) = &self.location {
            write!(f, "{loc}: ")?;
        }
        if let Some(r) = &self.reason {
            write!(f, "{r}: ")?;
        }
        write!(f, "{} {}", self.message, self.rule)
    }
}

impl std::error::Error for Rejection {}

impl From<&Rejection> for String {
    fn from(r: &Rejection) -> Self {
        r.rejection_reason()
    }
}

/// Received text as it may appear inside a rejection: between backticks, with control
/// characters, bidirectional controls and the backtick escaped, and cut after
/// [`QUOTE_CHARS`] characters with `…`. A rejection's text is logged and sent back, so
/// the sender must not be able to forge a log line (CWE-117), disguise text (Trojan
/// Source, CVE-2021-42574) or make the text as large as its document.
pub(crate) fn quote<S: AsRef<str> + ?Sized>(s: &S) -> Quoted<'_> {
    Quoted(s.as_ref(), true)
}

/// A received element or attribute name inside a rejection: escaped and cut like
/// [`quote`], without the backticks.
pub(crate) fn name<S: AsRef<str> + ?Sized>(s: &S) -> Quoted<'_> {
    Quoted(s.as_ref(), false)
}

/// How many characters of a received value a rejection shows.
pub(crate) const QUOTE_CHARS: usize = 64;

/// See [`quote`].
pub(crate) struct Quoted<'a>(&'a str, bool);

impl fmt::Display for Quoted<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let tick = if self.1 { "`" } else { "" };
        f.write_str(tick)?;
        let mut chars = self.0.chars();
        for c in chars.by_ref().take(QUOTE_CHARS) {
            match c {
                '`' => f.write_str("\\`")?,
                c if c.is_control() => write!(f, "{}", c.escape_debug())?,
                '\u{061C}'
                | '\u{200E}'
                | '\u{200F}'
                | '\u{2028}'..='\u{202E}'
                | '\u{2066}'..='\u{2069}' => write!(f, "{}", c.escape_unicode())?,
                c => write!(f, "{c}")?,
            }
        }
        if chars.next().is_some() {
            f.write_str("…")?;
        }
        f.write_str(tick)
    }
}

#[cfg(test)]
mod quote_tests {
    use super::quote;

    #[test]
    fn escapes_what_could_forge_or_disguise_text() {
        assert_eq!(quote("a\nb\r\tc").to_string(), "`a\\nb\\r\\tc`");
        assert_eq!(
            quote("\u{0}\u{7f}\u{85}").to_string(),
            "`\\0\\u{7f}\\u{85}`"
        );
        assert_eq!(
            quote("x\u{202e}y\u{2066}").to_string(),
            "`x\\u{202e}y\\u{2066}`"
        );
        assert_eq!(
            quote("\u{061c}\u{200e}\u{200f}").to_string(),
            "`\\u{61c}\\u{200e}\\u{200f}`"
        );
        assert_eq!(quote("a`b").to_string(), "`a\\`b`");
        assert_eq!(
            quote("\u{2028}\u{2029}").to_string(),
            "`\\u{2028}\\u{2029}`"
        );
    }

    #[test]
    fn keeps_printable_text() {
        assert_eq!(quote("a\"b\\c'").to_string(), "`a\"b\\c'`");
        assert_eq!(
            quote("Müller 🔌 \u{fffd}").to_string(),
            "`Müller 🔌 \u{fffd}`"
        );
    }

    #[test]
    fn cuts_after_64_characters_without_splitting_one() {
        let exactly = "é".repeat(64);
        assert_eq!(quote(&exactly).to_string(), format!("`{exactly}`"));
        let longer = format!("{exactly}é");
        assert_eq!(quote(&longer).to_string(), format!("`{exactly}…`"));
        let newlines = "\n".repeat(100);
        assert_eq!(
            quote(&newlines).to_string(),
            format!("`{}…`", "\\n".repeat(64))
        );
    }
}