Skip to main content

unitycatalog_server/policy/
constant.rs

1use unitycatalog_common::models::ResourceIdent;
2
3use super::{Decision, Permission, Policy};
4use crate::Result;
5
6/// Policy that always returns a constant decision.
7///
8/// This policy is mainly useful for testing and development, or servers that do not require
9/// authorization checks - e.g. when deployed in a trusted environment.
10#[derive(Debug, Clone, Copy)]
11pub struct ConstantPolicy {
12    decision: Decision,
13}
14
15impl Default for ConstantPolicy {
16    fn default() -> Self {
17        Self {
18            decision: Decision::Allow,
19        }
20    }
21}
22
23impl ConstantPolicy {
24    /// Create a new instance of [`ConstantPolicy`].
25    pub fn new(decision: Decision) -> Self {
26        Self { decision }
27    }
28}
29
30#[async_trait::async_trait]
31impl<Cx: Send + Sync + 'static> Policy<Cx> for ConstantPolicy {
32    async fn authorize(&self, _: &ResourceIdent, _: &Permission, _: &Cx) -> Result<Decision> {
33        Ok(self.decision)
34    }
35}
36
37#[cfg(test)]
38mod test {
39    use super::*;
40    use unitycatalog_common::models::resource_name;
41
42    #[test]
43    fn assert_send_sync() {
44        fn assert_send_sync<T: Send + Sync>() {}
45        assert_send_sync::<ConstantPolicy>();
46    }
47
48    #[tokio::test]
49    async fn allow_by_default() {
50        let policy = ConstantPolicy::default();
51
52        let resource = ResourceIdent::share(resource_name!("test_share"));
53        let permission = Permission::Read;
54
55        let decision = policy.authorize(&resource, &permission, &()).await.unwrap();
56        assert_eq!(decision, Decision::Allow);
57    }
58
59    #[tokio::test]
60    async fn allow() {
61        let policy = ConstantPolicy::new(Decision::Allow);
62
63        let resource = ResourceIdent::share(resource_name!("test_share"));
64        let permission = Permission::Read;
65
66        let decision = policy.authorize(&resource, &permission, &()).await.unwrap();
67        assert_eq!(decision, Decision::Allow);
68    }
69
70    #[tokio::test]
71    async fn deny() {
72        let policy = ConstantPolicy::new(Decision::Deny);
73
74        let resource = ResourceIdent::share(resource_name!("test_share"));
75        let permission = Permission::Read;
76
77        let decision = policy.authorize(&resource, &permission, &()).await.unwrap();
78        assert_eq!(decision, Decision::Deny);
79    }
80}