Skip to main content

authentication/
user.rs

1//! User management functionality for the Authentication module.
2//!
3//! This module provides user account management including:
4//! - User creation and authentication
5//! - Password management with secure hashing
6//! - User profile management (name, primary group, recorded home)
7//! - File-based persistent storage of user data
8//!
9//! Each account is a JSON record in `/system/accounts/users/`, in a file
10//! named after the user. See the crate documentation for the record format,
11//! home directories and renaming.
12
13use alloc::{
14    borrow::ToOwned,
15    format,
16    string::{String, ToString},
17    vec::Vec,
18};
19use file_system::{AccessFlags, Kind, Path, PathOwned};
20use miniserde::{Deserialize, Serialize};
21use users::{GroupIdentifier, GroupIdentifierInner, UserIdentifier, UserIdentifierInner};
22use virtual_file_system::{Directory, File};
23
24use crate::{
25    ACCOUNT_MUTATIONS, Context, Error, READ_CHUNK_SIZE, Result, USERS_FOLDER_PATH, atomic_write,
26    create_record,
27    hash::{generate_salt, hash_password},
28    remove_created_record,
29};
30
31/// Version written to every account record.
32///
33/// Version 1 records the account's home. Records without a `version` field
34/// predate it and are read as version 0, whose home is `/users/<identifier>`.
35pub const USER_RECORD_VERSION: u8 = 1;
36
37/// Temporary file used to replace an account record atomically.
38///
39/// Password changes and renames hold ACCOUNT_MUTATIONS until the replacement
40/// is complete, so they can reuse this path.
41fn temporary_record_path(identifier: UserIdentifier) -> String {
42    format!("/system/accounts/.user-{}.tmp", identifier.as_u16())
43}
44
45/// Represents a user account with all associated metadata.
46///
47/// This structure contains all the information needed to represent a user
48/// in the system, including their unique identifier, name, primary group,
49/// recorded home and hashed password with salt for security.
50#[derive(Clone, Debug, Serialize)]
51pub struct User {
52    /// Account record format, always [`USER_RECORD_VERSION`] once loaded
53    version: u8,
54    /// Unique identifier for the user
55    identifier: UserIdentifierInner,
56    /// Human-readable username
57    name: String,
58    /// Identifier of the user's primary group
59    primary_group: GroupIdentifierInner,
60    /// Home directory recorded when the account was created
61    home: String,
62    /// SHA-512 hash of the user's password combined with salt
63    hash: String,
64    /// Random salt used for password hashing
65    salt: String,
66}
67
68/// On-disk account record of any supported version.
69#[derive(Deserialize)]
70struct UserRecord {
71    version: Option<u8>,
72    identifier: UserIdentifierInner,
73    name: String,
74    primary_group: GroupIdentifierInner,
75    home: Option<String>,
76    hash: String,
77    salt: String,
78}
79
80impl UserRecord {
81    fn into_user(self) -> Result<User> {
82        let home = match (self.version, self.home) {
83            // Version 0 never recorded a home: its home was derived from the
84            // identifier. This fallback happens in memory only.
85            (None | Some(0), None) => legacy_user_home(UserIdentifier::new(self.identifier)),
86            (Some(USER_RECORD_VERSION), Some(home)) if users::is_valid_user_home(&home) => home,
87            (None | Some(0), Some(_)) | (Some(USER_RECORD_VERSION), _) => {
88                return Err(Error::InvalidUserHome);
89            }
90            (Some(_), _) => return Err(Error::UnsupportedUserRecordVersion),
91        };
92        Ok(User {
93            version: USER_RECORD_VERSION,
94            identifier: self.identifier,
95            name: self.name,
96            primary_group: self.primary_group,
97            home,
98            hash: self.hash,
99            salt: self.salt,
100        })
101    }
102}
103
104impl User {
105    /// Creates a new user instance with the provided information.
106    ///
107    /// # Arguments
108    ///
109    /// * `identifier` - Unique numerical identifier for the user
110    /// * `name` - Human-readable username
111    /// * `primary_group` - Identifier of the user's primary group
112    /// * `home` - Home directory recorded for the account
113    /// * `hash` - Pre-computed SHA-512 hash of password+salt
114    /// * `salt` - Random salt used for password hashing
115    pub fn new(
116        identifier: UserIdentifierInner,
117        name: String,
118        primary_group: GroupIdentifierInner,
119        home: String,
120        hash: String,
121        salt: String,
122    ) -> Self {
123        Self {
124            version: USER_RECORD_VERSION,
125            identifier,
126            name,
127            primary_group,
128            home,
129            hash,
130            salt,
131        }
132    }
133
134    /// Returns the user's unique identifier.
135    pub fn get_identifier(&self) -> UserIdentifier {
136        UserIdentifier::new(self.identifier)
137    }
138
139    /// Returns the user's primary group identifier.
140    pub fn get_primary_group(&self) -> GroupIdentifier {
141        GroupIdentifier::new(self.primary_group)
142    }
143
144    /// Returns the user's name as a string slice.
145    pub fn get_name(&self) -> &str {
146        &self.name
147    }
148
149    /// Returns the home directory recorded in the account.
150    pub fn get_home(&self) -> &str {
151        &self.home
152    }
153
154    /// Returns the user's password hash as a string slice.
155    pub fn get_hash(&self) -> &str {
156        &self.hash
157    }
158
159    /// Returns the user's salt as a string slice.
160    pub fn get_salt(&self) -> &str {
161        &self.salt
162    }
163
164    /// Updates the user's password hash.
165    pub fn set_hash(&mut self, hash: String) {
166        self.hash = hash;
167    }
168
169    /// Updates the user's salt.
170    pub fn set_salt(&mut self, salt: String) {
171        self.salt = salt;
172    }
173
174    /// Updates the user's primary group.
175    pub fn set_primary_group(&mut self, primary_group: GroupIdentifierInner) {
176        self.primary_group = primary_group;
177    }
178
179    /// Updates the user's name. The recorded home is not changed.
180    pub fn set_name(&mut self, name: String) {
181        self.name = name;
182    }
183}
184
185/// Home recorded for a new account: `/users/<user name>`.
186///
187/// Returns [`Error::InvalidUserName`] unless `user_name` satisfies
188/// [`users::is_valid_user_name`].
189pub fn new_user_home(user_name: &str) -> Result<String> {
190    if !users::is_valid_user_name(user_name) {
191        return Err(Error::InvalidUserName);
192    }
193    Ok(format!("{}/{user_name}", Path::USERS.as_str()))
194}
195
196/// Home of an account record saved before homes were recorded.
197fn legacy_user_home(identifier: UserIdentifier) -> String {
198    format!("{}/{}", Path::USERS.as_str(), identifier.as_u16())
199}
200
201/// Parses an account record read from the file named `file_name`.
202///
203/// The file name is authoritative for the user name: a rename moves the record
204/// file first, so an interrupted rename leaves the previous name inside it.
205fn parse_user_record(buffer: &[u8], file_name: &str) -> Result<User> {
206    let text = core::str::from_utf8(buffer).map_err(|_| Error::InvalidUserRecord)?;
207    let mut user = miniserde::json::from_str::<UserRecord>(text)
208        .map_err(Error::FailedToParseUserFile)?
209        .into_user()?;
210    if user.name != file_name {
211        user.name = file_name.to_string();
212    }
213    Ok(user)
214}
215
216/// Constructs the file system path for a user's data file.
217///
218/// Lookups accept any name that is a single, ordinary directory entry, so
219/// accounts created before [`users::is_valid_user_name`] still resolve, while
220/// `/`, `.`, `..`, NUL and control characters can never leave the accounts
221/// directory.
222///
223/// # Errors
224///
225/// Returns [`Error::FailedToGetUserFilePath`] for an unusable name.
226pub fn get_user_file_path(user_name: &str) -> Result<PathOwned> {
227    if user_name.is_empty()
228        || matches!(user_name, "." | "..")
229        || user_name
230            .chars()
231            .any(|character| character == '/' || character.is_control())
232    {
233        return Err(Error::FailedToGetUserFilePath);
234    }
235    Path::new(USERS_FOLDER_PATH)
236        .to_owned()
237        .append(user_name)
238        .ok_or(Error::FailedToGetUserFilePath)
239}
240
241/// Authenticates a user with their username and password.
242///
243/// This function reads the user's file from the filesystem, compares the
244/// provided password hash with the stored hash, and returns the user's
245/// identifier if authentication succeeds.
246///
247/// # Errors
248///
249/// - `FailedToGetUserFilePath` - Invalid username or path construction failure
250/// - `FailedToOpenUserFile` - User file doesn't exist or permission denied
251/// - `FailedToReadUserFile` - I/O error reading user file
252/// - `FailedToParseUserFile` - Invalid JSON format in user file
253/// - `InvalidPassword` - Password doesn't match stored hash
254pub async fn authenticate_user(
255    context: &Context<'_>,
256    user_name: &str,
257    password: &str,
258) -> Result<UserIdentifier> {
259    let path = get_user_file_path(user_name)?;
260
261    let virtual_file_system = context.virtual_file_system;
262    let task = context.task;
263
264    let mut user_file = File::open(virtual_file_system, task, path, AccessFlags::Read.into())
265        .await
266        .map_err(Error::FailedToOpenUserFile)?;
267
268    let mut buffer = Vec::new();
269
270    user_file
271        .read_to_end(&mut buffer, READ_CHUNK_SIZE)
272        .await
273        .map_err(Error::FailedToReadUserFile)?;
274
275    user_file
276        .close(virtual_file_system)
277        .await
278        .map_err(Error::FailedToCloseFile)?;
279
280    let user = parse_user_record(&buffer, user_name)?;
281
282    let hashed_password =
283        hash_password(virtual_file_system, task, password, user.get_salt()).await?;
284
285    if hashed_password == user.get_hash() {
286        Ok(user.get_identifier())
287    } else {
288        Err(Error::InvalidPassword)
289    }
290}
291
292/// Creates a new user account with the specified parameters.
293///
294/// The account records `/users/<user_name>` as its home. The home directory
295/// itself is created lazily, at the first login, by
296/// `VirtualFileSystem::ensure_user_home`.
297///
298/// # Errors
299///
300/// - `InvalidUserName` - The name does not satisfy [`users::is_valid_user_name`]
301/// - `UserHomeAlreadyUsed` - Another account records that home (for example a
302///   renamed account that kept it), or it exists and is not a directory owned
303///   by the new account
304/// - `FailedToCreateUser(DuplicateUserName)` - An account record with that
305///   name already exists, even one this firmware could not load
306/// - User identifier generation or assignment failures
307/// - File system operations (directory creation, file writing)
308/// - Random salt generation failures
309pub async fn create_user(
310    context: &Context<'_>,
311    user_name: &str,
312    password: &str,
313    primary_group: GroupIdentifier,
314    user_identifier: Option<UserIdentifier>,
315) -> Result<UserIdentifier> {
316    let virtual_file_system = context.virtual_file_system;
317    let users_manager = context.users_manager;
318
319    let home = new_user_home(user_name)?;
320    let _mutation = ACCOUNT_MUTATIONS.lock().await;
321
322    // - New user identifier if not provided.
323    let user_identifier = if let Some(user_identifier) = user_identifier {
324        user_identifier
325    } else {
326        users_manager
327            .get_new_user_identifier()
328            .await
329            .map_err(Error::FailedToGetNewUserIdentifier)?
330    };
331
332    // - Never hand an existing home to a different account.
333    if users_manager.is_user_home(&home).await {
334        return Err(Error::UserHomeAlreadyUsed);
335    }
336    match virtual_file_system.get_statistics(&home.as_str()).await {
337        Ok(statistics)
338            if statistics.user != user_identifier || statistics.kind != Kind::Directory =>
339        {
340            return Err(Error::UserHomeAlreadyUsed);
341        }
342        Ok(_) | Err(file_system::IoErrorKind::NotFound) => {}
343        Err(error) => return Err(Error::FailedToReadUserFile(error)),
344    }
345
346    // - Never overwrite an existing record, including one that was skipped
347    //   at load time (unsupported version, invalid home).
348    let user_file_path = get_user_file_path(user_name)?;
349    match virtual_file_system.get_statistics(&user_file_path).await {
350        Ok(_) => {
351            return Err(Error::FailedToCreateUser(users::Error::DuplicateUserName));
352        }
353        Err(file_system::IoErrorKind::NotFound) => {}
354        Err(error) => return Err(Error::FailedToReadUserFile(error)),
355    }
356
357    if users_manager
358        .exists_user(user_identifier)
359        .await
360        .map_err(Error::FailedToCreateUser)?
361    {
362        return Err(Error::FailedToCreateUser(
363            users::Error::DuplicateUserIdentifier,
364        ));
365    }
366    if users_manager.get_user_identifier(user_name).await.is_ok() {
367        return Err(Error::FailedToCreateUser(users::Error::DuplicateUserName));
368    }
369    if !users_manager
370        .exists_group(primary_group)
371        .await
372        .map_err(Error::FailedToCreateUser)?
373    {
374        return Err(Error::FailedToCreateUser(
375            users::Error::InvalidGroupIdentifier,
376        ));
377    }
378
379    // - Hash password.
380    let task = context.task;
381
382    let salt = generate_salt(virtual_file_system, task).await?;
383
384    let hash = hash_password(virtual_file_system, task, password, &salt).await?;
385
386    // - Write user file.
387    let user = User::new(
388        user_identifier.as_u16(),
389        user_name.to_string(),
390        primary_group.as_u16(),
391        home,
392        hash,
393        salt,
394    );
395
396    match Directory::create(virtual_file_system, task, USERS_FOLDER_PATH).await {
397        Ok(_) | Err(virtual_file_system::IoErrorKind::AlreadyExists) => {}
398        Err(error) => Err(Error::FailedToCreateUsersDirectory(error))?,
399    }
400
401    let user_json = miniserde::json::to_string(&user);
402
403    create_record(context, &user_file_path, user_json.as_bytes())
404        .await
405        .map_err(|error| match error {
406            file_system::IoErrorKind::AlreadyExists => {
407                Error::FailedToCreateUser(users::Error::DuplicateUserName)
408            }
409            error => Error::FailedToWriteUserFile(error),
410        })?;
411
412    if let Err(error) = users_manager
413        .add_user(user_identifier, user_name, primary_group, user.get_home())
414        .await
415    {
416        remove_created_record(context, &user_file_path).await;
417        return Err(Error::FailedToCreateUser(error));
418    }
419
420    Ok(user_identifier)
421}
422
423/// Changes a user's password by generating a new salt and hash.
424///
425/// The record is rewritten in the current format: a version 0 record is
426/// upgraded to version 1 and records the home it already used
427/// (`/users/<identifier>`), so its home does not move.
428///
429/// # Errors
430///
431/// - File system errors (opening, reading, writing user file)
432/// - Salt generation failures
433/// - JSON parsing errors
434pub async fn change_user_password(
435    context: &Context<'_>,
436    user_name: &str,
437    new_password: &str,
438) -> Result<()> {
439    let _mutation = ACCOUNT_MUTATIONS.lock().await;
440    let virtual_file_system = context.virtual_file_system;
441    let task = context.task;
442
443    let salt = generate_salt(virtual_file_system, task).await?;
444
445    let hash = hash_password(virtual_file_system, task, new_password, &salt).await?;
446
447    let user_file_path = get_user_file_path(user_name)?;
448
449    let mut buffer = Vec::new();
450
451    File::read_from_path(virtual_file_system, task, &user_file_path, &mut buffer)
452        .await
453        .map_err(Error::FailedToReadUserFile)?;
454
455    let mut user = parse_user_record(&buffer, user_name)?;
456
457    user.set_hash(hash);
458    user.set_salt(salt);
459
460    // Replaced atomically: a power loss leaves the old or the new password,
461    // never a truncated record.
462    atomic_write(
463        context,
464        &temporary_record_path(user.get_identifier()),
465        user_file_path.as_str(),
466        miniserde::json::to_string(&user).as_bytes(),
467    )
468    .await
469}
470
471/// Renames a user account.
472///
473/// Like Linux `usermod --login` without `--move-home`, renaming keeps the
474/// recorded home: `alice` renamed to `alicia` keeps `/users/alice`, and its
475/// contents are neither moved nor lost. Because that home stays recorded, the
476/// name `alice` cannot be given to a new account: `create_user` refuses it
477/// with `UserHomeAlreadyUsed`.
478///
479/// The record file is moved to its new name before the registry is updated.
480/// If the registry update fails, the function attempts to move the file back.
481/// After a successful update, the function replaces the record's contents
482/// atomically. This saves the new name and upgrades version 0 records to
483/// version 1 with their `/users/<identifier>` home. That rewrite is
484/// best effort: the record's file name is authoritative, so if it fails, or
485/// power is lost before it, the account still loads under its new name. A
486/// failed rewrite is logged and the rename still succeeds.
487///
488/// # Errors
489///
490/// - `InvalidUserName` - The new name does not satisfy [`users::is_valid_user_name`]
491/// - `FailedToRenameUser` - The new name is already used, or the account is
492///   not registered
493/// - File system errors (reading, moving, writing user file)
494/// - JSON parsing errors
495pub async fn change_user_name(
496    context: &Context<'_>,
497    current_name: &str,
498    new_name: &str,
499) -> Result<()> {
500    if !users::is_valid_user_name(new_name) {
501        return Err(Error::InvalidUserName);
502    }
503    if current_name == new_name {
504        return Ok(());
505    }
506
507    let _mutation = ACCOUNT_MUTATIONS.lock().await;
508    let virtual_file_system = context.virtual_file_system;
509    let task = context.task;
510    let users_manager = context.users_manager;
511    let current_path = get_user_file_path(current_name)?;
512    let new_path = get_user_file_path(new_name)?;
513
514    let mut buffer = Vec::new();
515
516    File::read_from_path(virtual_file_system, task, &current_path, &mut buffer)
517        .await
518        .map_err(Error::FailedToReadUserFile)?;
519
520    let mut user = parse_user_record(&buffer, current_name)?;
521    let identifier = user.get_identifier();
522
523    if users_manager.get_user_name(identifier).await.as_deref() != Ok(current_name) {
524        return Err(Error::FailedToRenameUser(
525            users::Error::InvalidUserIdentifier,
526        ));
527    }
528    if users_manager.get_user_identifier(new_name).await.is_ok() {
529        return Err(Error::FailedToRenameUser(users::Error::DuplicateUserName));
530    }
531    match virtual_file_system.get_statistics(&new_path).await {
532        Ok(_) => {
533            return Err(Error::FailedToRenameUser(users::Error::DuplicateUserName));
534        }
535        Err(file_system::IoErrorKind::NotFound) => {}
536        Err(error) => return Err(Error::FailedToReadUserFile(error)),
537    }
538
539    virtual_file_system
540        .rename(task, &current_path, &new_path)
541        .await
542        .map_err(Error::FailedToWriteUserFile)?;
543
544    if let Err(error) = users_manager.rename_user(identifier, new_name).await {
545        if let Err(rollback_error) = virtual_file_system
546            .rename(task, &new_path, &current_path)
547            .await
548        {
549            log::warning!(
550                "Failed to move an account record back after a rename failed: {rollback_error}"
551            );
552        }
553        return Err(Error::FailedToRenameUser(error));
554    }
555
556    user.set_name(new_name.to_string());
557
558    if let Err(error) = atomic_write(
559        context,
560        &temporary_record_path(identifier),
561        new_path.as_str(),
562        miniserde::json::to_string(&user).as_bytes(),
563    )
564    .await
565    {
566        log::warning!(
567            "Account {} renamed, but its record could not be rewritten: {error}",
568            identifier.as_u16()
569        );
570    }
571
572    Ok(())
573}
574
575/// Reads and parses a user file from the filesystem.
576///
577/// Version 0 records get their `/users/<identifier>` home in memory; nothing
578/// is written back.
579///
580/// # Errors
581///
582/// - Path construction failures
583/// - File system errors (opening, reading)
584/// - JSON parsing errors, invalid recorded homes and unsupported versions
585pub async fn read_user_file(
586    context: &Context<'_>,
587    buffer: &mut Vec<u8>,
588    file: &str,
589) -> Result<User> {
590    let user_file_path = get_user_file_path(file)?;
591
592    let virtual_file_system = context.virtual_file_system;
593    let task = context.task;
594
595    File::read_from_path(virtual_file_system, task, &user_file_path, buffer)
596        .await
597        .map_err(Error::FailedToReadUserFile)?;
598
599    parse_user_record(buffer, file)
600}
601
602#[cfg(test)]
603mod tests {
604    extern crate std;
605
606    use super::*;
607
608    fn parse(json: &str) -> Result<User> {
609        parse_user_record(json.as_bytes(), "bob")
610    }
611
612    #[test]
613    fn version_zero_records_fall_back_to_the_identifier_home() {
614        let user =
615            parse(r#"{"identifier":42,"name":"bob","primary_group":1000,"hash":"h","salt":"s"}"#)
616                .unwrap();
617        assert_eq!(user.get_home(), "/users/42");
618        assert_eq!(user.get_name(), "bob");
619        // Rewriting a version 0 record records the home it already used.
620        let written = miniserde::json::to_string(&user);
621        assert!(written.contains(r#""version":1"#), "{written}");
622        assert!(written.contains(r#""home":"/users/42""#), "{written}");
623        assert_eq!(parse(&written).unwrap().get_home(), "/users/42");
624    }
625
626    #[test]
627    fn version_one_records_keep_their_recorded_home() {
628        let user = parse(
629            r#"{"version":1,"identifier":42,"name":"bob","primary_group":1000,"home":"/users/robert","hash":"h","salt":"s"}"#,
630        )
631        .unwrap();
632        assert_eq!(user.get_home(), "/users/robert");
633    }
634
635    #[test]
636    fn malformed_or_future_records_are_rejected() {
637        for (json, expected) in [
638            (
639                r#"{"version":1,"identifier":42,"name":"bob","primary_group":1000,"hash":"h","salt":"s"}"#,
640                "home",
641            ),
642            (
643                r#"{"version":1,"identifier":42,"name":"bob","primary_group":1000,"home":"/system","hash":"h","salt":"s"}"#,
644                "home",
645            ),
646            (
647                r#"{"version":1,"identifier":42,"name":"bob","primary_group":1000,"home":"/users/../system","hash":"h","salt":"s"}"#,
648                "home",
649            ),
650            (
651                r#"{"identifier":42,"name":"bob","primary_group":1000,"home":"/users/bob","hash":"h","salt":"s"}"#,
652                "home",
653            ),
654            (
655                r#"{"version":2,"identifier":42,"name":"bob","primary_group":1000,"home":"/users/bob","hash":"h","salt":"s"}"#,
656                "version",
657            ),
658        ] {
659            match (parse(json), expected) {
660                (Err(Error::InvalidUserHome), "home")
661                | (Err(Error::UnsupportedUserRecordVersion), "version") => {}
662                (result, _) => panic!("{json}: {result:?}"),
663            }
664        }
665    }
666
667    #[test]
668    fn the_record_file_name_is_authoritative() {
669        let user = parse_user_record(
670            br#"{"version":1,"identifier":42,"name":"alice","primary_group":1000,"home":"/users/alice","hash":"h","salt":"s"}"#,
671            "alicia",
672        )
673        .unwrap();
674        assert_eq!(user.get_name(), "alicia");
675        assert_eq!(user.get_home(), "/users/alice");
676    }
677
678    #[test]
679    fn new_homes_are_named_after_valid_user_names() {
680        assert_eq!(new_user_home("alice").unwrap(), "/users/alice");
681        for name in ["", ".", "..", "a/b", "../root", "a\0", "1000", "with space"] {
682            assert!(
683                matches!(new_user_home(name), Err(Error::InvalidUserName)),
684                "{name:?}"
685            );
686        }
687    }
688
689    #[test]
690    fn record_paths_stay_inside_the_accounts_directory() {
691        assert_eq!(
692            get_user_file_path("alice").unwrap().as_str(),
693            "/system/accounts/users/alice"
694        );
695        for name in ["", ".", "..", "../groups/administrator", "a/b", "a\0"] {
696            assert!(get_user_file_path(name).is_err(), "{name:?}");
697        }
698    }
699}