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
//! Communicate with the Polar virtual machine: load rules, make queries, etc/

use polar_core::terms::{Call, Symbol, Term, Value};

use std::fs::File;
use std::io::Read;
use std::sync::{Arc, Mutex};

use crate::host::Host;
use crate::query::Query;
use crate::ToPolar;

/// Oso is the main struct you interact with. It is an instance of the Oso authorization library
/// and contains the polar language knowledge base and query engine.
#[derive(Clone)]
pub struct Oso {
    inner: Arc<polar_core::polar::Polar>,
    host: Arc<Mutex<Host>>,
}

impl Default for Oso {
    fn default() -> Self {
        Self::new()
    }
}

impl Oso {
    /// Create a new instance of Oso. Each instance is separate and can have different rules and classes loaded into it.
    pub fn new() -> Self {
        let inner = Arc::new(polar_core::polar::Polar::new());
        let host = Host::new(inner.clone());

        let mut oso = Self {
            host: Arc::new(Mutex::new(host)),
            inner,
        };

        for class in crate::builtins::classes() {
            oso.register_class(class)
                .expect("failed to register builtin class");
        }
        oso
    }

    /// High level interface for authorization decisions. Makes an allow query with the given actor, action and resource and returns true or false.
    pub fn is_allowed<Actor, Action, Resource>(
        &mut self,
        actor: Actor,
        action: Action,
        resource: Resource,
    ) -> crate::Result<bool>
    where
        Actor: ToPolar,
        Action: ToPolar,
        Resource: ToPolar,
    {
        let args: Vec<&dyn ToPolar> = vec![&actor, &action, &resource];
        let mut query = self.query_rule("allow", args).unwrap();
        match query.next() {
            Some(Ok(_)) => Ok(true),
            Some(Err(e)) => Err(e),
            None => Ok(false),
        }
    }

    /// Clear out all files and rules that have been loaded.
    pub fn clear(&mut self) {
        *self = Self::new();
    }

    fn check_inline_queries(&mut self) -> crate::Result<()> {
        while let Some(q) = self.inner.next_inline_query(false) {
            let query = Query::new(q, self.host.clone());
            match query.collect::<crate::Result<Vec<_>>>() {
                Ok(v) if !v.is_empty() => continue,
                Ok(_) => return lazy_error!("inline query result was false"),
                Err(e) => return lazy_error!("error in inline query: {}", e),
            }
        }
        check_messages!(self.inner);
        Ok(())
    }

    /// Load a file containing polar rules. All polar files must end in `.polar`
    pub fn load_file<P: AsRef<std::path::Path>>(&mut self, file: P) -> crate::Result<()> {
        let file = file.as_ref();
        if !file.extension().map(|ext| ext == "polar").unwrap_or(false) {
            return Err(crate::OsoError::IncorrectFileType {
                filename: file.to_string_lossy().into_owned(),
            });
        }
        let mut f = File::open(&file)?;
        let mut policy = String::new();
        f.read_to_string(&mut policy)?;
        self.inner
            .load(&policy, Some(file.to_string_lossy().into_owned()))?;
        self.check_inline_queries()
    }

    /// Load a string of polar source directly.
    /// # Examples
    /// ```ignore
    /// oso.load_str("allow(a, b, c) if true;");
    /// ```
    pub fn load_str(&mut self, s: &str) -> crate::Result<()> {
        self.inner.load(s, None)?;
        self.check_inline_queries()
    }

    /// Query the knowledge base. This can be an allow query or any other polar expression.
    /// # Examples
    /// ```ignore
    /// oso.query("x = 1 or x = 2");
    /// ```
    pub fn query(&mut self, s: &str) -> crate::Result<Query> {
        let query = self.inner.new_query(s, false)?;
        check_messages!(self.inner);
        let query = Query::new(query, self.host.clone());
        Ok(query)
    }

    /// Query the knowledge base but with a rule name and argument list.
    /// This allows you to pass in rust values.
    /// # Examples
    /// ```ignore
    /// oso.query_rule("is_admin", vec![User{name: "steve"}]);
    /// ```
    pub fn query_rule<'a>(
        &mut self,
        name: &str,
        args: impl IntoIterator<Item = &'a dyn crate::host::ToPolar>,
    ) -> crate::Result<Query> {
        let args = args
            .into_iter()
            .map(|arg| arg.to_polar(&mut self.host.lock().unwrap()))
            .collect();
        let query_value = Value::Call(Call {
            name: Symbol(name.to_string()),
            args,
            kwargs: None,
        });
        let query_term = Term::new_from_ffi(query_value);
        let query = self.inner.new_query_from_term(query_term, false);
        check_messages!(self.inner);
        let query = Query::new(query, self.host.clone());
        Ok(query)
    }

    /// Register a rust type as a Polar class.
    /// See [`oso::Class`] docs.
    pub fn register_class(&mut self, class: crate::host::Class) -> crate::Result<()> {
        let name = class.name.clone();
        let name = Symbol(name);
        let class_name = self.host.lock().unwrap().cache_class(class.clone(), name)?;
        self.register_constant(&class_name, &class)
    }

    /// Register a rust type as a Polar constant.
    /// See [`oso::Class`] docs.
    pub fn register_constant<V: crate::host::ToPolar>(
        &mut self,
        name: &str,
        value: &V,
    ) -> crate::Result<()> {
        let mut host = self.host.lock().unwrap();
        self.inner
            .register_constant(Symbol(name.to_string()), value.to_polar(&mut host));
        Ok(())
    }
}