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
//! `[UFTP App. 4 §3, §4]` on the [`http`] crate's types (feature `http`).
//!
//! The functions here neither read a socket nor a clock: they turn a sealed message into
//! a POST, check and open a received request, turn the outcome into the HTTP answer, and
//! classify the answer a sender got back. Any framework built on `http` 1.x (axum, hyper,
//! tower, reqwest, ureq) uses them as they are. Routing, TLS and retries stay with the
//! framework.
//!
//! A receiving handler, framework-agnostic:
//!
//! ```
//! use uftp::*;
//!
//! fn handle(
//!     request: ::http::Request<Vec<u8>>,
//!     options: &OpenOptions,
//!     directory: &Directory,
//! ) -> ::http::Response<String> {
//!     // Headers first: a framework that streams calls `check_headers` before it reads
//!     // the body, and answers `http::response(Err(&e))` on failure.
//!     let outcome = uftp::http::open_request(&request, options, directory.lookup());
//!     match &outcome {
//!         Ok(opened) => { /* hand the message to the application */ }
//!         Err(e) => {
//!             // A verified message that broke a rule: still 200, and a Rejected response
//!             // goes back later as its own POST: `e.response(id, now)`, sealed.
//!             let _ = e.opened();
//!         }
//!     }
//!     uftp::http::response(outcome.as_ref())
//! }
//! ```

use ::http::header::{self, HeaderMap, HeaderValue};
use ::http::{Method, Request, Response, StatusCode, Uri};

use jiff::Timestamp;

use crate::directory::{IntoKeys, KeyLookupError};
use crate::endpoint::Endpoint;
use crate::envelope::{OpenOptions, Opened, SignedMessage, open};
use crate::error::{Disposition, RejectKind, Rejection};
use crate::transport::{self, Delivery};
use crate::types::{InternetDomain, Role};
use crate::xml::reader::Limits;

/// The POST that delivers `message` to `uri`, such as
/// `https://agr.example/USEF/2019/SignedMessage` ([`transport::SPEC_PATH`]): UFTP
/// Content-Type, Content-Length, and the document as body.
#[must_use]
pub fn request(uri: &Uri, message: &SignedMessage) -> Request<String> {
    let body = message.to_xml();
    let mut request = Request::new(String::new());
    *request.method_mut() = Method::POST;
    *request.uri_mut() = uri.clone();
    let headers = request.headers_mut();
    headers.insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static(transport::CONTENT_TYPE),
    );
    headers.insert(header::CONTENT_LENGTH, HeaderValue::from(body.len()));
    *request.body_mut() = body;
    request
}

/// Checks a request's headers before its body is read: [`transport::check_request`] on
/// the Content-Type and Content-Length.
///
/// # Errors
/// - [`RejectKind::LengthRequired`] (411) without a Content-Length.
/// - [`RejectKind::Header`] (400) for a Content-Length that is not a decimal number or
///   that is repeated with another value (RFC 9110 §8.6), and for a Content-Type other
///   than `text/xml` in UTF-8.
/// - [`RejectKind::Limits`] (400) for a length over [`Limits::max_bytes`].
pub fn check_headers(headers: &HeaderMap, limits: &Limits) -> Result<(), Rejection> {
    let length = content_length(headers)?;
    let mut types = headers.get_all(header::CONTENT_TYPE).iter();
    let content_type = types.next().map(|v| v.to_str().unwrap_or("(not ASCII)"));
    if types.next().is_some() {
        return Err(header_error("The request has more than one Content-Type."));
    }
    transport::check_request(content_type, length, limits)
}

/// Checks the headers, refuses a body whose length is not the Content-Length, then
/// [`open`]s the body. Method and path are the router's business and are not checked.
///
/// [`Endpoint::receive_request`] does the same and then every other receive check.
///
/// # Errors
/// Those of [`check_headers`]; [`RejectKind::Header`] (400) when the body's length
/// differs from the Content-Length; then every error of [`open`].
pub fn open_request<B, F, K>(
    request: &Request<B>,
    options: &OpenOptions,
    lookup: F,
) -> Result<Opened, Rejection>
where
    B: AsRef<[u8]>,
    F: FnOnce(&InternetDomain, Role) -> Result<K, KeyLookupError>,
    K: IntoKeys,
{
    open(checked_body(request, &options.limits)?, options, lookup)
}

/// The body of a request whose headers pass [`check_headers`] and whose length is the
/// declared Content-Length.
fn checked_body<'a, B: AsRef<[u8]>>(
    request: &'a Request<B>,
    limits: &Limits,
) -> Result<&'a [u8], Rejection> {
    check_headers(request.headers(), limits)?;
    let body = request.body().as_ref();
    if let Some(declared) = content_length(request.headers())?
        && u64::try_from(body.len()).ok() != Some(declared)
    {
        return Err(header_error(&format!(
            "The body has {} bytes; the Content-Length says {declared}.",
            body.len()
        )));
    }
    Ok(body)
}

impl Endpoint {
    /// [`check_headers`], the body's length, then [`Endpoint::receive`]: a receiving
    /// handler in one call.
    ///
    /// ```
    /// # use uftp::*;
    /// # fn handler(endpoint: &mut Endpoint, request: ::http::Request<Vec<u8>>, directory: &Directory,
    /// #            now: uftp::jiff::Timestamp, id: MessageUuid) -> ::http::Response<String> {
    /// let outcome = endpoint.receive_request(&request, now, directory.lookup());
    /// if let Err(e) = &outcome {
    ///     if let Some(_answer) = e.response(id, now) { /* seal, then POST it later */ }
    /// }
    /// uftp::http::response(outcome.as_ref())
    /// # }
    /// ```
    ///
    /// # Errors
    /// Those of [`open_request`], then those of [`Endpoint::receive`].
    pub fn receive_request<B, F, K>(
        &mut self,
        request: &Request<B>,
        now: Timestamp,
        lookup: F,
    ) -> Result<Opened, Rejection>
    where
        B: AsRef<[u8]>,
        F: FnOnce(&InternetDomain, Role) -> Result<K, KeyLookupError>,
        K: IntoKeys,
    {
        let body = checked_body(request, &self.options().limits)?;
        self.receive(body, now, lookup)
    }
}

/// The HTTP answer to a received request `[UFTP App. 4 §4]`:
/// - an opened message, and a rejection whose [`Disposition`] is `Respond`: 200 with an
///   empty body. The Rejected response is a message of its own, sent later
///   ([`Rejection::response`]).
/// - every other rejection: its status, `text/plain; charset=utf-8`, `nosniff`, and its
///   one-sentence explanation as the body.
///
/// Pass `outcome.as_ref()` of what [`open_request`] returned.
#[must_use]
pub fn response(outcome: Result<&Opened, &Rejection>) -> Response<String> {
    let mut response = Response::new(String::new());
    let Err(rejection) = outcome else {
        return response;
    };
    let Disposition::Transport(status) = rejection.disposition() else {
        return response;
    };
    *response.status_mut() = StatusCode::from_u16(status).unwrap_or(StatusCode::BAD_REQUEST);
    let headers = response.headers_mut();
    headers.insert(
        header::CONTENT_TYPE,
        HeaderValue::from_static("text/plain; charset=utf-8"),
    );
    headers.insert(
        header::X_CONTENT_TYPE_OPTIONS,
        HeaderValue::from_static("nosniff"),
    );
    if let Some(delay) = rejection.retry_after() {
        // Whole seconds already (RFC 9110 §10.2.3 delay-seconds).
        headers.insert(header::RETRY_AFTER, HeaderValue::from(delay.as_secs()));
    }
    *response.body_mut() = rejection.to_string();
    response
}

/// What a sender does with the answer it got: [`Delivery::of`] its status.
#[must_use]
pub fn delivery<B>(response: &Response<B>) -> Delivery {
    Delivery::of(response.status().as_u16())
}

/// The one Content-Length the headers declare, if any. Comma-separated lists and repeated
/// headers are allowed when every element is the same number.
fn content_length(headers: &HeaderMap) -> Result<Option<u64>, Rejection> {
    let mut length = None;
    for value in headers.get_all(header::CONTENT_LENGTH) {
        let text = value
            .to_str()
            .map_err(|_| header_error("The Content-Length is not ASCII."))?;
        for element in text.split(',') {
            let element = element.trim();
            let n = (!element.is_empty() && element.bytes().all(|b| b.is_ascii_digit()))
                .then(|| element.parse::<u64>().ok())
                .flatten()
                .ok_or_else(|| {
                    header_error(&format!(
                        "The Content-Length {element} is not a decimal number of bytes.",
                        element = crate::error::quote(&element)
                    ))
                })?;
            match length {
                Some(previous) if previous != n => {
                    return Err(header_error(&format!(
                        "The request declares two Content-Lengths, {previous} and {n}."
                    )));
                }
                _ => length = Some(n),
            }
        }
    }
    Ok(length)
}

fn header_error(message: &str) -> Rejection {
    Rejection::new(
        RejectKind::Header,
        "[UFTP App. 4 §4] request headers; RFC 9110 §8.6",
        message,
    )
}