treetop-core 0.0.4

Core library for Treetop, a Cedar policy engine implementation.
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
use std::collections::HashMap;
use std::net::IpAddr;
use std::str::FromStr;

use itertools::Itertools;
use strum_macros::{Display, EnumDiscriminants, EnumString};

use cedar_policy::{ActionConstraint, Context, EntityUid, Policy, RestrictedExpression};

use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};
use serde_json::Value;

use crate::error::PolicyError;
use crate::host_patterns::HOST_PATTERNS;
use crate::traits::CedarAtom;

/// The API-level request, with strongly-typed principal, action, groups, and resource.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
    pub principal: User,
    pub action: Action,
    pub groups: Groups,
    pub resource: Resource,
}

/// A permit policy that permitted a specific action on a resource.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash, Default)]
pub struct PermitPolicy {
    pub literal: String,
    pub json: Value,
}

/// Allow or deny decision.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum Decision {
    Allow { policy: PermitPolicy },
    Deny,
}

impl std::fmt::Display for Decision {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Decision::Allow { policy } => write!(f, "Allow({})", policy.literal),
            Decision::Deny => write!(f, "Deny"),
        }
    }
}

pub trait FromDecisionWithPolicy {
    fn from_decision_with_policy(response: cedar_policy::Decision, policy: PermitPolicy) -> Self;
}

impl FromDecisionWithPolicy for Decision {
    fn from_decision_with_policy(decision: cedar_policy::Decision, policy: PermitPolicy) -> Self {
        match decision {
            cedar_policy::Decision::Allow => Decision::Allow { policy },
            cedar_policy::Decision::Deny => Decision::Deny,
        }
    }
}

/// A resource in our domain.
#[derive(Debug, Clone, Serialize, Deserialize, EnumDiscriminants)]
#[strum_discriminants(name(ResourceKind), derive(EnumString, Display))]
#[strum(serialize_all = "PascalCase")]
pub enum Resource {
    Photo { id: String },
    Host { name: String, ip: IpAddr },
    Generic { kind: String, id: String },
}

impl std::fmt::Display for Resource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Turn &self into its discriminant:
        let kind = ResourceKind::from(self).to_string();
        // Pick the right “id” field for each variant:
        let id = match self {
            Resource::Photo { id } => id,
            Resource::Host { name, .. } => name,
            Resource::Generic { id, .. } => id,
        };
        write!(f, "{}::\"{}\"", kind, id)
    }
}

impl CedarAtom for Resource {
    fn cedar_entity_uid(&self) -> Result<EntityUid, PolicyError> {
        let literal = match self {
            Resource::Generic { kind, id } => {
                format!("{kind}::\"{id}\"")
            }
            _ => {
                let kind = ResourceKind::from(self).to_string();
                let id = self.cedar_id();
                format!("{kind}::\"{id}\"")
            }
        };

        EntityUid::from_str(&literal).map_err(|e| PolicyError::ParseError(e.to_string()))
    }

    fn cedar_attr(&self) -> Result<HashMap<String, RestrictedExpression>, PolicyError> {
        let mut attrs = std::collections::HashMap::new();
        match self {
            Resource::Photo { id } => {
                attrs.insert(
                    "id".to_string(),
                    RestrictedExpression::new_string(id.clone()),
                );
            }
            Resource::Host { name, ip } => {
                attrs.insert(
                    "name".to_string(),
                    RestrictedExpression::new_string(name.clone()),
                );
                attrs.insert(
                    "ip".to_string(),
                    RestrictedExpression::new_ip(ip.to_string()),
                );

                let reg = HOST_PATTERNS.read().unwrap();
                let mut matched = Vec::new();
                for (label, re) in reg.iter() {
                    if re.is_match(name) {
                        matched.push(RestrictedExpression::new_string(label.clone()));
                    }
                }
                attrs.insert(
                    "nameLabels".to_string(),
                    RestrictedExpression::new_set(matched),
                );
            }
            Resource::Generic { kind, id } => {
                attrs.insert(
                    "kind".into(),
                    RestrictedExpression::new_string(kind.clone()),
                );
                attrs.insert("id".into(), RestrictedExpression::new_string(id.clone()));
            }
        }
        Ok(attrs)
    }

    fn cedar_ctx(&self) -> Result<Context, PolicyError> {
        match self {
            Resource::Host { name, ip } => {
                let result = Context::from_pairs(vec![
                    (
                        "name".to_string(),
                        RestrictedExpression::new_string(name.clone()),
                    ),
                    (
                        "ip".to_string(),
                        RestrictedExpression::new_ip(ip.to_string()),
                    ),
                ])?;
                Ok(result)
            }
            Resource::Photo { .. } => Ok(Context::empty()),
            Resource::Generic { kind, id } => {
                let result = Context::from_pairs(vec![
                    (
                        "kind".into(),
                        RestrictedExpression::new_string(kind.clone()),
                    ),
                    ("id".into(), RestrictedExpression::new_string(id.clone())),
                ])?;
                Ok(result)
            }
        }
    }

    fn cedar_type() -> &'static str {
        "Resource"
    }

    fn cedar_id(&self) -> &str {
        match self {
            Resource::Photo { id } => id,
            Resource::Host { name, .. } => name,
            Resource::Generic { id, .. } => id,
        }
    }
}

/// A user principal, possibly scoped (e.g. User::Application::"alice").
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
    pub scope: Option<String>,
    pub id: String,
}

impl std::fmt::Display for User {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(scope) = &self.scope {
            write!(f, "User::{}::\"{}\"", scope, self.id)
        } else {
            write!(f, "User::\"{}\"", self.id)
        }
    }
}

impl User {
    /// Create a new user with an optional scope.
    pub fn new<T: Into<String>>(id: T, scope: Option<Vec<String>>) -> Self {
        User {
            scope: scope.map(|s| s.join("::")),
            id: id.into(),
        }
    }

    /// Create a new user without a scope.
    pub fn without_scope<T: Into<String>>(id: T) -> Self {
        User::new(id, None)
    }
}

impl CedarAtom for User {
    fn cedar_type() -> &'static str {
        "User"
    }

    fn cedar_id(&self) -> &str {
        &self.id
    }
}

impl<T> From<T> for User
where
    T: Into<String>,
{
    fn from(v: T) -> Self {
        User {
            scope: None,
            id: v.into(),
        }
    }
}

/// An action, possibly scoped (e.g. Action::Infra::"delete_vm").
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Action {
    pub scope: Option<String>,
    pub id: String,
}

impl std::fmt::Display for Action {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(scope) = &self.scope {
            write!(f, "Action::{}::\"{}\"", scope, self.id)
        } else {
            write!(f, "Action::\"{}\"", self.id)
        }
    }
}

impl Action {
    /// Create a new action with an optional scope.
    pub fn new<T: Into<String>>(id: T, scope: Option<Vec<String>>) -> Self {
        Action {
            scope: scope.map(|s| s.join("::")),
            id: id.into(),
        }
    }

    /// Create a new action without a scope.
    pub fn without_scope<T: Into<String>>(id: T) -> Self {
        Action::new(id, None)
    }
}

impl CedarAtom for Action {
    fn cedar_type() -> &'static str {
        "Action"
    }

    fn cedar_id(&self) -> &str {
        &self.id
    }
}

impl<T> From<T> for Action
where
    T: Into<String>,
{
    fn from(v: T) -> Self {
        Action {
            scope: None,
            id: v.into(),
        }
    }
}

/// A group identifier (e.g. Group::"devs").
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Group(pub String);

impl CedarAtom for Group {
    fn cedar_type() -> &'static str {
        "Group"
    }

    fn cedar_id(&self) -> &str {
        &self.0
    }
}
/// A collection of Group entries.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Groups(pub Vec<Group>);

impl std::fmt::Display for Groups {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let group_names: Vec<String> = self.0.iter().map(|g| g.0.clone()).collect();
        write!(f, "[{}]", group_names.join(", "))
    }
}

/// A set of permissions for a given user.
#[derive(Debug, Clone)]
pub struct UserPolicies {
    user: String,
    policies: Vec<Policy>,
    actions: Vec<EntityUid>,
}
impl UserPolicies {
    pub fn new(user: &str, policies: &[Policy]) -> Self {
        let actions: Vec<EntityUid> = policies
            .iter()
            .flat_map(|p| match p.action_constraint() {
                // exactly one action
                ActionConstraint::Eq(act) => vec![act.clone()],
                // multiple actions
                ActionConstraint::In(acts) => acts.clone(),
                // “any” means unconstrained — skip or handle however you like
                ActionConstraint::Any => Vec::new(),
            })
            .collect();

        UserPolicies {
            user: user.to_string(),
            policies: policies.to_vec(),
            actions,
        }
    }

    pub fn user(&self) -> &str {
        &self.user
    }

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

    pub fn actions(&self) -> Vec<EntityUid> {
        self.actions.clone()
    }

    pub fn policies(&self) -> &[Policy] {
        &self.policies
    }

    /// Get the actions as a sorted list of strings.
    pub fn actions_by_name(&self) -> Vec<String> {
        self.actions
            .iter()
            .map(|a| a.to_string())
            .sorted()
            .collect()
    }

    /// Get the policies as a sorted list of strings.
    pub fn policies_by_name(&self) -> Vec<String> {
        self.policies
            .iter()
            .map(|p| p.to_string())
            .sorted()
            .collect()
    }
}

impl Serialize for UserPolicies {
    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let policies = self.policies();

        let mut policies_as_json: Vec<Value> = Vec::new();

        for policy in policies {
            let json = match policy.to_json() {
                Ok(json) => json,
                Err(e) => return Err(serde::ser::Error::custom(e)),
            };
            policies_as_json.push(json);
        }

        let mut s = ser.serialize_struct("UserPolicies", 2)?;
        s.serialize_field("user", &self.user)?;
        s.serialize_field("policies", &policies_as_json)?;
        s.end()
    }
}