summaryrefslogtreecommitdiff
path: root/src/authorization/cedar_authorizer.rs
blob: 662aafebc27cc7b861bc4b3ad42750ba71b2cac0 (plain)
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
use super::authorizer::Authorizer;
use std::fs;
use std::str::FromStr;

#[derive(Debug)]
pub struct CedarAuthorizer {
    authorizer: cedar_policy::Authorizer,
    entities: cedar_policy::Entities,
    policies: cedar_policy::PolicySet,
}

impl CedarAuthorizer {
    pub fn new(
        policies: cedar_policy::PolicySet,
        entities: cedar_policy::Entities,
    ) -> CedarAuthorizer {
        CedarAuthorizer {
            policies,
            entities,
            authorizer: cedar_policy::Authorizer::new(),
        }
    }

    pub fn new_from(path: &std::path::Path, entities: cedar_policy::Entities) -> CedarAuthorizer {
        Self::new(
            Self::load_from(path).unwrap_or_else(|e| {
                tracing::error!(
                    path = ?path,
                    error = %e,
                    "Failed to load Cedar policies, using empty policy set"
                );
                cedar_policy::PolicySet::default()
            }),
            entities,
        )
    }

    fn load_from(
        path: &std::path::Path,
    ) -> Result<cedar_policy::PolicySet, Box<dyn std::error::Error>> {
        if !path.exists() {
            return Ok(cedar_policy::PolicySet::default());
        }

        if path.is_file() && path.extension().map_or(false, |ext| ext == "cedar") {
            let content = fs::read_to_string(&path)?;
            return Ok(cedar_policy::PolicySet::from_str(&content)?);
        }

        if !path.is_dir() {
            return Ok(cedar_policy::PolicySet::default());
        }

        let mut policies = cedar_policy::PolicySet::new();
        for entry in fs::read_dir(path)? {
            policies.merge(&Self::load_from(&entry?.path())?, true)?;
        }
        return Ok(policies);
    }

    fn map_from(
        &self,
        http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest,
    ) -> Result<cedar_policy::Request, Box<dyn std::error::Error>> {
        let principal = self.principal_from(&http_request)?;
        let permission = self.permission_from(&http_request)?;
        let resource = self.resource_from(&http_request)?;
        let context = self.context_from(http_request)?;

        Ok(cedar_policy::Request::new(
            principal, permission, resource, context, None,
        )?)
    }

    fn principal_from(
        &self,
        http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest,
    ) -> Result<cedar_policy::EntityUid, Box<dyn std::error::Error>> {
        let subject = http_request
            .headers
            .get("x-jwt-claim-sub")
            .map_or("", |v| v);

        Ok(cedar_policy::EntityUid::from_type_name_and_id(
            cedar_policy::EntityTypeName::from_str("User")?,
            cedar_policy::EntityId::from_str(subject)?,
        ))
    }

    fn permission_from(
        &self,
        http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest,
    ) -> Result<cedar_policy::EntityUid, Box<dyn std::error::Error>> {
        Ok(cedar_policy::EntityUid::from_type_name_and_id(
            cedar_policy::EntityTypeName::from_str("Action")?,
            cedar_policy::EntityId::from_str(&http_request.method)?,
        ))
    }

    fn resource_from(
        &self,
        http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest,
    ) -> Result<cedar_policy::EntityUid, Box<dyn std::error::Error>> {
        Ok(cedar_policy::EntityUid::from_type_name_and_id(
            cedar_policy::EntityTypeName::from_str("Resource")?,
            cedar_policy::EntityId::from_str(&http_request.path)?,
        ))
    }

    fn context_from(
        &self,
        http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest,
    ) -> Result<cedar_policy::Context, Box<dyn std::error::Error>> {
        let mut items = std::collections::HashMap::new();

        items.insert("host".to_string(), self.safe_string(&http_request.host));
        items.insert("method".to_string(), self.safe_string(&http_request.method));
        items.insert("path".to_string(), self.safe_string(&http_request.path));

        Ok(cedar_policy::Context::from_pairs(
            items.into_iter().collect::<Vec<_>>(),
        )?)
    }

    fn safe_string(&self, item: &str) -> cedar_policy::RestrictedExpression {
        cedar_policy::RestrictedExpression::new_string(item.to_string())
    }
}

impl Default for CedarAuthorizer {
    fn default() -> Self {
        Self::new_from(
            std::path::Path::new("/etc/authzd"),
            cedar_policy::Entities::empty(),
        )
    }
}

impl Authorizer for CedarAuthorizer {
    fn authorize(&self, request: envoy_types::ext_authz::v3::pb::CheckRequest) -> bool {
        let http_request = match request
            .attributes
            .as_ref()
            .and_then(|attr| attr.request.as_ref())
            .and_then(|req| req.http.as_ref())
        {
            Some(http) => http,
            None => return false,
        };

        match self.map_from(http_request.clone()) {
            Ok(cedar_request) => {
                let response =
                    self.authorizer
                        .is_authorized(&cedar_request, &self.policies, &self.entities);

                let decision = response.decision();

                tracing::info!(
                    method = %http_request.method,
                    host = %http_request.host,
                    path = %http_request.path,
                    scheme = %http_request.scheme,
                    protocol = %http_request.protocol,
                    decision = ?decision,
                    diagnostics = ?response.diagnostics(),
                    "Processing HTTP request"
                );

                matches!(decision, cedar_policy::Decision::Allow)
            }
            Err(e) => {
                tracing::error!(
                    error = %e,
                    path = %http_request.path,
                    "Failed to create Cedar request"
                );
                false
            }
        }
    }
}