Struct Auth

Source
pub struct Auth {
    pub props: Option<Properties>,
    /* private fields */
}
Expand description

MQTT v5.0 AUTH packet representation

The AUTH packet is sent from the Client to the Server or from the Server to the Client as part of an extended authentication exchange, such as challenge/response authentication. It is also used by the Client or Server to perform re-authentication during a connection.

The AUTH packet enables enhanced authentication flows beyond the basic username/password mechanism provided in the CONNECT packet. It supports:

  • SASL-based authentication mechanisms
  • Challenge/response authentication flows
  • Re-authentication during an active connection
  • Custom authentication methods

§Packet Structure

The AUTH packet consists of:

  • Fixed Header (1 byte): Packet type (0xF0) and flags
  • Variable Header:
    • Reason Code (1 byte, optional)
    • Properties (variable length, optional if reason code present)

§Authentication Flow

Enhanced authentication is a challenge/response style authentication that can extend beyond the initial connection. The flow typically involves:

  1. Client sends CONNECT with Authentication Method property
  2. Server responds with CONNACK containing Continue Authentication reason code
  3. Multiple AUTH packet exchanges between client and server
  4. Final CONNACK with Success or failure reason code

§Re-authentication

Either the Client or Server can initiate re-authentication at any time during the connection by sending an AUTH packet with a reason code of Re-authenticate.

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
use mqtt_protocol_core::mqtt::packet::Properties;
use mqtt_protocol_core::mqtt::packet::Property;

// Create an AUTH packet for continue authentication
let auth = mqtt::packet::v5_0::Auth::builder()
    .reason_code(AuthReasonCode::ContinueAuthentication)
    .props(Properties::from_vec(vec![
        Property::AuthenticationMethod("SCRAM-SHA-256".into()),
        Property::AuthenticationData(b"challenge_data".to_vec()),
    ]))
    .build()
    .unwrap();

// Create an AUTH packet for re-authentication
let reauth = mqtt::packet::v5_0::Auth::builder()
    .reason_code(AuthReasonCode::ReAuthenticate)
    .build()
    .unwrap();

Fields§

§props: Option<Properties>

MQTT v5.0 properties for the AUTH packet

Valid properties for AUTH packets include:

  • Authentication Method: Specifies the authentication method being used
  • Authentication Data: Contains method-specific authentication data
  • Reason String: Human-readable string describing the reason
  • User Property: Application-specific key-value pairs

Implementations§

Source§

impl Auth

Source

pub fn props(&self) -> &Option<Properties>

MQTT v5.0 properties for the AUTH packet

Valid properties for AUTH packets include:

  • Authentication Method: Specifies the authentication method being used
  • Authentication Data: Contains method-specific authentication data
  • Reason String: Human-readable string describing the reason
  • User Property: Application-specific key-value pairs
Source§

impl Auth

Source

pub fn builder() -> AuthBuilder

Create a new AuthBuilder for constructing AUTH packets

Returns a builder instance that can be used to configure and construct an AUTH packet with the desired properties and reason code.

§Returns
  • AuthBuilder - A new builder instance
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;

let auth = mqtt::packet::v5_0::Auth::builder()
    .reason_code(AuthReasonCode::ContinueAuthentication)
    .build()
    .unwrap();
Source

pub fn packet_type() -> PacketType

Get the packet type for AUTH packets

Returns the fixed packet type identifier for AUTH packets as defined in the MQTT v5.0 specification.

§Returns
  • PacketType::Auth - The AUTH packet type constant
Source

pub fn reason_code(&self) -> Option<AuthReasonCode>

Get the reason code from the AUTH packet

Extracts and parses the reason code from the packet buffer. The reason code indicates the purpose or result of the authentication operation.

§Returns
  • Some(AuthReasonCode) - The parsed reason code if present and valid
  • None - If no reason code is present in the packet
§Examples
use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;

let auth = mqtt::packet::v5_0::Auth::builder()
    .reason_code(AuthReasonCode::Success)
    .build()
    .unwrap();

assert_eq!(auth.reason_code(), Some(AuthReasonCode::Success));
Source

pub fn size(&self) -> usize

Calculate the total size of the AUTH packet in bytes

Returns the complete size of the packet including the fixed header, remaining length field, reason code (if present), property length (if present), and all properties.

§Returns
  • usize - Total packet size in bytes
§Examples
use mqtt_protocol_core::mqtt;

let auth = mqtt::packet::v5_0::Auth::builder().build().unwrap();
let size = auth.size();
println!("AUTH packet size: {} bytes", size);
Source

pub fn to_buffers(&self) -> Vec<IoSlice<'_>>

Convert the AUTH packet to a series of I/O buffers for efficient network transmission

Creates a vector of IoSlice buffers that represent the complete packet data. This enables zero-copy transmission using vectored I/O operations like writev(). The buffers are ordered according to the MQTT wire format.

§Returns
  • Vec<IoSlice<'_>> - Vector of I/O slices representing the packet data
§Buffer Order
  1. Fixed header (1 byte)
  2. Remaining length (1-4 bytes)
  3. Reason code (1 byte, if present)
  4. Property length (1-4 bytes, if properties present)
  5. Properties data (variable length, if present)
§Examples
use mqtt_protocol_core::mqtt;
use std::io::IoSlice;

let auth = mqtt::packet::v5_0::Auth::builder().build().unwrap();
let buffers = auth.to_buffers();

// Send using vectored I/O
// socket.write_vectored(&buffers)?;
Source

pub fn parse(data: &[u8]) -> Result<(Self, usize), MqttError>

Parse an AUTH packet from raw bytes

Parses the variable header portion of an AUTH packet from the provided byte buffer. This function expects the fixed header to have already been parsed and removed.

The parsing process validates:

  • Reason code validity (if present)
  • Property structure and content
  • Required property relationships (e.g., Authentication Data requires Authentication Method)
  • Protocol compliance for reason code and property combinations
§Parameters
  • data - Byte slice containing the AUTH packet variable header (excluding fixed header)
§Returns
  • Ok((Auth, usize)) - Successfully parsed AUTH packet and number of bytes consumed
  • Err(MqttError::MalformedPacket) - If the packet structure is invalid
  • Err(MqttError::ProtocolError) - If the packet violates MQTT protocol rules
§Protocol Rules
  • If reason code is not Success, Authentication Method property is required
  • Authentication Data property requires Authentication Method property
  • Properties must not contain duplicates (except User Property)
  • Only specific properties are allowed in AUTH packets
§Examples
use mqtt_protocol_core::mqtt;

let data = &[0x00, 0x00]; // Minimal AUTH packet: Success reason code + empty properties
let (auth_packet, consumed) = mqtt::packet::v5_0::Auth::parse(data)?;
assert_eq!(consumed, 2);

Trait Implementations§

Source§

impl AsConcrete<Auth> for Packet

Source§

impl Clone for Auth

Source§

fn clone(&self) -> Auth

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Auth

Debug implementation for AUTH packets

Provides debug output for AUTH packets by delegating to the Display implementation. This ensures consistent formatting between debug and display representations, which is useful for logging and debugging scenarios.

The debug output is identical to the display output, showing the packet in JSON format with all relevant fields.

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;

let auth = mqtt::packet::v5_0::Auth::builder()
    .reason_code(AuthReasonCode::Success)
    .build()
    .unwrap();

println!("{:?}", auth);
// Outputs: {"type":"AUTH","reason_code":"Success","props":{}}
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Auth

Display implementation for AUTH packets

Provides human-readable string representation of AUTH packets using JSON format. This implementation leverages the Serialize trait to create consistent, structured output suitable for logging and debugging.

If serialization fails, an error message is returned instead of panicking.

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;

let auth = mqtt::packet::v5_0::Auth::builder()
    .reason_code(AuthReasonCode::ContinueAuthentication)
    .build()
    .unwrap();

println!("{}", auth);
// Outputs: {"type":"AUTH","reason_code":"ContinueAuthentication","props":{}}
Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<PacketIdType> From<Auth> for GenericPacket<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Source§

fn from(v: Auth) -> GenericPacket<PacketIdType>

Converts to this type from the input type.
Source§

impl GenericPacketDisplay for Auth

GenericPacketDisplay implementation for AUTH packets

Implements the generic packet display interface that provides standardized formatting capabilities for AUTH packets. This trait enables consistent display and debug output across different packet types.

Source§

fn fmt_debug(&self, f: &mut Formatter<'_>) -> Result

Source§

fn fmt_display(&self, f: &mut Formatter<'_>) -> Result

Source§

impl GenericPacketTrait for Auth

GenericPacketTrait implementation for AUTH packets

Implements the common packet interface that allows AUTH packets to be used polymorphically with other MQTT packet types. This trait provides standardized methods for packet size calculation and buffer generation.

Source§

fn size(&self) -> usize

Source§

fn to_buffers(&self) -> Vec<IoSlice<'_>>

Source§

impl IntoConcreteOwned<Auth> for Packet

Source§

impl PacketKind for Auth

PacketKind implementation for v5.0 AUTH packet (v5.0 exclusive)

Source§

const IS_AUTH: bool = true

true if this is an AUTH packet (v5.0 only)
Source§

const IS_V5_0: bool = true

true if this is an MQTT v5.0 packet
Source§

const IS_CONNECT: bool = false

true if this is a CONNECT packet
Source§

const IS_CONNACK: bool = false

true if this is a CONNACK packet
Source§

const IS_PUBLISH: bool = false

true if this is a PUBLISH packet
Source§

const IS_PUBACK: bool = false

true if this is a PUBACK packet
Source§

const IS_PUBREC: bool = false

true if this is a PUBREC packet
Source§

const IS_PUBREL: bool = false

true if this is a PUBREL packet
Source§

const IS_PUBCOMP: bool = false

true if this is a PUBCOMP packet
Source§

const IS_SUBSCRIBE: bool = false

true if this is a SUBSCRIBE packet
Source§

const IS_SUBACK: bool = false

true if this is a SUBACK packet
Source§

const IS_UNSUBSCRIBE: bool = false

true if this is an UNSUBSCRIBE packet
Source§

const IS_UNSUBACK: bool = false

true if this is an UNSUBACK packet
Source§

const IS_PINGREQ: bool = false

true if this is a PINGREQ packet
Source§

const IS_PINGRESP: bool = false

true if this is a PINGRESP packet
Source§

const IS_DISCONNECT: bool = false

true if this is a DISCONNECT packet
Source§

const IS_V3_1_1: bool = false

true if this is an MQTT v3.1.1 packet
Source§

impl PartialEq for Auth

Source§

fn eq(&self, other: &Auth) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for Auth

Serialize implementation for AUTH packets

Provides JSON serialization support for AUTH packets, enabling conversion to structured data formats for logging, debugging, and inter-process communication.

The serialized format includes:

  • type: Always “AUTH” for packet type identification
  • reason_code: The authentication reason code (if present)
  • props: The MQTT v5.0 properties (if present)

§Examples

use mqtt_protocol_core::mqtt;
use mqtt_protocol_core::mqtt::result_code::AuthReasonCode;
use serde_json;

let auth = mqtt::packet::v5_0::Auth::builder()
    .reason_code(AuthReasonCode::Success)
    .build()
    .unwrap();

let json = serde_json::to_string(&auth).unwrap();
// Results in: {"type":"AUTH","reason_code":"Success","props":{}}
Source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl<PacketIdType> TryInto<Auth> for GenericPacket<PacketIdType>
where PacketIdType: IsPacketId + Serialize,

Source§

type Error = &'static str

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<Auth, <Self as TryInto<Auth>>::Error>

Performs the conversion.
Source§

impl Eq for Auth

Source§

impl SendableRole<Any> for Auth

Source§

impl SendableRole<Client> for Auth

Source§

impl SendableRole<Server> for Auth

Source§

impl StructuralPartialEq for Auth

Auto Trait Implementations§

§

impl Freeze for Auth

§

impl RefUnwindSafe for Auth

§

impl Send for Auth

§

impl Sync for Auth

§

impl Unpin for Auth

§

impl UnwindSafe for Auth

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsConcrete<T> for T

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoConcreteOwned<T> for T

Source§

impl<Role, PacketIdType, T> Sendable<Role, PacketIdType> for T
where Role: RoleType, PacketIdType: IsPacketId, T: SendableRole<Role> + SendableVersion + Display + Debug + PacketKind + SendableHelper<Role, PacketIdType>,

Source§

fn dispatch_send( self, connection: &mut GenericConnection<Role, PacketIdType>, ) -> Vec<GenericEvent<PacketIdType>>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more