linkrs-server 0.1.0

Linkrs network service layer (HTTP/gRPC)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use dashmap::DashMap;
use std::collections::HashMap;
use std::sync::Arc;

use super::PermissionResult;

// Re-export the permission types from the core layer.
pub use linkrs_core::{Permission, RoleType};

/// The Space ID identifier for the God character (a global character, not bound to a specific Space)
pub const GOD_SPACE_ID: i64 = -1;

/// Permission Manager – Data Layer
///
/// Responsibilities:
/// 1. Manage Role mapping(username -> {space_id -> role})
/// 2. Manage space mapping\(space_id -> {username -> [permissions]})
/// 3. Provide basic character query and permission checking functions.
///
/// This layer does not involve any business logic decisions (such as the priority of the God character); it only provides basic data operations.
///
/// Performance optimization:
/// Use DashMap to achieve true concurrent access without the need for explicit locking.
/// Outstanding performance in scenarios where more reading and less writing are required.
pub struct PermissionManager {
    /// User role mapping:username -> {space_id -> role}
    /// The “God” role uses a special space_id: -1 to indicate that it is a global role, which is not associated with a specific Space.
    /// Using DashMap, concurrent read and write operations are supported.
    user_roles: Arc<DashMap<String, HashMap<i64, RoleType>>>,
}

impl Clone for PermissionManager {
    fn clone(&self) -> Self {
        Self {
            user_roles: Arc::clone(&self.user_roles),
        }
    }
}

impl PermissionManager {
    /// Create a new permission manager.
    pub fn new() -> Self {
        let user_roles = DashMap::new();
        let mut root_roles = HashMap::new();
        // The root user acts as the "God" character (the global super administrator).
        // Using GOD_SPACE_ID(-1) to represent global roles, not bound to specific Space
        root_roles.insert(GOD_SPACE_ID, RoleType::God);
        user_roles.insert("root".into(), root_roles);

        Self {
            user_roles: Arc::new(user_roles),
        }
    }

    // ==================== Role Management (Basic CRUD) ====================

    /// Drop all role mappings (used for snapshot rebuild).
    pub fn clear(&self) {
        self.user_roles.clear();
    }

    /// Remove every role mapping of a user (used on user drop).
    pub fn remove_user(&self, username: &str) {
        self.user_roles.remove(username);
    }

    /// Rebuild the whole mapping from persisted snapshot roles.
    pub fn rebuild_from_snapshot(&self, roles: Vec<(String, Vec<(i64, RoleType)>)>) {
        self.user_roles.clear();
        for (username, entries) in roles {
            let mut map = HashMap::new();
            for (space_id, role) in entries {
                map.insert(space_id, role);
            }
            self.user_roles.insert(username, map);
        }
    }

    /// Granting roles
    ///
    /// Using the entry API of DashMap, there is no need to explicitly acquire locks.
    pub fn grant_role(
        &self,
        username: &str,
        space_id: i64,
        role: RoleType,
    ) -> PermissionResult<()> {
        self.user_roles
            .entry(username.to_string())
            .or_default()
            .insert(space_id, role);
        Ok(())
    }

    /// Revoke the role
    ///
    /// Using DashMap, there is no need to explicitly apply locks.
    pub fn revoke_role(&self, username: &str, space_id: i64) -> PermissionResult<()> {
        if let Some(mut roles) = self.user_roles.get_mut(username) {
            roles.remove(&space_id);
        }
        Ok(())
    }

    /// Obtain the user's role in the specified space.
    ///
    /// DashMap supports true concurrent reading.
    pub fn get_role(&self, username: &str, space_id: i64) -> Option<RoleType> {
        self.user_roles
            .get(username)
            .and_then(|roles| roles.get(&space_id).copied())
    }

    /// Obtain all the user's roles
    pub fn get_user_roles(&self, username: &str) -> HashMap<i64, RoleType> {
        self.user_roles
            .get(username)
            .map(|roles| roles.clone())
            .unwrap_or_default()
    }

    /// List all of the user’s roles.
    /// Return a Vec<(space_id, role)> containing the user's roles in all Spaces.
    pub fn list_user_roles(&self, username: &str) -> Vec<(i64, RoleType)> {
        self.user_roles
            .get(username)
            .map(|roles| {
                roles
                    .iter()
                    .map(|(&space_id, &role)| (space_id, role))
                    .collect()
            })
            .unwrap_or_default()
    }

    /// List all users in Space and their respective roles.
    /// Return a Vec<(username, role)> containing all users in the specified Space.
    ///
    /// DashMap supports true concurrent reading; locking is not required during iteration.
    pub fn list_space_users(&self, space_id: i64) -> Vec<(String, RoleType)> {
        self.user_roles
            .iter()
            .filter_map(|entry| {
                let username = entry.key();
                let roles = entry.value();
                roles.get(&space_id).map(|&role| (username.clone(), role))
            })
            .collect()
    }

    /// List all users with their roles in every space.
    /// Returns Vec<(username, Vec<(space_id, role)>)> covering the whole map.
    pub fn list_all_users(&self) -> Vec<(String, Vec<(i64, RoleType)>)> {
        self.user_roles
            .iter()
            .map(|entry| {
                let roles = entry
                    .value()
                    .iter()
                    .map(|(&space_id, &role)| (space_id, role))
                    .collect();
                (entry.key().clone(), roles)
            })
            .collect()
    }

    /// Highest privilege role of a user across all spaces, if any.
    pub fn highest_role(&self, username: &str) -> Option<RoleType> {
        self.user_roles
            .get(username)
            .and_then(|roles| roles.values().copied().min_by_key(|role| role.to_byte()))
    }

    // ==================== Role Query (Basic Query) ====================

    /// Check whether the user is the God character.
    pub fn is_god(&self, username: &str) -> bool {
        self.user_roles
            .get(username)
            .map(|roles| roles.values().any(|&role| role == RoleType::God))
            .unwrap_or(false)
    }

    /// Check whether the user is an administrator (with the God or Admin role).
    ///
    /// User management privilege. Structure management additionally accepts
    /// the Dba role, see `is_schema_admin`.
    pub fn is_admin(&self, username: &str) -> bool {
        self.user_roles
            .get(username)
            .map(|roles| {
                roles
                    .values()
                    .any(|&role| matches!(role, RoleType::God | RoleType::Admin))
            })
            .unwrap_or(false)
    }

    /// Check whether the user holds structure management privilege.
    ///
    /// True for God, Admin and Dba. Matches the role matrix where Dba carries
    /// schema permission but not user administration.
    pub fn is_schema_admin(&self, username: &str) -> bool {
        self.user_roles
            .get(username)
            .map(|roles| {
                roles
                    .values()
                    .any(|&role| matches!(role, RoleType::God | RoleType::Admin | RoleType::Dba))
            })
            .unwrap_or(false)
    }

    /// Check whether the user has the specified role in the designated space.
    pub fn has_role(&self, username: &str, space_id: i64, role: RoleType) -> bool {
        self.get_role(username, space_id)
            .map(|r| r == role)
            .unwrap_or(false)
    }

    // ==================== Permission Check (Basic Verification) ====================

    /// Basic permission check
    /// Check whether the user has the specified permissions in the designated space.
    pub fn check_permission(
        &self,
        username: &str,
        space_id: i64,
        permission: Permission,
    ) -> PermissionResult<()> {
        use crate::permission::PermissionError;

        let role = self
            .get_role(username, space_id)
            .or_else(|| self.get_role(username, GOD_SPACE_ID))
            .ok_or_else(|| PermissionError::no_role_in_space(username.to_string(), space_id))?;

        if role.has_permission(permission) {
            Ok(())
        } else {
            Err(PermissionError::permission_denied(
                format!("{:?}", permission),
                username.to_string(),
            ))
        }
    }

    /// Check whether the user can be granted the role.
    pub fn can_grant_role(&self, granter: &str, space_id: i64, target_role: RoleType) -> bool {
        self.user_roles
            .get(granter)
            .and_then(|roles| roles.get(&space_id).copied())
            .map(|role| role.can_grant(target_role))
            .unwrap_or(false)
    }

    /// Check whether the user can revoke the assigned role.
    pub fn can_revoke_role(&self, revoker: &str, space_id: i64, target_role: RoleType) -> bool {
        self.can_grant_role(revoker, space_id, target_role)
    }
}

impl Default for PermissionManager {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_grant_and_get_role() {
        let pm = PermissionManager::new();

        pm.grant_role("user1", 1, RoleType::Admin)
            .expect("Failed to grant role");

        assert_eq!(pm.get_role("user1", 1), Some(RoleType::Admin));
        assert_eq!(pm.get_role("user1", 2), None);
        assert_eq!(pm.get_role("nonexistent", 1), None);
    }

    #[test]
    fn test_is_god() {
        let pm = PermissionManager::new();

        // The default is God.
        assert!(pm.is_god("root"));

        let _ = pm.grant_role("user1", 1, RoleType::Admin);
        assert!(!pm.is_god("user1"));

        let _ = pm.grant_role("user2", GOD_SPACE_ID, RoleType::God);
        assert!(pm.is_god("user2"));
    }

    #[test]
    fn test_check_permission() {
        let pm = PermissionManager::new();

        pm.grant_role("user1", 1, RoleType::User)
            .expect("Failed to grant role");
        pm.grant_role("guest1", 1, RoleType::Guest)
            .expect("Failed to grant role");

        // The User role has Read and Write permissions
        assert!(pm.check_permission("user1", 1, Permission::Read).is_ok());
        assert!(pm.check_permission("user1", 1, Permission::Write).is_ok());
        // The Guest role has only Read privileges
        assert!(pm.check_permission("guest1", 1, Permission::Read).is_ok());
        assert!(pm.check_permission("guest1", 1, Permission::Write).is_err());
        // unauthorized user
        assert!(pm
            .check_permission("nonexistent", 1, Permission::Read)
            .is_err());
    }

    #[test]
    fn test_can_grant_role() {
        let pm = PermissionManager::new();

        pm.grant_role("admin", 1, RoleType::Admin)
            .expect("Failed to grant role");
        pm.grant_role("user", 1, RoleType::User)
            .expect("Failed to grant role");

        // Admin can grant the User and Guest roles
        assert!(pm.can_grant_role("admin", 1, RoleType::User));
        assert!(pm.can_grant_role("admin", 1, RoleType::Guest));
        // Admin cannot grant the Admin or God role.
        assert!(!pm.can_grant_role("admin", 1, RoleType::Admin));
        assert!(!pm.can_grant_role("admin", 1, RoleType::God));

        // User cannot be granted any role
        assert!(!pm.can_grant_role("user", 1, RoleType::Guest));
    }

    #[test]
    fn test_god_role_global_permission() {
        let pm = PermissionManager::new();

        // God roles have permissions in any space
        assert!(pm.check_permission("root", 999, Permission::Write).is_ok());
        assert!(pm.check_permission("root", 999, Permission::Read).is_ok());
    }

    #[test]
    fn test_list_user_roles() {
        let pm = PermissionManager::new();

        // Granting different roles to users in different Space
        pm.grant_role("multi_user", 1, RoleType::Admin)
            .expect("Failed to grant role");
        pm.grant_role("multi_user", 2, RoleType::User)
            .expect("Failed to grant role");
        pm.grant_role("multi_user", 3, RoleType::Guest)
            .expect("Failed to grant role");

        // List all roles of a user
        let roles = pm.list_user_roles("multi_user");
        assert_eq!(roles.len(), 3);

        // Verify that the correct roles are included
        let role_map: HashMap<i64, RoleType> = roles.into_iter().collect();
        assert_eq!(role_map.get(&1), Some(&RoleType::Admin));
        assert_eq!(role_map.get(&2), Some(&RoleType::User));
        assert_eq!(role_map.get(&3), Some(&RoleType::Guest));

        // Returns an empty list for non-existent users
        let empty_roles = pm.list_user_roles("nonexistent");
        assert!(empty_roles.is_empty());
    }

    #[test]
    fn test_list_space_users() {
        let pm = PermissionManager::new();
        let space_id = 1i64;

        // Granting roles to multiple users
        pm.grant_role("user1", space_id, RoleType::User)
            .expect("Failed to grant role");
        pm.grant_role("user2", space_id, RoleType::Admin)
            .expect("Failed to grant role");
        pm.grant_role("user3", space_id, RoleType::Guest)
            .expect("Failed to grant role");

        // List all users in Space
        let users = pm.list_space_users(space_id);
        assert_eq!(users.len(), 3);

        // Verify that the correct users and roles are included
        let user_map: HashMap<String, RoleType> = users.into_iter().collect();
        assert_eq!(user_map.get("user1"), Some(&RoleType::User));
        assert_eq!(user_map.get("user2"), Some(&RoleType::Admin));
        assert_eq!(user_map.get("user3"), Some(&RoleType::Guest));

        // Empty Space returns an empty list
        let empty_users = pm.list_space_users(999);
        assert!(empty_users.is_empty());
    }
}