Skip to main content

sasl/server/mechanisms/
anonymous.rs

1use crate::common::Identity;
2use crate::server::{Mechanism, MechanismError, Response};
3use alloc::string::String;
4use alloc::vec::Vec;
5use core::fmt::Write;
6
7pub struct Anonymous;
8
9impl Anonymous {
10    #[allow(clippy::new_without_default)]
11    pub fn new() -> Anonymous {
12        Anonymous
13    }
14}
15
16impl Mechanism for Anonymous {
17    fn name(&self) -> &str {
18        "ANONYMOUS"
19    }
20
21    fn respond(&mut self, payload: &[u8]) -> Result<Response, MechanismError> {
22        if !payload.is_empty() {
23            return Err(MechanismError::FailedToDecodeMessage);
24        }
25        let mut rand = [0u8; 16];
26        getrandom::fill(&mut rand)?;
27        let mut username = String::with_capacity(32);
28        for byte in rand {
29            write!(&mut username, "{byte:02x}").unwrap();
30        }
31        let ident = Identity::Username(username);
32        Ok(Response::Success(ident, Vec::new()))
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn response() {
42        let mut anonymous = Anonymous::new();
43        let Ok(Response::Success(ident, data)) = anonymous.respond(&[]) else {
44            panic!("Didn’t get a Success response!");
45        };
46        let Identity::Username(username) = ident else {
47            panic!("Didn’t get a Username identity!");
48        };
49        assert_eq!(username.len(), 32);
50        assert_eq!(data.len(), 0);
51    }
52}