Skip to main content

bare_types/sys/
username.rs

1//! System username type for system information.
2//!
3//! This module provides a type-safe abstraction for system usernames,
4//! ensuring valid username strings following POSIX rules.
5//!
6//! # Username Format
7//!
8//! System usernames follow POSIX rules:
9//!
10//! - Must be 1-32 characters
11//! - Must start with a letter or underscore
12//! - Can contain alphanumeric characters, underscores, and hyphens
13//!
14//! # Examples
15//!
16//! ```rust
17//! use bare_types::sys::Username;
18//!
19//! // Parse from string
20//! let username: Username = "root".parse()?;
21//!
22//! // Access as string
23//! assert_eq!(username.as_str(), "root");
24//! # Ok::<(), bare_types::sys::UsernameError>(())
25//! ```
26
27use core::fmt;
28use core::str::FromStr;
29
30#[cfg(feature = "serde")]
31use serde::{Deserialize, Serialize};
32
33/// Error type for username parsing.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
36#[non_exhaustive]
37pub enum UsernameError {
38    /// Empty username
39    ///
40    /// The provided string is empty. Usernames must contain at least one character.
41    Empty,
42    /// Username too long (max 32 characters)
43    ///
44    /// According to POSIX, usernames must not exceed 32 characters.
45    /// This variant contains the actual length of the provided username.
46    TooLong(usize),
47    /// Invalid first character (must be letter or underscore)
48    ///
49    /// Usernames must start with a letter (a-z, A-Z) or underscore (_).
50    /// Digits and other characters are not allowed as the first character.
51    InvalidFirstCharacter,
52    /// Invalid character in username
53    ///
54    /// Usernames can only contain ASCII letters, digits, underscores, and hyphens.
55    /// This variant indicates an invalid character was found.
56    InvalidCharacter,
57}
58
59impl fmt::Display for UsernameError {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        match self {
62            Self::Empty => write!(f, "username cannot be empty"),
63            Self::TooLong(len) => write!(f, "username too long (got {len}, max 32 characters)"),
64            Self::InvalidFirstCharacter => {
65                write!(f, "username must start with a letter or underscore")
66            }
67            Self::InvalidCharacter => write!(f, "username contains invalid character"),
68        }
69    }
70}
71
72#[cfg(feature = "std")]
73impl std::error::Error for UsernameError {}
74
75/// System username.
76///
77/// This type provides type-safe system usernames following POSIX rules.
78/// It uses the newtype pattern with `#[repr(transparent)]` for zero-cost abstraction.
79#[repr(transparent)]
80#[derive(Debug, Clone, PartialEq, Eq, Hash)]
81#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
82pub struct Username(heapless::String<32>);
83
84impl Username {
85    /// Maximum length of a username (POSIX)
86    pub const MAX_LEN: usize = 32;
87
88    /// Creates a new username from a string.
89    ///
90    /// # Errors
91    ///
92    /// Returns an error `UsernameError` if the string is not a valid username.
93    pub fn new(s: &str) -> Result<Self, UsernameError> {
94        Self::validate(s)?;
95        let mut value = heapless::String::new();
96        value
97            .push_str(s)
98            .map_err(|_| UsernameError::TooLong(s.len()))?;
99        Ok(Self(value))
100    }
101
102    /// Validates a username string.
103    fn validate(s: &str) -> Result<(), UsernameError> {
104        if s.is_empty() {
105            return Err(UsernameError::Empty);
106        }
107        if s.len() > Self::MAX_LEN {
108            return Err(UsernameError::TooLong(s.len()));
109        }
110        let mut chars = s.chars();
111        if let Some(first) = chars.next() {
112            if !first.is_ascii_alphabetic() && first != '_' {
113                return Err(UsernameError::InvalidFirstCharacter);
114            }
115        }
116        for ch in chars {
117            if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
118                return Err(UsernameError::InvalidCharacter);
119            }
120        }
121        Ok(())
122    }
123
124    /// Returns the username as a string slice.
125    #[must_use]
126    #[inline]
127    pub fn as_str(&self) -> &str {
128        &self.0
129    }
130
131    /// Returns a reference to the underlying `heapless::String`.
132    #[must_use]
133    #[inline]
134    pub const fn as_inner(&self) -> &heapless::String<32> {
135        &self.0
136    }
137
138    /// Consumes this username and returns the underlying string.
139    #[must_use]
140    #[inline]
141    pub fn into_inner(self) -> heapless::String<32> {
142        self.0
143    }
144
145    /// Returns `true` if this is a system user.
146    ///
147    /// System users typically start with underscore or are well-known system accounts.
148    #[must_use]
149    pub fn is_system_user(&self) -> bool {
150        self.0.starts_with('_') || self.0 == "root" || self.0 == "daemon"
151    }
152
153    /// Returns `true` if this is a service account.
154    ///
155    /// Service accounts typically start with "svc-" or "service-".
156    #[must_use]
157    pub fn is_service_account(&self) -> bool {
158        self.0.starts_with("svc-") || self.0.starts_with("service-")
159    }
160}
161
162impl AsRef<str> for Username {
163    fn as_ref(&self) -> &str {
164        self.as_str()
165    }
166}
167
168impl TryFrom<&str> for Username {
169    type Error = UsernameError;
170
171    fn try_from(s: &str) -> Result<Self, Self::Error> {
172        Self::new(s)
173    }
174}
175
176impl FromStr for Username {
177    type Err = UsernameError;
178
179    fn from_str(s: &str) -> Result<Self, Self::Err> {
180        Self::new(s)
181    }
182}
183
184impl fmt::Display for Username {
185    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186        write!(f, "{}", self.0)
187    }
188}
189
190#[cfg(feature = "arbitrary")]
191impl<'a> arbitrary::Arbitrary<'a> for Username {
192    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
193        const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
194        const DIGITS: &[u8] = b"0123456789";
195
196        // Generate 1-32 character username
197        let len = 1 + (u8::arbitrary(u)? % 32).min(31);
198        let mut inner = heapless::String::<32>::new();
199
200        // First character: letter or underscore
201        let first_byte = u8::arbitrary(u)?;
202        if first_byte % 10 == 0 {
203            // 10% chance of underscore
204            inner
205                .push('_')
206                .map_err(|_| arbitrary::Error::IncorrectFormat)?;
207        } else {
208            let first = ALPHABET[(first_byte % 26) as usize] as char;
209            inner
210                .push(first)
211                .map_err(|_| arbitrary::Error::IncorrectFormat)?;
212        }
213
214        // Remaining characters: alphanumeric, underscore, or hyphen
215        for _ in 1..len {
216            let byte = u8::arbitrary(u)?;
217            let c = match byte % 4 {
218                0 => ALPHABET[((byte >> 2) % 26) as usize] as char,
219                1 => DIGITS[((byte >> 2) % 10) as usize] as char,
220                2 => '_',
221                _ => '-',
222            };
223            inner
224                .push(c)
225                .map_err(|_| arbitrary::Error::IncorrectFormat)?;
226        }
227
228        Ok(Self(inner))
229    }
230}
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235
236    #[test]
237    fn test_new_valid() {
238        let username = Username::new("root").unwrap();
239        assert_eq!(username.as_str(), "root");
240    }
241
242    #[test]
243    fn test_new_empty() {
244        assert!(matches!(Username::new(""), Err(UsernameError::Empty)));
245    }
246
247    #[test]
248    fn test_new_too_long() {
249        let long_name = "a".repeat(33);
250        assert!(matches!(
251            Username::new(&long_name),
252            Err(UsernameError::TooLong(33))
253        ));
254    }
255
256    #[test]
257    fn test_new_invalid_first_character() {
258        assert!(matches!(
259            Username::new("1root"),
260            Err(UsernameError::InvalidFirstCharacter)
261        ));
262        assert!(matches!(
263            Username::new("-root"),
264            Err(UsernameError::InvalidFirstCharacter)
265        ));
266    }
267
268    #[test]
269    fn test_new_invalid_character() {
270        assert!(matches!(
271            Username::new("root@"),
272            Err(UsernameError::InvalidCharacter)
273        ));
274        assert!(matches!(
275            Username::new("root.user"),
276            Err(UsernameError::InvalidCharacter)
277        ));
278    }
279
280    #[test]
281    fn test_is_system_user() {
282        let root = Username::new("root").unwrap();
283        assert!(root.is_system_user());
284        let daemon = Username::new("daemon").unwrap();
285        assert!(daemon.is_system_user());
286        let system = Username::new("_system").unwrap();
287        assert!(system.is_system_user());
288        let user = Username::new("user").unwrap();
289        assert!(!user.is_system_user());
290    }
291
292    #[test]
293    fn test_is_service_account() {
294        let svc = Username::new("svc-api").unwrap();
295        assert!(svc.is_service_account());
296        let service = Username::new("service-api").unwrap();
297        assert!(service.is_service_account());
298        let user = Username::new("user").unwrap();
299        assert!(!user.is_service_account());
300    }
301
302    #[test]
303    fn test_from_str() {
304        let username: Username = "root".parse().unwrap();
305        assert_eq!(username.as_str(), "root");
306    }
307
308    #[test]
309    fn test_from_str_error() {
310        assert!("".parse::<Username>().is_err());
311        assert!("1root".parse::<Username>().is_err());
312    }
313
314    #[test]
315    fn test_display() {
316        let username = Username::new("root").unwrap();
317        assert_eq!(format!("{}", username), "root");
318    }
319
320    #[test]
321    fn test_as_ref() {
322        let username = Username::new("root").unwrap();
323        let s: &str = username.as_ref();
324        assert_eq!(s, "root");
325    }
326
327    #[test]
328    fn test_clone() {
329        let username = Username::new("root").unwrap();
330        let username2 = username.clone();
331        assert_eq!(username, username2);
332    }
333
334    #[test]
335    fn test_equality() {
336        let u1 = Username::new("root").unwrap();
337        let u2 = Username::new("root").unwrap();
338        let u3 = Username::new("user").unwrap();
339        assert_eq!(u1, u2);
340        assert_ne!(u1, u3);
341    }
342
343    #[test]
344    fn test_as_inner() {
345        let username = Username::new("root").unwrap();
346        let inner = username.as_inner();
347        assert_eq!(inner.as_str(), "root");
348    }
349
350    #[test]
351    fn test_into_inner() {
352        let username = Username::new("root").unwrap();
353        let inner = username.into_inner();
354        assert_eq!(inner.as_str(), "root");
355    }
356}