themis-auth 0.3.1

Extensible authorization engine: permission catalog, RBAC, ABAC and ReBAC in one decision, with governance and auditing of changes.
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
use std::borrow::Cow;
use std::fmt;
#[cfg(feature = "audit")]
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use crate::attr::Attributes;
#[cfg(feature = "audit")]
use crate::audit::Auditor;
use crate::decision::Request;
use crate::engine::{Context, Engine};
use crate::grant::{Effect, Grant, SubjectMatcher};
use crate::rebac::TupleStore;
use crate::resource::Resource;
use crate::subject::{RoleAssignment, Subject};

/// Proposed change to the grant set or to a subject's roles.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[allow(clippy::large_enum_variant)]
pub enum Mutation {
    Add(Grant),
    Remove {
        id: String,
    },
    /// Gives `role` to `subject`. The grant set does not change; whoever stores the subject's roles
    /// writes [`Mutation::subject_after`].
    AssignRole {
        subject: Subject,
        role: RoleAssignment,
    },
    /// Takes `role` from `subject`, comparing role and scope.
    RevokeRole {
        subject: Subject,
        role: RoleAssignment,
    },
}

impl Mutation {
    /// Subject, assignment and `true` to assign (`false` to revoke), if the change is a
    /// role change.
    pub fn role_change(&self) -> Option<(&Subject, &RoleAssignment, bool)> {
        match self {
            Mutation::AssignRole { subject, role } => Some((subject, role, true)),
            Mutation::RevokeRole { subject, role } => Some((subject, role, false)),
            Mutation::Add(_) | Mutation::Remove { .. } => None,
        }
    }

    /// The subject of the role change with the role added or removed. `None` for a grant
    /// change.
    pub fn subject_after(&self) -> Option<Subject> {
        let (subject, role, assigned) = self.role_change()?;
        Some(with_role_change(subject, role, assigned))
    }
}

fn with_role_change(subject: &Subject, role: &RoleAssignment, assigned: bool) -> Subject {
    let mut next = subject.clone();
    if !assigned {
        next.roles.retain(|r| r != role);
    } else if !next.roles.contains(role) {
        next.roles.push(role.clone());
    }
    next
}

/// Same subject: subjects are identified by id, ignoring the kind, and only when the id exists.
/// The same id with another kind counts as the same subject, the safe side for self-management and lockout.
fn same_subject(a: &Subject, b: &Subject) -> bool {
    a.id.is_some() && a.id == b.id
}

fn role_label(role: &RoleAssignment) -> String {
    match &role.scope {
        Some(scope) => format!("{} em {scope}", role.role),
        None => role.role.clone(),
    }
}

/// What an invariant sees: who changes, what, and the set before and after. In a role
/// change, `before` and `after` are the same set; the effect shows up in
/// [`Proposal::subject_after`].
pub struct Proposal<'a> {
    pub actor: &'a Subject,
    pub mutation: &'a Mutation,
    pub before: &'a [Grant],
    pub after: &'a [Grant],
    pub tuples: Option<&'a dyn TupleStore>,
}

impl<'a> Proposal<'a> {
    /// The grant added, or the one removed. `None` for a role change.
    pub fn grant(&self) -> Option<&'a Grant> {
        match self.mutation {
            Mutation::Add(grant) => Some(grant),
            Mutation::Remove { id } => self.before.iter().find(|g| &g.id == id),
            Mutation::AssignRole { .. } | Mutation::RevokeRole { .. } => None,
        }
    }

    /// `subject` as it would be after the change: with the role applied, if it is the subject of
    /// the role change (same id); unchanged in the other cases.
    pub fn subject_after<'s>(&self, subject: &'s Subject) -> Cow<'s, Subject> {
        match self.mutation.role_change() {
            Some((target, role, assigned)) if same_subject(target, subject) => {
                Cow::Owned(with_role_change(subject, role, assigned))
            }
            _ => Cow::Borrowed(subject),
        }
    }

    pub fn before_context(&self) -> Context<'_> {
        self.context(&self.before)
    }

    pub fn after_context(&self) -> Context<'_> {
        self.context(&self.after)
    }

    fn context<'s>(&'s self, grants: &'s &'a [Grant]) -> Context<'s> {
        let ctx = Context::new(grants);
        match self.tuples {
            Some(tuples) => ctx.with_tuples(tuples),
            None => ctx,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Violation {
    pub invariant: String,
    pub message: String,
}

impl Violation {
    pub fn new(invariant: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            invariant: invariant.into(),
            message: message.into(),
        }
    }
}

impl fmt::Display for Violation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}] {}", self.invariant, self.message)
    }
}

/// Rule that every grant or role change must respect.
pub trait Invariant: Send + Sync {
    fn name(&self) -> &str;
    fn check(&self, engine: &Engine, proposal: &Proposal<'_>) -> Result<(), Violation>;
}

/// Applies grant and role changes only after they pass every invariant and, with the
/// `audit` feature, after recording the decision.
#[derive(Default)]
pub struct Governance {
    invariants: Vec<Box<dyn Invariant>>,
    #[cfg(feature = "audit")]
    auditor: Option<Arc<Auditor>>,
}

impl Governance {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with(mut self, invariant: impl Invariant + 'static) -> Self {
        self.invariants.push(Box::new(invariant));
        self
    }

    /// Records every change, applied or refused. If the record fails, the change is refused
    /// with the `audit` violation.
    #[cfg(feature = "audit")]
    pub fn audited(mut self, auditor: Arc<Auditor>) -> Self {
        self.auditor = Some(auditor);
        self
    }

    pub fn len(&self) -> usize {
        self.invariants.len()
    }

    pub fn is_empty(&self) -> bool {
        self.invariants.is_empty()
    }

    /// Returns the grant set after the change, or all the violations. Persistence
    /// is up to the application, which writes only on `Ok`. For a role change the set comes back unchanged
    /// and the subject to write comes from [`Mutation::subject_after`].
    pub fn apply(
        &self,
        engine: &Engine,
        actor: &Subject,
        current: &[Grant],
        mutation: &Mutation,
        tuples: Option<&dyn TupleStore>,
    ) -> Result<Vec<Grant>, Vec<Violation>> {
        self.apply_with(engine, actor, current, mutation, tuples, &Attributes::new())
    }

    /// Like [`Governance::apply`], with request metadata (ip, request id, reason) that goes
    /// to the audit from the `detailed` level upward.
    pub fn apply_with(
        &self,
        engine: &Engine,
        actor: &Subject,
        current: &[Grant],
        mutation: &Mutation,
        tuples: Option<&dyn TupleStore>,
        meta: &Attributes,
    ) -> Result<Vec<Grant>, Vec<Violation>> {
        let result = self.evaluate(engine, actor, current, mutation, tuples);
        #[cfg(feature = "audit")]
        if let Some(auditor) = &self.auditor
            && let Err(error) = auditor.grant_mutation(actor, mutation, current, &result, meta)
        {
            return Err(vec![Violation::new("audit", error.to_string())]);
        }
        #[cfg(not(feature = "audit"))]
        let _ = meta;
        result
    }

    fn evaluate(
        &self,
        engine: &Engine,
        actor: &Subject,
        current: &[Grant],
        mutation: &Mutation,
        tuples: Option<&dyn TupleStore>,
    ) -> Result<Vec<Grant>, Vec<Violation>> {
        let after: Cow<'_, [Grant]> = match mutation {
            Mutation::Add(grant) => {
                if current.iter().any(|g| g.id == grant.id) {
                    return Err(vec![Violation::new(
                        "mutation",
                        format!("grant {} já existe", grant.id),
                    )]);
                }
                let mut next = current.to_vec();
                next.push(grant.clone());
                Cow::Owned(next)
            }
            Mutation::Remove { id } => {
                if !current.iter().any(|g| &g.id == id) {
                    return Err(vec![Violation::new("mutation", format!("grant {id} não existe"))]);
                }
                Cow::Owned(current.iter().filter(|g| &g.id != id).cloned().collect())
            }
            Mutation::AssignRole { subject, role } => {
                check_role_mutation(subject, role, true)?;
                Cow::Borrowed(current)
            }
            Mutation::RevokeRole { subject, role } => {
                check_role_mutation(subject, role, false)?;
                Cow::Borrowed(current)
            }
        };
        let proposal = Proposal {
            actor,
            mutation,
            before: current,
            after: &after,
            tuples,
        };
        let violations: Vec<Violation> = self
            .invariants
            .iter()
            .filter_map(|inv| inv.check(engine, &proposal).err())
            .collect();
        if violations.is_empty() {
            Ok(after.into_owned())
        } else {
            Err(violations)
        }
    }
}

fn check_role_mutation(subject: &Subject, role: &RoleAssignment, assigned: bool) -> Result<(), Vec<Violation>> {
    let Some(id) = subject.id.as_deref() else {
        return Err(vec![Violation::new(
            "mutation",
            "papel só se atribui a sujeito identificado",
        )]);
    };
    let has = subject.roles.contains(role);
    let message = match (assigned, has) {
        (true, true) => format!("{id} já tem o papel {}", role_label(role)),
        (false, false) => format!("{id} não tem o papel {}", role_label(role)),
        _ => return Ok(()),
    };
    Err(vec![Violation::new("mutation", message)])
}

/// The added grant exists in the catalog and targets a kind the permission accepts. The assigned
/// role is known (it is in the engine's [`RoleGraph`](crate::RoleGraph) or in some current grant) and
/// its scope, if any, uses a kind from the catalog. Revoking always passes: removing an
/// unknown role is cleanup.
pub struct CatalogConformance;

impl CatalogConformance {
    fn check_role(&self, engine: &Engine, current: &[Grant], role: &RoleAssignment) -> Result<(), Violation> {
        let known = engine.roles().contains(&role.role)
            || current
                .iter()
                .any(|g| matches!(&g.subject, SubjectMatcher::Role { id } if *id == role.role));
        if !known {
            return Err(Violation::new(
                self.name(),
                format!("papel desconhecido: {}", role.role),
            ));
        }
        match &role.scope {
            Some(scope) if !engine.catalog().is_target_kind(&scope.kind) => Err(Violation::new(
                self.name(),
                format!("escopo {scope} usa tipo fora do catálogo"),
            )),
            _ => Ok(()),
        }
    }
}

impl Invariant for CatalogConformance {
    fn name(&self) -> &str {
        "catalog_conformance"
    }

    fn check(&self, engine: &Engine, proposal: &Proposal<'_>) -> Result<(), Violation> {
        match proposal.mutation {
            Mutation::Add(grant) => engine
                .validate_grant(grant)
                .map_err(|e| Violation::new(self.name(), e.to_string())),
            Mutation::AssignRole { role, .. } => self.check_role(engine, proposal.before, role),
            Mutation::Remove { .. } | Mutation::RevokeRole { .. } => Ok(()),
        }
    }
}

/// Nobody changes a grant that applies to themselves: neither the user directly, nor a role they
/// hold (direct or inherited). Grants by principal and by relation are left out. Nobody assigns
/// or revokes a role of their own, either.
pub struct NoSelfManagement;

impl Invariant for NoSelfManagement {
    fn name(&self) -> &str {
        "no_self_management"
    }

    fn check(&self, engine: &Engine, proposal: &Proposal<'_>) -> Result<(), Violation> {
        let actor = proposal.actor;
        if let Some((subject, _, _)) = proposal.mutation.role_change() {
            return if same_subject(subject, actor) {
                Err(Violation::new(
                    self.name(),
                    "não é permitido gerenciar os próprios papéis",
                ))
            } else {
                Ok(())
            };
        }
        let Some(grant) = proposal.grant() else {
            return Ok(());
        };
        let affects_actor = match &grant.subject {
            SubjectMatcher::User { id } => actor.id.as_deref() == Some(id.as_str()),
            SubjectMatcher::Role { id } => engine
                .roles()
                .expand(actor.roles.iter().map(|r| r.role.as_str()))
                .contains(id),
            _ => false,
        };
        if affects_actor {
            Err(Violation::new(
                self.name(),
                "não é permitido gerenciar as próprias permissões",
            ))
        } else {
            Ok(())
        }
    }
}

/// The actor must hold `key` on `resource` before the change.
pub struct RequirePermission {
    key: String,
    resource: Resource,
}

impl RequirePermission {
    pub fn new(key: impl Into<String>, resource: Resource) -> Self {
        Self {
            key: key.into(),
            resource,
        }
    }
}

impl Invariant for RequirePermission {
    fn name(&self) -> &str {
        "require_permission"
    }

    fn check(&self, engine: &Engine, proposal: &Proposal<'_>) -> Result<(), Violation> {
        let request = Request::new(proposal.actor, &self.key, &self.resource);
        if engine.check(&proposal.before_context(), &request) {
            Ok(())
        } else {
            Err(Violation::new(self.name(), format!("falta a permissão {}", self.key)))
        }
    }
}

/// After the change, each critical permission still has at least one member able to
/// exercise it on `resource`. Prevents locking a scope out of its own management. Each member
/// is evaluated as they would be after the change ([`Proposal::subject_after`]), so revoking the
/// role of the last one who exercises the permission is also refused.
pub struct NoLockout {
    critical: Vec<String>,
    members: Vec<Subject>,
    resource: Resource,
}

impl NoLockout {
    pub fn new<I, S>(critical: I, members: Vec<Subject>, resource: Resource) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            critical: critical.into_iter().map(Into::into).collect(),
            members,
            resource,
        }
    }
}

impl Invariant for NoLockout {
    fn name(&self) -> &str {
        "no_lockout"
    }

    fn check(&self, engine: &Engine, proposal: &Proposal<'_>) -> Result<(), Violation> {
        let ctx = proposal.after_context();
        for key in &self.critical {
            let covered = self.members.iter().any(|m| {
                let member = proposal.subject_after(m);
                engine.check(&ctx, &Request::new(&member, key, &self.resource))
            });
            if !covered {
                return Err(Violation::new(
                    self.name(),
                    format!("a mudança deixaria ninguém com a permissão {key}"),
                ));
            }
        }
        Ok(())
    }
}

/// `subject` never receives `allow` on `permissions` or on any permission that grants them.
///
/// On a role assignment, it only applies when `subject` is [`SubjectMatcher::User`] with the
/// subject's id: it refuses the role if any current `allow` grant for them, or for a role they inherit,
/// grants a forbidden permission, regardless of scope. The other matchers (principal, `any`,
/// role, relation) do not apply to role assignment.
pub struct Forbid {
    subject: SubjectMatcher,
    permissions: Vec<String>,
}

impl Forbid {
    pub fn new<I, S>(subject: SubjectMatcher, permissions: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        Self {
            subject,
            permissions: permissions.into_iter().map(Into::into).collect(),
        }
    }
}

impl Invariant for Forbid {
    fn name(&self) -> &str {
        "forbid"
    }

    fn check(&self, engine: &Engine, proposal: &Proposal<'_>) -> Result<(), Violation> {
        match proposal.mutation {
            Mutation::Add(grant) => self.check_grant(engine, grant),
            Mutation::AssignRole { subject, role } => self.check_role(engine, proposal.before, subject, role),
            Mutation::Remove { .. } | Mutation::RevokeRole { .. } => Ok(()),
        }
    }
}

impl Forbid {
    fn forbidden_by<'s>(&'s self, engine: &Engine, permission: &str) -> Option<&'s String> {
        self.permissions
            .iter()
            .find(|p| engine.catalog().implies(permission, p))
    }

    fn check_grant(&self, engine: &Engine, grant: &Grant) -> Result<(), Violation> {
        if grant.effect != Effect::Allow || grant.subject != self.subject {
            return Ok(());
        }
        match self.forbidden_by(engine, &grant.permission) {
            Some(forbidden) => Err(Violation::new(
                self.name(),
                format!(
                    "{} concederia {forbidden}, proibido para este sujeito",
                    grant.permission
                ),
            )),
            None => Ok(()),
        }
    }

    fn check_role(
        &self,
        engine: &Engine,
        current: &[Grant],
        subject: &Subject,
        role: &RoleAssignment,
    ) -> Result<(), Violation> {
        let SubjectMatcher::User { id } = &self.subject else {
            return Ok(());
        };
        if subject.id.as_deref() != Some(id.as_str()) {
            return Ok(());
        }
        let roles = engine.roles().expand([role.role.as_str()]);
        for grant in current.iter().filter(|g| g.effect == Effect::Allow) {
            let SubjectMatcher::Role { id: granted } = &grant.subject else {
                continue;
            };
            if !roles.contains(granted) {
                continue;
            }
            if let Some(forbidden) = self.forbidden_by(engine, &grant.permission) {
                return Err(Violation::new(
                    self.name(),
                    format!(
                        "o papel {} concederia {forbidden} pelo grant {} ({}), proibido para este sujeito",
                        role.role, grant.id, grant.permission
                    ),
                ));
            }
        }
        Ok(())
    }
}