relay-core 0.1.1-alpha.0

The core components of the Relay Protocol.
Documentation
use serde::{Deserialize, Serialize};

use super::{AgentId, IdentityError as Err, InboxId, UserId};

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Address {
    pub inbox: Option<InboxId>,
    pub user: UserId,
    pub agent: AgentId,
}

impl TryFrom<&str> for Address {
    type Error = Err;

    fn try_from(value: &str) -> Result<Self, Err> {
        Address::parse(value)
    }
}

impl TryFrom<String> for Address {
    type Error = Err;

    fn try_from(value: String) -> Result<Self, Err> {
        Address::parse(value)
    }
}

impl Address {
    /// Creates a new address.
    pub fn new(inbox: Option<InboxId>, user: UserId, agent: AgentId) -> Self {
        Address { inbox, user, agent }
    }

    /// Parse an address from a string.
    /// https://gitlab.com/relay-mail/docs/-/wikis/Architecture/Identity#address
    /// General format: `[inbox]#user@agent`
    ///
    /// # Example
    /// ```
    /// use relay_core::id::{Address, AgentId, InboxId, UserId};
    ///
    /// let address = Address::parse("work#alice.smith@example.com").unwrap();
    /// assert_eq!(address.inbox, Some(InboxId::parse("work").unwrap()));
    /// assert_eq!(address.user, UserId::parse("alice.smith").unwrap());
    /// assert_eq!(address.agent, AgentId::parse("example.com").unwrap());
    /// ```
    pub fn parse(input: impl AsRef<str>) -> Result<Self, Err> {
        let input = input.as_ref();
        if input.trim() != input {
            return Err(Err::InvalidAddress);
        }

        let (left, agent_str) = input.rsplit_once('@').ok_or(Err::InvalidAddress)?;
        let agent = AgentId::parse(agent_str)?;

        let (inbox, user_str) = if let Some((inbox_str, user_str)) = left.rsplit_once('#') {
            let inbox = if inbox_str.is_empty() {
                None
            } else {
                Some(InboxId::parse(inbox_str)?)
            };
            (inbox, user_str)
        } else {
            (None, left)
        };
        let user = UserId::parse(user_str)?;

        Ok(Address { inbox, user, agent })
    }

    /// Get the canonical string representation of the address.
    /// https://gitlab.com/relay-mail/docs/-/wikis/Architecture/Identity#canonical-form
    pub fn canonical(&self) -> String {
        match &self.inbox {
            Some(inbox) => format!(
                "{}#{}@{}",
                inbox.canonical(),
                self.user.canonical(),
                self.agent.canonical()
            ),
            None => format!("#{}@{}", self.user.canonical(), self.agent.canonical()),
        }
    }

    /// Get inbox id.
    pub fn inbox(&self) -> Option<&InboxId> {
        self.inbox.as_ref()
    }

    /// Get user id.
    pub fn user(&self) -> &UserId {
        &self.user
    }

    /// Get agent id.
    pub fn agent(&self) -> &AgentId {
        &self.agent
    }
}

impl std::fmt::Display for Address {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.canonical())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_and_canonicalizes() {
        assert_eq!(
            Address::parse("#Bob@example.org").unwrap().canonical(),
            "#bob@example.org"
        );
        assert_eq!(
            Address::parse("Bob@example.org").unwrap().canonical(),
            "#bob@example.org"
        );
        assert_eq!(
            Address::parse("wORk#Bob@example.ORG").unwrap().canonical(),
            "work#bob@example.org"
        );
    }

    #[test]
    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
    fn rejects_empty() {
        let _ = Address::parse("").unwrap();
    }

    #[test]
    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
    fn rejects_invalid_chars() {
        let _ = Address::parse("Invalid Address!").unwrap();
    }

    #[test]
    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
    fn reject_untrimmed() {
        let _ = Address::parse("  trim_me  ").unwrap();
    }

    #[test]
    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidAddress")]
    fn rejects_non_ascii() {
        let _ = Address::parse("调试输出").unwrap();
    }

    #[test]
    #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: InvalidIdentityString")]
    fn rejects_homoglyphs() {
        let _ = Address::parse("wоrk#аlice@us.exaмple.org").unwrap(); // Cyrillic 'о', 'а', 'м'
    }
}