Repository navigation
Expand file tree
/
Copy pathauthority.rs
More file actions
100 lines (92 loc) · 2.5 KB
/
Copy pathauthority.rs
File metadata and controls
100 lines (92 loc) · 2.5 KB
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
//! Explicit request authority. Effects describe requirements and never mint grants.
use crate::error::{Error, Result};
use std::collections::{BTreeMap, BTreeSet};
pub(crate) type Restrictions = BTreeMap<String, BTreeSet<String>>;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum Effect {
Read(String),
Write(String),
Host(String),
}
pub(crate) type Effects = BTreeSet<Effect>;
#[derive(Clone, Debug, Default)]
pub(crate) enum Principal {
#[default]
Anonymous,
User {
id: String,
roles: BTreeSet<String>,
},
}
impl Principal {
pub fn id(&self) -> Option<&str> {
match self {
Self::Anonymous => None,
Self::User { id, .. } => Some(id),
}
}
pub fn has_role(&self, role: &str) -> bool {
match self {
Self::Anonymous => false,
Self::User { roles, .. } => roles.contains(role),
}
}
}
/// A borrowed scope cannot outlive its principal or its host-provided grants.
/// It is not a Diamond value and has no serialization or cloning implementation.
#[derive(Debug)]
pub(crate) struct Scope<'a> {
principal: &'a Principal,
grants: &'a Effects,
restrictions: Option<&'a Restrictions>,
unscoped: bool,
}
impl<'a> Scope<'a> {
pub fn new(principal: &'a Principal, grants: &'a Effects) -> Self {
Self {
principal,
grants,
restrictions: None,
unscoped: true,
}
}
pub fn restricted(
principal: &'a Principal,
grants: &'a Effects,
restrictions: &'a Restrictions,
unscoped: bool,
) -> Self {
Self {
principal,
grants,
restrictions: Some(restrictions),
unscoped,
}
}
pub fn restrictions(&self) -> Option<&Restrictions> {
self.restrictions
}
pub fn allows_unscoped(&self) -> bool {
self.unscoped
}
pub fn principal(&self) -> &Principal {
self.principal
}
pub fn require(&self, effect: &Effect) -> Result<()> {
if self.grants.contains(effect) {
Ok(())
} else {
Err(Error::Denied)
}
}
}
pub(crate) fn random_hex() -> Result<String> {
use std::fmt::Write;
let mut bytes = [0_u8; 32];
getrandom::fill(&mut bytes).map_err(|_| Error::Random)?;
let mut output = String::with_capacity(64);
for byte in bytes {
write!(output, "{byte:02x}").map_err(|_| Error::Random)?;
}
Ok(output)
}