typesec-rbac 0.8.0

RBAC policy engine for typesec — YAML → typed enforcement
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
//! RBAC policy engine — implements [`PolicyEngine`] for [`RbacPolicy`].

use std::collections::{HashMap, HashSet};

use glob::Pattern;
use tracing::debug;
use typesec_core::{
    ResourceId, SubjectId,
    policy::{PolicyEngine, PolicyResult},
};

use crate::model::RbacPolicy;

/// A compiled, fast-lookup RBAC engine.
///
/// After construction from an [`RbacPolicy`], the engine pre-computes:
/// - Effective permissions per role (with inheritance flattened).
/// - Subject → role mappings.
///
/// Every `check()` call does O(roles × patterns) work — fast enough for
/// the sizes of policies used in AI agent deployments.
pub struct RbacEngine {
    /// Subject → set of effective (permission, resource_pattern) pairs.
    subject_grants: HashMap<String, Vec<CompiledGrant>>,
    /// Glob subject pattern → set of effective grants.
    wildcard_subject_grants: Vec<(SubjectPattern, Vec<CompiledGrant>)>,
}

#[derive(Debug, Clone)]
struct Grant {
    permission: String,
    resource_patterns: Vec<String>,
}

/// A grant with its glob patterns validated and compiled once at load time.
///
/// Compiling here (rather than per `check()`) both surfaces pattern typos as
/// load errors — a malformed pattern would otherwise silently never match,
/// i.e. silently deny — and avoids re-parsing the glob on every check.
#[derive(Debug, Clone)]
struct CompiledGrant {
    permission: String,
    resource_patterns: Vec<ResourcePattern>,
}

#[derive(Debug, Clone)]
enum ResourcePattern {
    /// The literal `"*"` — matches every resource, including across `/`.
    Any,
    /// A compiled glob. Note glob `*` does not cross `/` separators:
    /// `reports/*` matches `reports/q1` but not `reports/2024/q1` (use
    /// `reports/**` for that).
    Glob(Pattern),
}

#[derive(Debug, Clone)]
enum SubjectPattern {
    /// The literal `"*"` — matches every subject.
    Any,
    /// A compiled glob.
    Glob(Pattern),
}

impl SubjectPattern {
    fn compile(pattern: &str) -> Result<Self, String> {
        if pattern == "*" {
            return Ok(Self::Any);
        }
        Pattern::new(pattern)
            .map(Self::Glob)
            .map_err(|e| format!("invalid subject pattern '{pattern}': {e}"))
    }

    fn matches(&self, subject: &str) -> bool {
        match self {
            Self::Any => true,
            Self::Glob(pattern) => pattern.matches(subject),
        }
    }
}

impl ResourcePattern {
    fn compile(pattern: &str) -> Result<Self, String> {
        if pattern == "*" {
            return Ok(Self::Any);
        }
        Pattern::new(pattern)
            .map(Self::Glob)
            .map_err(|e| format!("invalid resource pattern '{pattern}': {e}"))
    }

    fn matches(&self, resource: &str) -> bool {
        match self {
            Self::Any => true,
            Self::Glob(pattern) => pattern.matches(resource),
        }
    }
}

impl RbacEngine {
    /// Build an engine from a validated [`RbacPolicy`].
    ///
    /// Returns an error if the policy fails validation.
    pub fn new(policy: RbacPolicy) -> Result<Self, String> {
        policy.validate()?;

        // Step 1: flatten role inheritance into effective (permission, resources) pairs.
        let effective_roles: HashMap<String, Vec<Grant>> = {
            let mut map = HashMap::new();
            for role in &policy.roles {
                let grants = flatten_role(&role.name, &policy);
                map.insert(role.name.clone(), grants);
            }
            map
        };

        // Step 2: build subject → grants mapping, compiling patterns up front
        // so invalid globs fail the policy load instead of silently denying.
        let mut subject_grants: HashMap<String, Vec<CompiledGrant>> = HashMap::new();
        let mut wildcard_subject_grants: Vec<(SubjectPattern, Vec<CompiledGrant>)> = Vec::new();
        for assignment in &policy.assignments {
            let mut all_grants: Vec<CompiledGrant> = Vec::new();
            for role_name in &assignment.roles {
                if let Some(grants) = effective_roles.get(role_name) {
                    for grant in grants {
                        all_grants.push(CompiledGrant {
                            permission: grant.permission.clone(),
                            resource_patterns: grant
                                .resource_patterns
                                .iter()
                                .map(|p| ResourcePattern::compile(p))
                                .collect::<Result<_, _>>()?,
                        });
                    }
                }
            }
            if is_glob_pattern(&assignment.subject) {
                wildcard_subject_grants
                    .push((SubjectPattern::compile(&assignment.subject)?, all_grants));
            } else {
                subject_grants
                    .entry(assignment.subject.clone())
                    .or_default()
                    .extend(all_grants);
            }
        }

        Ok(Self {
            subject_grants,
            wildcard_subject_grants,
        })
    }

    /// Load an engine directly from a YAML string.
    pub fn from_yaml(yaml: &str) -> Result<Self, String> {
        let policy = RbacPolicy::from_yaml(yaml).map_err(|e| format!("YAML parse error: {e}"))?;
        Self::new(policy)
    }
}

impl PolicyEngine for RbacEngine {
    fn check(&self, subject: &SubjectId, action: &str, resource: &ResourceId) -> PolicyResult {
        let subject = subject.as_str();
        let resource = resource.as_str();
        debug!(subject, action, resource, "rbac check");

        let exact_grants = self.subject_grants.get(subject).into_iter().flatten();
        let wildcard_grants = self
            .wildcard_subject_grants
            .iter()
            .filter(|(pattern, _)| pattern.matches(subject))
            .flat_map(|(_, grants)| grants);

        let mut matched_subject = false;
        for grant in exact_grants.chain(wildcard_grants) {
            matched_subject = true;
            if grant.permission == action {
                for pattern in &grant.resource_patterns {
                    if pattern.matches(resource) {
                        return PolicyResult::Allow;
                    }
                }
            }
        }

        if !matched_subject {
            return PolicyResult::Deny(format!("no role assignments for subject '{subject}'"));
        }

        PolicyResult::Deny(format!(
            "no rule grants '{subject}' permission '{action}' on '{resource}'"
        ))
    }
}

fn is_glob_pattern(value: &str) -> bool {
    value.contains(['*', '?', '['])
}

/// Recursively flatten a role's permissions by resolving inheritance.
fn flatten_role(role_name: &str, policy: &RbacPolicy) -> Vec<Grant> {
    let mut seen = HashSet::new();
    flatten_role_inner(role_name, policy, &mut seen)
}

fn flatten_role_inner(
    role_name: &str,
    policy: &RbacPolicy,
    seen: &mut HashSet<String>,
) -> Vec<Grant> {
    if !seen.insert(role_name.to_owned()) {
        return vec![]; // cycle guard (already validated, but be safe)
    }

    let role = match policy.roles.iter().find(|r| r.name == role_name) {
        Some(r) => r,
        None => return vec![],
    };

    let mut grants: Vec<Grant> = Vec::new();

    // Own permissions.
    for perm in &role.permissions {
        grants.push(Grant {
            permission: perm.clone(),
            resource_patterns: role.resources.clone(),
        });
    }

    // Inherited permissions (recursive).
    for parent_name in &role.inherits {
        let inherited = flatten_role_inner(parent_name, policy, seen);
        grants.extend(inherited);
    }

    grants
}

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

    const YAML: &str = r#"
roles:
  - name: analyst
    permissions: [read, read_sensitive]
    resources: ["reports/*", "metrics/*"]
  - name: engineer
    permissions: [read, write, execute]
    resources: ["code/*", "infra/*"]
  - name: admin
    inherits: [analyst, engineer]
    permissions: [delete, delegate]
    resources: ["*"]

assignments:
  - subject: "agent:data-pipeline"
    roles: [analyst]
  - subject: "agent:deploy-bot"
    roles: [engineer]
  - subject: "agent:superuser"
    roles: [admin]
"#;

    fn engine() -> RbacEngine {
        RbacEngine::from_yaml(YAML).expect("engine build should succeed")
    }

    fn check(e: &RbacEngine, subject: &str, action: &str, resource: &str) -> PolicyResult {
        e.check(
            &SubjectId::from(subject),
            action,
            &ResourceId::from(resource),
        )
    }

    #[test]
    fn analyst_can_read_reports() {
        let e = engine();
        assert_eq!(
            check(&e, "agent:data-pipeline", "read", "reports/q1"),
            PolicyResult::Allow
        );
    }

    #[test]
    fn analyst_cannot_write() {
        let e = engine();
        assert!(matches!(
            check(&e, "agent:data-pipeline", "write", "reports/q1"),
            PolicyResult::Deny(_)
        ));
    }

    #[test]
    fn engineer_can_write_code() {
        let e = engine();
        assert_eq!(
            check(&e, "agent:deploy-bot", "write", "code/main.rs"),
            PolicyResult::Allow
        );
    }

    #[test]
    fn engineer_cannot_access_reports() {
        let e = engine();
        assert!(matches!(
            check(&e, "agent:deploy-bot", "read", "reports/q1"),
            PolicyResult::Deny(_)
        ));
    }

    #[test]
    fn admin_inherits_analyst_and_engineer() {
        let e = engine();
        // Inherited from analyst:
        assert_eq!(
            check(&e, "agent:superuser", "read_sensitive", "reports/q1"),
            PolicyResult::Allow
        );
        // Inherited from engineer:
        assert_eq!(
            check(&e, "agent:superuser", "execute", "code/deploy.sh"),
            PolicyResult::Allow
        );
        // Own permissions:
        assert_eq!(
            check(&e, "agent:superuser", "delete", "anything"),
            PolicyResult::Allow
        );
    }

    #[test]
    fn invalid_resource_pattern_fails_policy_load() {
        let yaml = r#"
roles:
  - name: broken
    permissions: [read]
    resources: ["reports/[unclosed"]

assignments:
  - subject: "agent:x"
    roles: [broken]
"#;
        let result = RbacEngine::from_yaml(yaml);
        assert!(
            result.is_err(),
            "malformed glob must fail at load, not silently deny"
        );
    }

    #[test]
    fn unknown_subject_is_denied() {
        let e = engine();
        assert!(matches!(
            check(&e, "agent:ghost", "read", "reports/q1"),
            PolicyResult::Deny(_)
        ));
    }

    #[test]
    fn wildcard_subject_assignment_matches_globbed_agents() {
        let yaml = r#"
roles:
  - name: deployer
    permissions: [execute]
    resources: ["infra/*"]

assignments:
  - subject: "agent:deploy-*"
    roles: [deployer]
"#;
        let e = RbacEngine::from_yaml(yaml).expect("engine build should succeed");
        assert_eq!(
            check(&e, "agent:deploy-prod", "execute", "infra/restart"),
            PolicyResult::Allow
        );
        assert!(matches!(
            check(&e, "agent:build-prod", "execute", "infra/restart"),
            PolicyResult::Deny(_)
        ));
    }

    #[test]
    fn exact_subject_and_wildcard_subject_grants_are_combined() {
        let yaml = r#"
roles:
  - name: reader
    permissions: [read]
    resources: ["reports/*"]
  - name: writer
    permissions: [write]
    resources: ["reports/*"]

assignments:
  - subject: "agent:report-*"
    roles: [reader]
  - subject: "agent:report-prod"
    roles: [writer]
"#;
        let e = RbacEngine::from_yaml(yaml).expect("engine build should succeed");
        assert_eq!(
            check(&e, "agent:report-prod", "read", "reports/q1"),
            PolicyResult::Allow
        );
        assert_eq!(
            check(&e, "agent:report-prod", "write", "reports/q1"),
            PolicyResult::Allow
        );
    }

    #[test]
    fn invalid_subject_pattern_fails_policy_load() {
        let yaml = r#"
roles:
  - name: reader
    permissions: [read]
    resources: ["*"]

assignments:
  - subject: "agent:[broken"
    roles: [reader]
"#;
        let result = RbacEngine::from_yaml(yaml);
        assert!(
            result.is_err(),
            "malformed subject glob must fail at load, not silently deny"
        );
    }

    #[test]
    fn cyclic_role_inheritance_fails_engine_construction() {
        let yaml = r#"
roles:
  - name: a
    inherits: [b]
    permissions: [read]
    resources: ["*"]
  - name: b
    inherits: [a]
    permissions: [write]
    resources: ["*"]

assignments:
  - subject: "agent:x"
    roles: [a]
"#;

        assert!(RbacEngine::from_yaml(yaml).is_err());
    }
}