Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions smtp-types/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,16 +1,42 @@
[package]
name = "smtp-types"
description = "Misuse-resistant SMTP types"
description = "Misuse-resistant data structures for SMTP"
keywords = ["email", "smtp", "types"]
categories = ["email", "data-structures", "network-programming"]
version = "0.2.0"
authors = ["Damian Poddebniak <poddebniak@mailbox.org>"]
repository = "https://github.com/duesee/smtp-codec"
license = "MIT OR Apache-2.0"
edition = "2021"
rust-version.workspace = true
edition = "2024"
exclude = [
".github",
]

[features]
default = []
arbitrary = ["dep:arbitrary"]
serde = ["dep:serde"]

# SMTP Extensions
starttls = []
ext_auth = []
ext_size = []
ext_8bitmime = []
ext_pipelining = []
ext_smtputf8 = []
ext_enhancedstatuscodes = []

[dependencies]
serde = { version = "1", features = ["derive"], optional = true }
arbitrary = { version = "1.4.2", optional = true, default-features = false, features = ["derive"] }
base64 = { version = "0.22", default-features = false, features = ["alloc"] }
bounded-static-derive = { version = "0.8.0", default-features = false }
bounded-static = { version = "0.8.0", default-features = false, features = ["alloc"] }
serde = { version = "1.0.228", features = ["derive"], optional = true }
thiserror = "2.0.18"

[dev-dependencies]
serde_json = { version = "1.0.149" }

[package.metadata.docs.rs]
all-features = true
rustdoc-args = ["--cfg", "docsrs"]
52 changes: 45 additions & 7 deletions smtp-types/README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,52 @@
# Misuse-resistant SMTP Types
# smtp-types

This library provides types, i.e., `struct`s and `enum`s, to support [SMTP] implementations.
Misuse-resistant data structures for SMTP (RFC 5321).

## Overview

This crate provides types for SMTP protocol messages including:

- **Core types**: `Domain`, `Mailbox`, `Atom`, `Text`, `Parameter`
- **Commands**: `Command` enum with all RFC 5321 commands (EHLO, HELO, MAIL, RCPT, DATA, etc.)
- **Responses**: `Response`, `Greeting`, `EhloResponse`, `ReplyCode`
- **Authentication**: `AuthMechanism`, `AuthenticateData` (with `ext_auth` feature)

## Features

* Rust's type system is used to enforce correctness and make the library misuse-resistant.
It must not be possible to construct a type that violates the SMTP specification.
| Feature | Description |
|-------------------------|------------------------------------------|
| `starttls` | STARTTLS command support |
| `ext_auth` | SMTP Authentication (RFC 4954) |
| `ext_size` | Message Size Declaration (RFC 1870) |
| `ext_8bitmime` | 8-bit MIME Transport (RFC 6152) |
| `ext_pipelining` | Command Pipelining (RFC 2920) |
| `ext_smtputf8` | Internationalized Email (RFC 6531) |
| `ext_enhancedstatuscodes` | Enhanced Error Codes (RFC 2034) |
| `arbitrary` | Derive `Arbitrary` for fuzzing |
| `serde` | Derive `Serialize`/`Deserialize` |

## Usage

```rust
use smtp_types::{
command::Command,
core::{Domain, ForwardPath, LocalPart, Mailbox, ReversePath},
};

// Create an EHLO command
let domain = Domain::try_from("client.example.com").unwrap();
let cmd = Command::ehlo(domain);

// Create a MAIL FROM command
let cmd = Command::mail(ReversePath::Null);

# License
// Create a RCPT TO command
let local = LocalPart::try_from("user").unwrap();
let domain = Domain::try_from("example.com").unwrap();
let mailbox = Mailbox::new(local, domain.into());
let cmd = Command::rcpt(ForwardPath::from(mailbox));
```

This crate is dual-licensed under Apache 2.0 and MIT terms.
## License

[SMTP]: https://www.rfc-editor.org/rfc/rfc5321
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
245 changes: 245 additions & 0 deletions smtp-types/src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
//! Authentication-related types for SMTP AUTH command.

use std::{
borrow::Cow,
fmt::{Display, Formatter},
str::FromStr,
};

#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use bounded_static_derive::ToStatic;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::{
core::{Atom, impl_try_from},
error::ValidationError,
secret::Secret,
};

/// Authentication mechanism for SMTP AUTH.
///
/// # Reference
///
/// RFC 4954: SMTP Service Extension for Authentication
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type", content = "content"))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, ToStatic)]
#[non_exhaustive]
pub enum AuthMechanism<'a> {
/// The PLAIN SASL mechanism.
///
/// ```text
/// base64(b"<authorization identity>\x00<authentication identity>\x00<password>")
/// ```
///
/// # Reference
///
/// RFC 4616: The PLAIN Simple Authentication and Security Layer (SASL) Mechanism
Plain,

/// The (non-standardized) LOGIN SASL mechanism.
///
/// ```text
/// base64(b"<username>")
/// base64(b"<password>")
/// ```
///
/// # Reference
///
/// draft-murchison-sasl-login-00: The LOGIN SASL Mechanism
Login,

/// OAuth 2.0 bearer token mechanism.
///
/// # Reference
///
/// RFC 7628: A Set of Simple Authentication and Security Layer (SASL) Mechanisms for OAuth
OAuthBearer,

/// Google's OAuth 2.0 mechanism.
///
/// ```text
/// base64(b"user=<user>\x01auth=Bearer <token>\x01\x01")
/// ```
XOAuth2,

/// SCRAM-SHA-1
///
/// # Reference
///
/// RFC 5802: Salted Challenge Response Authentication Mechanism (SCRAM)
ScramSha1,

/// SCRAM-SHA-1-PLUS
///
/// # Reference
///
/// RFC 5802: Salted Challenge Response Authentication Mechanism (SCRAM)
ScramSha1Plus,

/// SCRAM-SHA-256
///
/// # Reference
///
/// RFC 7677: SCRAM-SHA-256 and SCRAM-SHA-256-PLUS SASL Mechanisms
ScramSha256,

/// SCRAM-SHA-256-PLUS
///
/// # Reference
///
/// RFC 7677: SCRAM-SHA-256 and SCRAM-SHA-256-PLUS SASL Mechanisms
ScramSha256Plus,

/// SCRAM-SHA3-512
ScramSha3_512,

/// SCRAM-SHA3-512-PLUS
ScramSha3_512Plus,

/// CRAM-MD5 (legacy mechanism)
///
/// # Reference
///
/// RFC 2195: IMAP/POP AUTHorize Extension for Simple Challenge/Response
CramMd5,

/// Some other (unknown) mechanism.
Other(AuthMechanismOther<'a>),
}

impl_try_from!(Atom<'a>, 'a, &'a [u8], AuthMechanism<'a>);
impl_try_from!(Atom<'a>, 'a, Vec<u8>, AuthMechanism<'a>);
impl_try_from!(Atom<'a>, 'a, &'a str, AuthMechanism<'a>);
impl_try_from!(Atom<'a>, 'a, String, AuthMechanism<'a>);
impl_try_from!(Atom<'a>, 'a, Cow<'a, str>, AuthMechanism<'a>);

impl<'a> From<Atom<'a>> for AuthMechanism<'a> {
fn from(atom: Atom<'a>) -> Self {
match atom.as_ref().to_ascii_uppercase().as_str() {
"PLAIN" => Self::Plain,
"LOGIN" => Self::Login,
"OAUTHBEARER" => Self::OAuthBearer,
"XOAUTH2" => Self::XOAuth2,
"SCRAM-SHA-1" => Self::ScramSha1,
"SCRAM-SHA-1-PLUS" => Self::ScramSha1Plus,
"SCRAM-SHA-256" => Self::ScramSha256,
"SCRAM-SHA-256-PLUS" => Self::ScramSha256Plus,
"SCRAM-SHA3-512" => Self::ScramSha3_512,
"SCRAM-SHA3-512-PLUS" => Self::ScramSha3_512Plus,
"CRAM-MD5" => Self::CramMd5,
_ => Self::Other(AuthMechanismOther(atom)),
}
}
}

impl Display for AuthMechanism<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_ref())
}
}

impl AsRef<str> for AuthMechanism<'_> {
fn as_ref(&self) -> &str {
match self {
Self::Plain => "PLAIN",
Self::Login => "LOGIN",
Self::OAuthBearer => "OAUTHBEARER",
Self::XOAuth2 => "XOAUTH2",
Self::ScramSha1 => "SCRAM-SHA-1",
Self::ScramSha1Plus => "SCRAM-SHA-1-PLUS",
Self::ScramSha256 => "SCRAM-SHA-256",
Self::ScramSha256Plus => "SCRAM-SHA-256-PLUS",
Self::ScramSha3_512 => "SCRAM-SHA3-512",
Self::ScramSha3_512Plus => "SCRAM-SHA3-512-PLUS",
Self::CramMd5 => "CRAM-MD5",
Self::Other(other) => other.0.as_ref(),
}
}
}

impl FromStr for AuthMechanism<'static> {
type Err = ValidationError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
AuthMechanism::try_from(s.to_string())
}
}

#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for AuthMechanism<'static> {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
let variant: u8 = u.int_in_range(0..=10)?;
Ok(match variant {
0 => AuthMechanism::Plain,
1 => AuthMechanism::Login,
2 => AuthMechanism::OAuthBearer,
3 => AuthMechanism::XOAuth2,
4 => AuthMechanism::ScramSha1,
5 => AuthMechanism::ScramSha1Plus,
6 => AuthMechanism::ScramSha256,
7 => AuthMechanism::ScramSha256Plus,
8 => AuthMechanism::ScramSha3_512,
9 => AuthMechanism::ScramSha3_512Plus,
_ => AuthMechanism::CramMd5,
})
}
}

/// An (unknown) authentication mechanism.
///
/// It's guaranteed that this type can't represent any known mechanism from [`AuthMechanism`].
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, ToStatic)]
pub struct AuthMechanismOther<'a>(pub(crate) Atom<'a>);

/// Data line used during SMTP AUTH exchange.
///
/// Holds the raw binary data, i.e., a `Vec<u8>`, *not* the BASE64 string.
#[cfg_attr(feature = "arbitrary", derive(Arbitrary))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(tag = "type", content = "content"))]
#[derive(Debug, Clone, PartialEq, Eq, Hash, ToStatic)]
pub enum AuthenticateData<'a> {
/// Continue SASL authentication with response data.
Continue(Secret<Cow<'a, [u8]>>),
/// Cancel SASL authentication.
///
/// The client sends a single "*" to cancel the authentication exchange.
Cancel,
}

impl<'a> AuthenticateData<'a> {
/// Create a continuation response with the given data.
pub fn r#continue<D>(data: D) -> Self
where
D: Into<Cow<'a, [u8]>>,
{
Self::Continue(Secret::new(data.into()))
}
}

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

#[test]
fn test_conversion() {
assert!(AuthMechanism::try_from("plain").is_ok());
assert!(AuthMechanism::try_from("login").is_ok());
assert!(AuthMechanism::try_from("oauthbearer").is_ok());
assert!(AuthMechanism::try_from("xoauth2").is_ok());
assert!(AuthMechanism::try_from("cram-md5").is_ok());
assert!(AuthMechanism::try_from("xxxplain").is_ok());
assert!(AuthMechanism::try_from("xxxlogin").is_ok());
}

#[test]
fn test_display() {
assert_eq!(AuthMechanism::Plain.to_string(), "PLAIN");
assert_eq!(AuthMechanism::Login.to_string(), "LOGIN");
assert_eq!(AuthMechanism::CramMd5.to_string(), "CRAM-MD5");
}
}
Loading
Loading