backbone-authorization 3.8.2

Backbone Framework Authorization - Centralized RBAC authorization service
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Authorization types
//!
//! Core types for authorization system.

use serde::{Deserialize, Serialize};
use std::fmt;

/// Authorization error
#[derive(Debug, Clone, thiserror::Error)]
pub enum AuthorizationError {
    /// No user matches the given identifier.
    #[error("User not found: {0}")]
    UserNotFound(String),

    /// The user lacks the permission the request needs.
    #[error("Permission denied: {0}")]
    PermissionDenied(String),

    /// The presented token is malformed, expired or not trusted.
    #[error("Invalid token: {0}")]
    InvalidToken(String),

    /// The authorization setup itself is wrong.
    #[error("Configuration error: {0}")]
    Configuration(String),

    /// Reading roles or permissions from storage failed.
    #[error("Database error: {0}")]
    Database(String),
}

/// User information with roles and permissions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthUser {
    /// The user's identifier.
    pub user_id: String,
    /// The user's login name.
    pub username: String,
    /// Role names the user holds.
    pub roles: Vec<String>,
    /// Permission names granted directly or through roles.
    pub permissions: Vec<String>,
    /// When the authorization expires, as a Unix timestamp in seconds.
    pub expires_at: Option<i64>,
}

/// Action types for permissions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Action {
    /// Create a record.
    Create,
    /// Read one record.
    Read,
    /// Change a record.
    Update,
    /// Remove a record.
    Delete,
    /// List records.
    List,
    /// Bring back a removed record.
    Restore,
}

impl Action {
    /// Every action.
    pub fn all() -> Vec<Self> {
        vec![
            Self::Create,
            Self::Read,
            Self::Update,
            Self::Delete,
            Self::List,
            Self::Restore,
        ]
    }
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Create => write!(f, "create"),
            Self::Read => write!(f, "read"),
            Self::Update => write!(f, "update"),
            Self::Delete => write!(f, "delete"),
            Self::List => write!(f, "list"),
            Self::Restore => write!(f, "restore"),
        }
    }
}

/// Resource types for permissions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Resource {
    /// User accounts.
    User,
    /// Roles.
    Role,
    /// Permission definitions.
    Permission,
    /// System settings.
    Settings,
}

impl Resource {
    /// Every resource.
    pub fn all() -> Vec<Self> {
        vec![
            Self::User,
            Self::Role,
            Self::Permission,
            Self::Settings,
        ]
    }
}

impl fmt::Display for Resource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::User => write!(f, "user"),
            Self::Role => write!(f, "role"),
            Self::Permission => write!(f, "permission"),
            Self::Settings => write!(f, "settings"),
        }
    }
}

/// Standard roles
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Role {
    /// Every permission, without checks.
    SuperAdmin,
    /// Administers the system.
    Admin,
    /// A signed-in user.
    User,
    /// An anonymous or unprivileged visitor.
    Guest,
}

impl Role {
    /// The names of every standard role.
    pub fn all() -> Vec<&'static str> {
        vec![
            "super_admin",
            "admin",
            "user",
            "guest",
        ]
    }

    /// The role's name.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::SuperAdmin => "super_admin",
            Self::Admin => "admin",
            Self::User => "user",
            Self::Guest => "guest",
        }
    }

    /// The standard role with this name, if any.
    pub fn from_str(s: &str) -> Option<Self> {
        match s {
            "super_admin" => Some(Self::SuperAdmin),
            "admin" => Some(Self::Admin),
            "user" => Some(Self::User),
            "guest" => Some(Self::Guest),
            _ => None,
        }
    }
}

/// Permission check result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionCheck {
    /// Whether the permission was granted.
    pub allowed: bool,
    /// The permission checked.
    pub permission: Permission,
    /// Why it was granted or refused.
    pub reason: String,
}

/// Authorization request
#[derive(Debug, Clone)]
pub struct AuthorizationRequest {
    /// Who is asking.
    pub user: AuthUser,
    /// What kind of record the action touches.
    pub resource: Resource,
    /// What the user wants to do.
    pub action: Action,
    /// The one record, when the action targets one.
    pub resource_id: Option<String>,
}

/// Authorization response
#[derive(Debug, Clone)]
pub struct AuthorizationResponse {
    /// Whether the request is allowed.
    pub allowed: bool,
    /// Each permission checked on the way to the answer.
    pub checks: Vec<PermissionCheck>,
}

/// Authorization configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorizationConfig {
    /// How long a cached permission answer stays valid, in seconds.
    pub cache_ttl_seconds: u64,
    /// The role a user without any role is treated as.
    pub default_role: String,
    /// Whether permission answers are cached.
    pub enable_permission_caching: bool,
}

impl Default for AuthorizationConfig {
    fn default() -> Self {
        Self {
            cache_ttl_seconds: 300, // 5 minutes
            default_role: "guest".to_string(),
            enable_permission_caching: true,
        }
    }
}

/// User actions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum UserAction {
    /// Create one.
    Create,
    /// Read one.
    Read,
    /// Change one.
    Update,
    /// Remove one.
    Delete,
    /// List them.
    List,
    /// Reset the user's password.
    ResetPassword,
    /// Change the user's roles.
    ChangeRole,
}

/// Role actions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RoleAction {
    /// Create one.
    Create,
    /// Read one.
    Read,
    /// Change one.
    Update,
    /// Remove one.
    Delete,
    /// List them.
    List,
    /// Grant a permission to the role.
    AssignPermission,
    /// Take a permission from the role.
    RevokePermission,
}

/// Permission actions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionAction {
    /// Create one.
    Create,
    /// Read one.
    Read,
    /// Change one.
    Update,
    /// Remove one.
    Delete,
    /// List them.
    List,
}

/// Settings actions
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SettingsAction {
    /// Create one.
    Create,
    /// Read one.
    Read,
    /// Change one.
    Update,
    /// Remove one.
    Delete,
    /// List them.
    List,
}

/// Permission definition
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Permission {
    /// An action on user accounts.
    User(UserAction),
    /// An action on roles.
    Role(RoleAction),
    /// An action on permission definitions.
    Permission(PermissionAction),
    /// An action on system settings.
    Settings(SettingsAction),
}

impl Permission {
    /// Get all possible permissions
    pub fn all_permissions() -> HashSet<Permission> {
        let mut perms = HashSet::new();

        // User permissions
        for action in UserAction::all() {
            perms.insert(Permission::User(action));
        }

        // Role permissions
        for action in RoleAction::all() {
            perms.insert(Permission::Role(action));
        }

        // Permission permissions
        for action in PermissionAction::all() {
            perms.insert(Permission::Permission(action));
        }

        // Settings permissions
        for action in SettingsAction::all() {
            perms.insert(Permission::Settings(action));
        }

        perms
    }

    /// Create permission from action and resource.
    ///
    /// The action enums carry no restore of their own, so restoring a record
    /// asks for the permission to delete it: whoever may remove a record may
    /// bring it back, and no unrelated permission (a password reset, a
    /// permission grant) opens the restore path.
    pub fn from_action_resource(action: Action, resource: Resource) -> Self {
        match resource {
            Resource::User => match action {
                Action::Create => Permission::User(UserAction::Create),
                Action::Read => Permission::User(UserAction::Read),
                Action::Update => Permission::User(UserAction::Update),
                Action::Delete => Permission::User(UserAction::Delete),
                Action::List => Permission::User(UserAction::List),
                Action::Restore => Permission::User(UserAction::Delete),
            },
            Resource::Role => match action {
                Action::Create => Permission::Role(RoleAction::Create),
                Action::Read => Permission::Role(RoleAction::Read),
                Action::Update => Permission::Role(RoleAction::Update),
                Action::Delete => Permission::Role(RoleAction::Delete),
                Action::List => Permission::Role(RoleAction::List),
                Action::Restore => Permission::Role(RoleAction::Delete),
            },
            Resource::Permission => match action {
                Action::Create => Permission::Permission(PermissionAction::Create),
                Action::Read => Permission::Permission(PermissionAction::Read),
                Action::Update => Permission::Permission(PermissionAction::Update),
                Action::Delete => Permission::Permission(PermissionAction::Delete),
                Action::List => Permission::Permission(PermissionAction::List),
                Action::Restore => Permission::Permission(PermissionAction::Delete),
            },
            Resource::Settings => match action {
                Action::Create => Permission::Settings(SettingsAction::Create),
                Action::Read => Permission::Settings(SettingsAction::Read),
                Action::Update => Permission::Settings(SettingsAction::Update),
                Action::Delete => Permission::Settings(SettingsAction::Delete),
                Action::List => Permission::Settings(SettingsAction::List),
                Action::Restore => Permission::Settings(SettingsAction::Delete),
            },
        }
    }
}

impl UserAction {
    /// Every user action.
    pub fn all() -> Vec<Self> {
        vec![
            Self::Create,
            Self::Read,
            Self::Update,
            Self::Delete,
            Self::List,
            Self::ResetPassword,
            Self::ChangeRole,
        ]
    }
}

impl RoleAction {
    /// Every role action.
    pub fn all() -> Vec<Self> {
        vec![
            Self::Create,
            Self::Read,
            Self::Update,
            Self::Delete,
            Self::List,
            Self::AssignPermission,
            Self::RevokePermission,
        ]
    }
}

impl PermissionAction {
    /// Every permission action.
    pub fn all() -> Vec<Self> {
        vec![
            Self::Create,
            Self::Read,
            Self::Update,
            Self::Delete,
            Self::List,
        ]
    }
}

impl SettingsAction {
    /// Every settings action.
    pub fn all() -> Vec<Self> {
        vec![
            Self::Create,
            Self::Read,
            Self::Update,
            Self::Delete,
            Self::List,
        ]
    }
}

use std::collections::HashSet;

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

    #[test]
    fn restoring_a_record_requires_the_permission_to_delete_it() {
        assert_eq!(
            Permission::from_action_resource(Action::Restore, Resource::User),
            Permission::User(UserAction::Delete)
        );
        assert_eq!(
            Permission::from_action_resource(Action::Restore, Resource::Role),
            Permission::Role(RoleAction::Delete)
        );
        assert_eq!(
            Permission::from_action_resource(Action::Restore, Resource::Permission),
            Permission::Permission(PermissionAction::Delete)
        );
        assert_eq!(
            Permission::from_action_resource(Action::Restore, Resource::Settings),
            Permission::Settings(SettingsAction::Delete)
        );
    }
}