summaryrefslogtreecommitdiff
path: root/src/authorization/cedar_authorizer.rs
blob: 96a406d861d5375cedb5664795691eb02ffdcf3a (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
use super::authorizer::Authorizer;
use cedar_policy::{
    Authorizer as CedarAuth, Context, Entities, EntityId, EntityTypeName, EntityUid, PolicySet,
    Request as CedarRequest,
};
use envoy_types::ext_authz::v3::pb::CheckRequest;
use std::fs;
use std::str::FromStr;

#[derive(Debug)]
pub struct CedarAuthorizer {
    policies: PolicySet,
    authorizer: CedarAuth,
}

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

    pub fn new_from(path: &std::path::Path) -> CedarAuthorizer {
        Self::new(Self::load_from(path).unwrap_or_else(|_| PolicySet::default()))
    }

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

        let mut policies = PolicySet::new();

        for entry in fs::read_dir(path)? {
            let file_path = entry?.path();

            if let Some(extension) = file_path.extension() {
                if extension == "cedar" {
                    let content = fs::read_to_string(&file_path)?;
                    let file_policies = PolicySet::from_str(&content)?;

                    for policy in file_policies.policies() {
                        policies.add(policy.clone())?;
                    }
                }
            }
        }

        Ok(policies)
    }
}

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

impl Authorizer for CedarAuthorizer {
    fn authorize(&self, request: 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,
        };

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

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

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

impl CedarAuthorizer {
    fn map_from(
        &self,
        http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest,
    ) -> Result<CedarRequest, 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)?;

        CedarRequest::new(principal, permission, resource, context, None)
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)
    }

    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>> {
        Ok(EntityUid::from_type_name_and_id(
            EntityTypeName::from_str("User")?,
            EntityId::from_str("client")?,
        ))
    }

    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(EntityUid::from_type_name_and_id(
            EntityTypeName::from_str("Action")?,
            EntityId::from_str("check")?,
        ))
    }

    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(EntityUid::from_type_name_and_id(
            EntityTypeName::from_str("Resource")?,
            EntityId::from_str("resource")?,
        ))
    }

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

        items.insert("bearer_token".to_string(), self.token_from(&http_request));
        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));

        Context::from_pairs(items.into_iter().collect::<Vec<_>>())
    }

    fn token_from(
        &self,
        http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest,
    ) -> cedar_policy::RestrictedExpression {
        let bearer_token = &http_request
            .headers
            .get("authorization")
            .and_then(|auth| auth.strip_prefix("Bearer "))
            .unwrap_or("");

        self.safe_string(bearer_token)
    }

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