authentication/group.rs
1// Group management functionality for the Authentication module.
2//
3// This module provides group management capabilities including:
4// - Group creation and management
5// - User group membership tracking
6// - File-based persistent storage of group data
7//
8// All group data is stored as JSON files in the `/System/Groups/` directory,
9// with each group having their own file named after their group name.
10
11use alloc::{
12 borrow::ToOwned,
13 string::{String, ToString},
14 vec,
15 vec::Vec,
16};
17use file_system::{AccessFlags, Path, PathOwned};
18use miniserde::{Deserialize, Serialize};
19use users::{GroupIdentifier, GroupIdentifierInner, UserIdentifier, UserIdentifierInner};
20use virtual_file_system::{Directory, File};
21
22use crate::{
23 ACCOUNT_MUTATIONS, Context, Error, GROUP_FOLDER_PATH, Result, create_record,
24 remove_created_record,
25};
26
27/// Represents a user group with associated metadata and member list.
28///
29/// This structure contains all the information needed to represent a group
30/// in the system, including its unique identifier, name, and list of users
31/// that belong to the group.
32#[derive(Clone, Debug, Deserialize, Serialize)]
33pub struct Group {
34 /// Unique identifier for the group
35 identifier: GroupIdentifierInner,
36 /// Human-readable group name
37 name: String,
38 /// List of user identifiers that belong to this group
39 users: Vec<UserIdentifierInner>,
40}
41
42impl Group {
43 /// Creates a new group instance with the provided information.
44 ///
45 /// # Arguments
46 ///
47 /// * `Identifier` - Unique numerical identifier for the group
48 /// * `Name` - Human-readable group name
49 /// * `Users` - List of user identifiers that belong to this group
50 ///
51 /// # Returns
52 ///
53 /// A new `Group_type` instance with the provided data.
54 pub fn new(
55 identifier: GroupIdentifierInner,
56 name: String,
57 users: Vec<UserIdentifierInner>,
58 ) -> Self {
59 Self {
60 identifier,
61 name,
62 users,
63 }
64 }
65
66 /// Returns the group's unique identifier.
67 ///
68 /// # Returns
69 ///
70 /// A `GroupIdentifier` containing the group's unique ID.
71 pub fn get_identifier(&self) -> GroupIdentifier {
72 GroupIdentifier::new(self.identifier)
73 }
74
75 /// Returns the group's name as a string slice.
76 ///
77 /// # Returns
78 ///
79 /// A string slice containing the group name.
80 pub fn get_name(&self) -> &str {
81 &self.name
82 }
83
84 /// Returns the list of users that belong to this group.
85 ///
86 /// This function uses unsafe transmutation to avoid copying the vector,
87 /// since `UserIdentifier` is transparent to `User_identifier_inner_type`.
88 ///
89 /// # Returns
90 ///
91 /// A slice of `UserIdentifier` containing all group members.
92 pub fn get_users(&self) -> &[UserIdentifier] {
93 // Avoid to copy the vector since UserIdentifier is transparent to User_identifier_inner_type.
94 unsafe { core::mem::transmute(self.users.as_slice()) }
95 }
96}
97
98/// Constructs the file system path for a group's data file.
99///
100/// # Arguments
101///
102/// * `Group_name` - The group name to generate a path for
103///
104/// # Returns
105///
106/// Returns `Ok(Path_owned_type)` with the complete path to the group file,
107/// or `Err(Error::Failed_to_get_group_file_path)` if path construction fails.
108pub fn get_group_file_path(group_name: &str) -> Result<PathOwned> {
109 Path::new(GROUP_FOLDER_PATH)
110 .to_owned()
111 .append(group_name)
112 .ok_or(Error::FailedToGetGroupFilePath)
113}
114
115/// Reads and parses a group file from the filesystem.
116///
117/// This function is used internally to load group data from JSON files.
118/// It reads the file contents into the provided buffer and deserializes
119/// the JSON data into a `Group_type` structure.
120///
121/// # Arguments
122///
123/// * `Virtual_file_system` - Reference to the virtual file system
124/// * `Buffer` - Mutable buffer to use for reading file contents
125/// * `File` - Name of the group file to read
126///
127/// # Returns
128///
129/// Returns `Ok(Group_type)` with the parsed group data,
130/// or an appropriate error if reading or parsing fails.
131///
132/// # Errors
133///
134/// - Path construction failures
135/// - File system errors (opening, reading)
136/// - JSON parsing errors
137pub async fn read_group_file(
138 context: &Context<'_>,
139 buffer: &mut Vec<u8>,
140 file: &str,
141) -> Result<Group> {
142 let group_file_path = Path::new(GROUP_FOLDER_PATH)
143 .to_owned()
144 .append(file)
145 .ok_or(Error::FailedToGetGroupFilePath)?;
146
147 let virtual_file_system = context.virtual_file_system;
148 let task = context.task;
149
150 let mut group_file = File::open(
151 virtual_file_system,
152 task,
153 group_file_path,
154 AccessFlags::Read.into(),
155 )
156 .await
157 .map_err(Error::FailedToOpenGroupFile)?;
158
159 buffer.clear();
160
161 group_file
162 .read_to_end(buffer, 32)
163 .await
164 .map_err(Error::FailedToReadGroupFile)?;
165
166 group_file
167 .close(virtual_file_system)
168 .await
169 .map_err(Error::FailedToCloseFile)?;
170
171 let text = core::str::from_utf8(buffer)
172 .map_err(|_| Error::FailedToParseGroupFile(miniserde::Error))?;
173
174 miniserde::json::from_str(text).map_err(Error::FailedToParseGroupFile)
175}
176
177/// Creates a new group with the specified parameters.
178///
179/// This function creates a new group in the system by:
180/// 1. Generating a new group identifier (if not provided)
181/// 2. Creating the group record
182/// 3. Adding the group to the Users manager
183///
184/// The group is created with an empty user list initially.
185///
186/// # Arguments
187///
188/// * `Virtual_file_system` - Reference to the virtual file system
189/// * `Group_name` - Name for the new group
190/// * `Group_identifier` - Optional specific group identifier (auto-generated if None)
191///
192/// # Returns
193///
194/// Returns `Ok(GroupIdentifier)` with the new group's identifier,
195/// or an appropriate error if creation fails.
196///
197/// # Errors
198///
199/// This function can fail for various reasons including:
200/// - Group identifier generation or assignment failures
201/// - File system operations (directory creation, file writing)
202/// - Users manager operations (adding group)
203pub async fn create_group(
204 context: &Context<'_>,
205 group_name: &str,
206 group_identifier: Option<GroupIdentifier>,
207) -> Result<GroupIdentifier> {
208 let _mutation = ACCOUNT_MUTATIONS.lock().await;
209 let virtual_file_system = context.virtual_file_system;
210 let users_manager = context.users_manager;
211
212 // - New group identifier if not provided.
213 let group_identifier = if let Some(group_identifier) = group_identifier {
214 group_identifier
215 } else {
216 users_manager
217 .get_new_group_identifier()
218 .await
219 .map_err(Error::FailedToGetNewGroupIdentifier)?
220 };
221
222 if users_manager
223 .exists_group(group_identifier)
224 .await
225 .map_err(Error::FailedToAddGroup)?
226 {
227 return Err(Error::FailedToAddGroup(
228 users::Error::DuplicateGroupIdentifier,
229 ));
230 }
231 if users_manager.get_group_identifier(group_name).await.is_ok() {
232 return Err(Error::FailedToAddGroup(users::Error::DuplicateGroupName));
233 }
234
235 let group = Group::new(group_identifier.as_u16(), group_name.to_string(), vec![]);
236
237 let task = context.task;
238
239 match Directory::create(virtual_file_system, task, GROUP_FOLDER_PATH).await {
240 Ok(_) | Err(virtual_file_system::IoErrorKind::AlreadyExists) => {}
241 Err(error) => Err(Error::FailedToCreateGroupsDirectory(error))?,
242 };
243
244 let group_file_path = get_group_file_path(group_name)?;
245
246 let group_json = miniserde::json::to_string(&group);
247
248 create_record(context, &group_file_path, group_json.as_bytes())
249 .await
250 .map_err(Error::FailedToWriteGroupFile)?;
251
252 if let Err(error) = users_manager
253 .add_group(group_identifier, group_name, &[])
254 .await
255 {
256 remove_created_record(context, &group_file_path).await;
257 return Err(Error::FailedToAddGroup(error));
258 }
259
260 Ok(group_identifier)
261}