rs-tenant 0.4.0

Multi-tenant RBAC authorization engine for Rust
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
use super::{
    PlatformAccessRequest, PlatformAuthorizationSource, PlatformGrantScope,
    PlatformPrincipalStatus, PlatformRoleId, PlatformSubject, TenantDataAccessRequest,
    TenantDataAccessScope, TenantDataScopeQuery, TenantScopedDataAccessRequest,
};
use crate::{AccessDecision, Error, Permission, Result};
use std::collections::HashSet;

/// 平台引擎行为配置。
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct PlatformEngineConfig {
    /// 是否启用平台角色继承遍历。
    pub enable_role_hierarchy: bool,
    /// 是否启用完整资源/动作通配符匹配。
    pub enable_wildcard: bool,
    /// 最大平台角色继承深度。
    pub max_role_depth: usize,
}

impl Default for PlatformEngineConfig {
    fn default() -> Self {
        Self {
            enable_role_hierarchy: false,
            enable_wildcard: false,
            max_role_depth: 16,
        }
    }
}

/// 平台授权引擎。
#[derive(Debug)]
pub struct PlatformEngine<S> {
    source: S,
    config: PlatformEngineConfig,
}

/// [`PlatformEngine`] 构造器。
pub struct PlatformEngineBuilder<S> {
    source: S,
    config: PlatformEngineConfig,
}

impl<S> PlatformEngineBuilder<S> {
    /// 使用默认配置创建构造器。
    pub fn new(source: S) -> Self {
        Self {
            source,
            config: PlatformEngineConfig::default(),
        }
    }

    /// 替换完整平台引擎配置。
    pub fn config(mut self, config: PlatformEngineConfig) -> Self {
        self.config = config;
        self
    }

    /// 启用或禁用平台角色继承。
    pub fn enable_role_hierarchy(mut self, on: bool) -> Self {
        self.config.enable_role_hierarchy = on;
        self
    }

    /// 启用或禁用通配符匹配。
    pub fn enable_wildcard(mut self, on: bool) -> Self {
        self.config.enable_wildcard = on;
        self
    }

    /// 设置最大平台角色继承深度。
    pub fn max_role_depth(mut self, depth: usize) -> Self {
        self.config.max_role_depth = depth;
        self
    }

    /// 构建平台引擎。
    pub fn build(self) -> PlatformEngine<S> {
        PlatformEngine {
            source: self.source,
            config: self.config,
        }
    }
}

impl<S> PlatformEngine<S>
where
    S: PlatformAuthorizationSource,
{
    /// 返回当前平台引擎配置。
    pub fn config(&self) -> &PlatformEngineConfig {
        &self.config
    }

    /// 检查平台主体是否可以访问平台自有资源。
    pub async fn can_platform(&self, request: PlatformAccessRequest) -> Result<AccessDecision> {
        let grants = self
            .matching_grants(&request.subject, &request.permission)
            .await?;
        let allowed = grants
            .into_iter()
            .any(|grant| matches!(grant.scope, PlatformGrantScope::Platform));
        Ok(decision(allowed))
    }

    /// 计算平台权限可访问的租户数据范围。
    pub async fn accessible_tenants(
        &self,
        query: TenantDataScopeQuery,
    ) -> Result<TenantDataAccessScope> {
        let grants = self
            .matching_grants(&query.subject, &query.permission)
            .await?;
        TenantDataAccessScope::merge(grants.into_iter().map(|grant| grant.scope))
    }

    /// 检查平台主体的租户级数据访问权。
    pub async fn can_access_tenant(
        &self,
        request: TenantDataAccessRequest,
    ) -> Result<AccessDecision> {
        let scope = self
            .accessible_tenants(TenantDataScopeQuery {
                subject: request.subject,
                permission: request.permission,
            })
            .await?;
        Ok(decision(scope.allows_tenant(&request.tenant)))
    }

    /// 检查平台主体的租户路径数据访问权。
    pub async fn can_access_tenant_scope(
        &self,
        request: TenantScopedDataAccessRequest,
    ) -> Result<AccessDecision> {
        let scope = self
            .accessible_tenants(TenantDataScopeQuery {
                subject: request.subject,
                permission: request.permission,
            })
            .await?;
        Ok(decision(
            scope.allows_path(&request.tenant, &request.target),
        ))
    }

    /// 过滤出主体拥有且匹配所需权限的有效授权。
    async fn matching_grants(
        &self,
        subject: &PlatformSubject,
        required: &Permission,
    ) -> Result<Vec<PlatformEffectiveGrant>> {
        if self.source.platform_principal_status(subject).await? != PlatformPrincipalStatus::Active
        {
            return Ok(Vec::new());
        }

        let grants = self.effective_grants(subject).await?;
        Ok(grants
            .into_iter()
            .filter(|grant| {
                grant
                    .permission
                    .matches(required, self.config.enable_wildcard)
            })
            .collect())
    }

    /// 计算平台主体在当前配置下的有效授权。
    async fn effective_grants(
        &self,
        subject: &PlatformSubject,
    ) -> Result<Vec<PlatformEffectiveGrant>> {
        let assignments = self.source.platform_role_assignments(subject).await?;
        let mut grants = Vec::new();
        for assignment in assignments {
            let roles = if self.config.enable_role_hierarchy {
                self.expand_roles(assignment.role.clone()).await?
            } else {
                vec![assignment.role]
            };

            for role in roles {
                let permissions = self.source.platform_role_permissions(&role).await?;
                grants.extend(
                    permissions
                        .into_iter()
                        .map(|permission| PlatformEffectiveGrant {
                            permission,
                            scope: assignment.scope.clone(),
                        }),
                );
            }
        }
        Ok(grants)
    }

    /// 展开平台角色及其继承链上的父角色。
    async fn expand_roles(&self, root: PlatformRoleId) -> Result<Vec<PlatformRoleId>> {
        let mut visited = HashSet::new();
        let mut visiting = HashSet::new();
        let mut output = Vec::new();
        self.expand_from(root, &mut visited, &mut visiting, &mut output)
            .await?;
        Ok(output)
    }

    /// 以显式栈遍历平台角色继承图,同时检测环和深度限制。
    async fn expand_from(
        &self,
        root: PlatformRoleId,
        visited: &mut HashSet<PlatformRoleId>,
        visiting: &mut HashSet<PlatformRoleId>,
        output: &mut Vec<PlatformRoleId>,
    ) -> Result<()> {
        visiting.insert(root.clone());
        output.push(root.clone());
        let parents = self.source.platform_parent_roles(&root).await?;
        let mut stack: Vec<(PlatformRoleId, usize, std::vec::IntoIter<PlatformRoleId>)> =
            vec![(root, 0, parents.into_iter())];

        while let Some((current, depth, mut iter)) = stack.pop() {
            if let Some(parent) = iter.next() {
                stack.push((current.clone(), depth, iter));
                let next_depth = depth + 1;
                if next_depth > self.config.max_role_depth {
                    return Err(Error::PlatformRoleDepthExceeded {
                        role: parent,
                        max_depth: self.config.max_role_depth,
                    });
                }
                if visiting.contains(&parent) {
                    return Err(Error::PlatformRoleCycleDetected { role: parent });
                }
                if visited.contains(&parent) {
                    continue;
                }

                let parents = self.source.platform_parent_roles(&parent).await?;
                visiting.insert(parent.clone());
                output.push(parent.clone());
                stack.push((parent, next_depth, parents.into_iter()));
                continue;
            }

            visiting.remove(&current);
            visited.insert(current);
        }

        Ok(())
    }
}

/// 平台引擎内部计算出的有效授权。
#[derive(Clone, Debug)]
struct PlatformEffectiveGrant {
    permission: Permission,
    scope: PlatformGrantScope,
}

/// 将布尔允许结果转换为访问决策。
fn decision(allowed: bool) -> AccessDecision {
    if allowed {
        AccessDecision::Allow
    } else {
        AccessDecision::Deny
    }
}

#[cfg(all(test, feature = "memory-store"))]
mod tests {
    use super::*;
    use crate::platform::{MemoryPlatformSource, TenantScopedRoots};
    use crate::{Permission, ScopePath, ScopeRoots, TenantId};
    use futures::executor::block_on;

    /// 构造平台管理员测试主体。
    fn principal() -> super::PlatformSubject {
        super::PlatformSubject::new(
            crate::platform::PlatformPrincipalId::parse("platform_admin").expect("principal"),
        )
    }

    /// 解析测试平台角色标识符。
    fn role(value: &str) -> PlatformRoleId {
        PlatformRoleId::parse(value).expect("role")
    }

    /// 解析测试租户标识符。
    fn tenant(value: &str) -> TenantId {
        TenantId::parse(value).expect("tenant")
    }

    /// 解析测试范围路径。
    fn path(value: &str) -> ScopePath {
        ScopePath::parse(value).expect("path")
    }

    /// 构造已激活平台主体和角色授权的测试数据源。
    fn active_source(
        scope: PlatformGrantScope,
        permission: &str,
    ) -> (MemoryPlatformSource, PlatformSubject) {
        let source = MemoryPlatformSource::new();
        let subject = principal();
        let role = role("platform_reader");
        source.set_principal_status(subject.principal.clone(), PlatformPrincipalStatus::Active);
        source.add_role_assignment(subject.principal.clone(), role.clone(), scope);
        source.add_role_permission(role, Permission::parse(permission).expect("permission"));
        (source, subject)
    }

    #[test]
    fn can_platform_should_deny_inactive_principal() {
        let source = MemoryPlatformSource::new();
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(engine.can_platform(PlatformAccessRequest {
            subject: principal(),
            permission: Permission::parse("platform/role:update").expect("permission"),
        }))
        .expect("decision");

        assert_eq!(decision, AccessDecision::Deny);
    }

    #[test]
    fn can_platform_should_deny_without_role_assignments() {
        let source = MemoryPlatformSource::new();
        let subject = principal();
        source.set_principal_status(subject.principal.clone(), PlatformPrincipalStatus::Active);
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(engine.can_platform(PlatformAccessRequest {
            subject,
            permission: Permission::parse("platform/role:update").expect("permission"),
        }))
        .expect("decision");

        assert_eq!(decision, AccessDecision::Deny);
    }

    #[test]
    fn can_platform_should_allow_platform_scope() {
        let (source, subject) =
            active_source(PlatformGrantScope::platform(), "platform/role:update");
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(engine.can_platform(PlatformAccessRequest {
            subject,
            permission: Permission::parse("platform/role:update").expect("permission"),
        }))
        .expect("decision");

        assert_eq!(decision, AccessDecision::Allow);
    }

    #[test]
    fn platform_scope_should_not_access_tenant_data() {
        let (source, subject) = active_source(PlatformGrantScope::platform(), "tenant:read");
        let engine = PlatformEngineBuilder::new(source).build();
        let scope = block_on(engine.accessible_tenants(TenantDataScopeQuery {
            subject,
            permission: Permission::parse("tenant:read").expect("permission"),
        }))
        .expect("scope");

        assert_eq!(scope, TenantDataAccessScope::None);
    }

    #[test]
    fn all_tenants_should_access_any_tenant_data() {
        let (source, subject) = active_source(PlatformGrantScope::all_tenants(), "tenant:read");
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(engine.can_access_tenant(TenantDataAccessRequest {
            subject,
            permission: Permission::parse("tenant:read").expect("permission"),
            tenant: tenant("tenant_b"),
        }))
        .expect("decision");

        assert_eq!(decision, AccessDecision::Allow);
    }

    #[test]
    fn tenant_set_should_allow_only_listed_tenant() {
        let (source, subject) = active_source(
            PlatformGrantScope::tenants(vec![tenant("tenant_a")]).expect("scope"),
            "tenant:read",
        );
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(engine.can_access_tenant(TenantDataAccessRequest {
            subject,
            permission: Permission::parse("tenant:read").expect("permission"),
            tenant: tenant("tenant_b"),
        }))
        .expect("decision");

        assert_eq!(decision, AccessDecision::Deny);
    }

    #[test]
    fn tenant_paths_should_allow_descendant_path() {
        let (source, subject) = active_source(
            PlatformGrantScope::tenant_paths(vec![TenantScopedRoots::new(
                tenant("tenant_a"),
                ScopeRoots::new(vec![path("agent/1")]).expect("roots"),
            )])
            .expect("scope"),
            "tenant/order:read",
        );
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(
            engine.can_access_tenant_scope(TenantScopedDataAccessRequest {
                subject,
                permission: Permission::parse("tenant/order:read").expect("permission"),
                tenant: tenant("tenant_a"),
                target: path("agent/1/store/2"),
            }),
        )
        .expect("decision");

        assert_eq!(decision, AccessDecision::Allow);
    }

    #[test]
    fn tenant_paths_should_deny_sibling_path() {
        let (source, subject) = active_source(
            PlatformGrantScope::tenant_paths(vec![TenantScopedRoots::new(
                tenant("tenant_a"),
                ScopeRoots::new(vec![path("agent/1")]).expect("roots"),
            )])
            .expect("scope"),
            "tenant/order:read",
        );
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(
            engine.can_access_tenant_scope(TenantScopedDataAccessRequest {
                subject,
                permission: Permission::parse("tenant/order:read").expect("permission"),
                tenant: tenant("tenant_a"),
                target: path("agent/2/store/1"),
            }),
        )
        .expect("decision");

        assert_eq!(decision, AccessDecision::Deny);
    }

    #[test]
    fn tenant_paths_should_not_allow_tenant_level_access() {
        let (source, subject) = active_source(
            PlatformGrantScope::tenant_paths(vec![TenantScopedRoots::new(
                tenant("tenant_a"),
                ScopeRoots::new(vec![path("agent/1")]).expect("roots"),
            )])
            .expect("scope"),
            "tenant:read",
        );
        let engine = PlatformEngineBuilder::new(source).build();
        let decision = block_on(engine.can_access_tenant(TenantDataAccessRequest {
            subject,
            permission: Permission::parse("tenant:read").expect("permission"),
            tenant: tenant("tenant_a"),
        }))
        .expect("decision");

        assert_eq!(decision, AccessDecision::Deny);
    }

    #[test]
    fn multiple_role_assignments_should_merge_tenant_scope() {
        let source = MemoryPlatformSource::new();
        let subject = principal();
        let role_a = role("tenant_a_reader");
        let role_b = role("tenant_b_reader");
        let permission = Permission::parse("tenant:read").expect("permission");
        source.set_principal_status(subject.principal.clone(), PlatformPrincipalStatus::Active);
        source.add_role_assignment(
            subject.principal.clone(),
            role_a.clone(),
            PlatformGrantScope::tenants(vec![tenant("tenant_a")]).expect("scope"),
        );
        source.add_role_assignment(
            subject.principal.clone(),
            role_b.clone(),
            PlatformGrantScope::tenants(vec![tenant("tenant_b")]).expect("scope"),
        );
        source.add_role_permission(role_a, permission.clone());
        source.add_role_permission(role_b, permission.clone());
        let engine = PlatformEngineBuilder::new(source).build();
        let scope = block_on(engine.accessible_tenants(TenantDataScopeQuery {
            subject,
            permission,
        }))
        .expect("scope");

        assert_eq!(
            scope,
            TenantDataAccessScope::Tenants {
                tenants: vec![tenant("tenant_a"), tenant("tenant_b")]
            }
        );
    }

    #[test]
    fn mixed_tenant_and_path_assignments_should_return_error() {
        let source = MemoryPlatformSource::new();
        let subject = principal();
        let tenant_role = role("tenant_reader");
        let path_role = role("path_reader");
        let permission = Permission::parse("tenant/order:read").expect("permission");
        source.set_principal_status(subject.principal.clone(), PlatformPrincipalStatus::Active);
        source.add_role_assignment(
            subject.principal.clone(),
            tenant_role.clone(),
            PlatformGrantScope::tenants(vec![tenant("tenant_a")]).expect("scope"),
        );
        source.add_role_assignment(
            subject.principal.clone(),
            path_role.clone(),
            PlatformGrantScope::tenant_paths(vec![TenantScopedRoots::new(
                tenant("tenant_b"),
                ScopeRoots::new(vec![path("agent/1")]).expect("roots"),
            )])
            .expect("scope"),
        );
        source.add_role_permission(tenant_role, permission.clone());
        source.add_role_permission(path_role, permission.clone());
        let engine = PlatformEngineBuilder::new(source).build();

        let err = block_on(engine.accessible_tenants(TenantDataScopeQuery {
            subject: subject.clone(),
            permission: permission.clone(),
        }))
        .expect_err("must reject mixed grants");
        assert!(err.to_string().contains("must not mix"));

        let err = block_on(
            engine.can_access_tenant_scope(TenantScopedDataAccessRequest {
                subject,
                permission,
                tenant: tenant("tenant_b"),
                target: path("agent/1/order/1"),
            }),
        )
        .expect_err("must reject mixed grants consistently");
        assert!(err.to_string().contains("must not mix"));
    }

    #[test]
    fn role_hierarchy_should_use_parent_permissions() {
        let source = MemoryPlatformSource::new();
        let subject = principal();
        let child = role("child");
        let parent = role("parent");
        source.set_principal_status(subject.principal.clone(), PlatformPrincipalStatus::Active);
        source.add_role_assignment(
            subject.principal.clone(),
            child.clone(),
            PlatformGrantScope::platform(),
        );
        source.add_parent_role(child, parent.clone());
        source.add_role_permission(
            parent,
            Permission::parse("platform/role:update").expect("permission"),
        );
        let engine = PlatformEngineBuilder::new(source)
            .enable_role_hierarchy(true)
            .build();
        let decision = block_on(engine.can_platform(PlatformAccessRequest {
            subject,
            permission: Permission::parse("platform/role:update").expect("permission"),
        }))
        .expect("decision");

        assert_eq!(decision, AccessDecision::Allow);
    }

    #[test]
    fn role_hierarchy_should_detect_cycle() {
        let source = MemoryPlatformSource::new();
        let subject = principal();
        let child = role("child");
        let parent = role("parent");
        source.set_principal_status(subject.principal.clone(), PlatformPrincipalStatus::Active);
        source.add_role_assignment(
            subject.principal.clone(),
            child.clone(),
            PlatformGrantScope::platform(),
        );
        source.add_parent_role(child.clone(), parent.clone());
        source.add_parent_role(parent, child.clone());
        let engine = PlatformEngineBuilder::new(source)
            .enable_role_hierarchy(true)
            .build();
        let err = block_on(engine.can_platform(PlatformAccessRequest {
            subject,
            permission: Permission::parse("platform/role:update").expect("permission"),
        }))
        .expect_err("must detect cycle");

        assert!(matches!(
            err,
            Error::PlatformRoleCycleDetected { role } if role == child
        ));
    }

    #[test]
    fn role_hierarchy_should_limit_max_depth() {
        let source = MemoryPlatformSource::new();
        let subject = principal();
        let child = role("child");
        let parent = role("parent");
        let grandparent = role("grandparent");
        source.set_principal_status(subject.principal.clone(), PlatformPrincipalStatus::Active);
        source.add_role_assignment(
            subject.principal.clone(),
            child.clone(),
            PlatformGrantScope::platform(),
        );
        source.add_parent_role(child, parent);
        source.add_parent_role(role("parent"), grandparent.clone());
        let engine = PlatformEngineBuilder::new(source)
            .enable_role_hierarchy(true)
            .max_role_depth(1)
            .build();
        let err = block_on(engine.can_platform(PlatformAccessRequest {
            subject,
            permission: Permission::parse("platform/role:update").expect("permission"),
        }))
        .expect_err("must enforce depth");

        assert!(matches!(
            err,
            Error::PlatformRoleDepthExceeded { role, max_depth: 1 } if role == grandparent
        ));
    }

    #[test]
    fn wildcard_should_require_config_flag() {
        let (source, subject) = active_source(PlatformGrantScope::platform(), "platform/role:*");
        let strict_engine = PlatformEngineBuilder::new(source.clone()).build();
        let wildcard_engine = PlatformEngineBuilder::new(source)
            .enable_wildcard(true)
            .build();
        let request = PlatformAccessRequest {
            subject,
            permission: Permission::parse("platform/role:update").expect("permission"),
        };

        let strict = block_on(strict_engine.can_platform(request.clone())).expect("decision");
        let wildcard = block_on(wildcard_engine.can_platform(request)).expect("decision");

        assert_eq!(strict, AccessDecision::Deny);
        assert_eq!(wildcard, AccessDecision::Allow);
    }
}