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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
use serde::{Deserialize, Serialize};
use std::{borrow::Cow, collections::HashMap};

mod api;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Api Error: {0}")]
    Api(#[from] reqwest::Error),
    #[error("Server Error: {0}")]
    Server(String),
    #[error("Input error: {0}")]
    Input(String),
}

#[derive(Clone, Debug)]
pub struct Oso {
    client: api::Client,
}

type StringRef<'a> = Cow<'a, str>;

/// Representation of values used in Oso Cloud
///
/// All values are represented as a `type` and an `id`, both of which are strings
#[derive(Clone, Default, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Value<'a> {
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub type_: Option<StringRef<'a>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<StringRef<'a>>,
}

impl<'a> Value<'a> {
    /// Construct a new Value
    pub fn new(type_: impl Into<StringRef<'a>>, id: impl Into<StringRef<'a>>) -> Self {
        Self {
            type_: Some(type_.into()),
            id: Some(id.into()),
        }
    }

    /// Construct a variable Value that can be bound to any value
    pub fn any() -> Self {
        Self { type_: None, id: None }
    }

    /// Construct a variable Value that can be bound to any value of a given type
    pub fn any_of_type(type_: impl Into<StringRef<'a>>) -> Self {
        Self {
            type_: Some(type_.into()),
            id: None,
        }
    }
}

impl From<bool> for Value<'static> {
    fn from(b: bool) -> Self {
        Self::new("Boolean", b.to_string())
    }
}

impl From<i64> for Value<'static> {
    fn from(i: i64) -> Self {
        Self::new("Integer", i.to_string())
    }
}

impl From<f64> for Value<'static> {
    fn from(f: f64) -> Self {
        Self::new("Float", f.to_string())
    }
}

impl<'a> From<&'a str> for Value<'a> {
    fn from(s: &'a str) -> Self {
        Self::new("String", s)
    }
}

impl From<String> for Value<'static> {
    fn from(s: String) -> Self {
        Self::new("String", s)
    }
}

#[macro_export]
macro_rules! value {
    ($str:literal) => {
        $crate::Value::new("String", $str)
    };
    ($type_:ident { $id:expr }) => {
        $crate::Value::new(stringify!($type_), $id)
    };
    ($val:expr) => {
        $crate::Value::from($val)
    };
}

#[macro_export]
macro_rules! push_values {
    ($args:expr; $str:literal) => {{
        $args.push($crate::value!($str));
    }};
    ($args:expr; $type_:ident { $id:expr }) => {{
        $args.push($crate::value!($type_ { $id }));
    }};

    ($args:expr; $str:literal, $($rest:tt)*) => {{
        $args.push($crate::value!($str));
        $crate::push_values!($args; $($rest)*);
    }};
    ($args:expr; $type_:ident { $id:expr }, $($rest:tt)*) => {{
        $args.push($crate::value!($type_ { $id }));
        $crate::push_values!($args; $($rest)*);
    }};
    ($args:expr; $val:expr) => {{
        $args.push($crate::value!($val));
    }};
    ($args:expr; $val:expr, $($rest:tt)*) => {{
        $args.push($crate::value!($val));
        $crate::push_values!($args; $($rest)*);
    }};
}

#[derive(Serialize, Deserialize, Debug, PartialEq, PartialOrd, Eq, Ord, Clone)]
pub struct Fact<'a> {
    pub predicate: String,
    pub args: Vec<Value<'a>>,
}

#[macro_export]
macro_rules! fact {
    ($predicate:expr, $($args:tt)*) => {{
        let mut args = vec![];
        $crate::push_values!(args; $($args)+);
        $crate::Fact {
            predicate: $predicate.to_owned(),
            args,
        }
    }};
}

pub struct Builder {
    url: String,
    api_key: String,
}

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

impl Builder {
    pub fn new() -> Self {
        Self {
            url: "https://api.osohq.com".to_owned(),
            api_key: "".to_owned(),
        }
    }

    pub fn with_url(&mut self, url: &str) -> &mut Self {
        self.url = url.to_owned();
        self
    }

    pub fn with_api_key(&mut self, api_key: &str) -> &mut Self {
        self.api_key = api_key.to_owned();
        self
    }

    /// Create a new Oso client from environment variables.
    ///
    /// The following environment variables are used:
    ///
    /// * `OSO_URL` - The URL of the Oso Cloud instance to connect to. Defaults to `https://api.osohq.com`.
    /// * `OSO_AUTH` - The API key to use when connecting to Oso Cloud. Defaults to an empty string.
    pub fn from_env() -> Self {
        let mut builder = Builder::new();
        if let Ok(url) = std::env::var("OSO_URL") {
            builder.with_url(&url);
        }
        if let Ok(api_key) = std::env::var("OSO_AUTH") {
            builder.with_api_key(&api_key);
        }
        builder
    }

    pub fn build(&self) -> Result<Oso, Error> {
        if self.api_key.is_empty() {
            return Err(Error::Input("API key must be set".to_owned()));
        }

        Oso::new_with_url(&self.url, &self.api_key)
    }
}

// Generic result from the API, for things that don't need to return anything besides a message.
#[derive(Deserialize)]
struct ApiResult {
    pub message: String,
}

pub struct OsoWithContext<'a> {
    client: &'a api::Client,
    context: Vec<Fact<'a>>,
}

impl Oso {
    pub fn new_with_url(url: &str, api_key: &str) -> Result<Self, Error> {
        let client = api::Client::new(url, api_key)?;
        Ok(Self { client })
    }

    pub fn new(api_key: &str) -> Result<Self, Error> {
        Oso::new_with_url("https://api.osohq.com", api_key)
    }

    /// Update the current policy for the environment
    pub async fn policy(&self, policy_src: &str) -> Result<(), Error> {
        #[derive(Debug, Serialize)]
        struct PolicyRequest<'a> {
            src: &'a str,
        }

        let body = PolicyRequest { src: policy_src };
        let res: ApiResult = self.client.post("policy", &body).await?;
        tracing::info!("Policy updated: {}", res.message);

        Ok(())
    }

    /// Add a single fact into Oso Cloud
    pub async fn tell<'a>(&self, fact: Fact<'a>) -> Result<(), Error> {
        self.bulk(&[], &[fact]).await
    }

    /// Deleta a fact
    pub async fn delete<'a>(&self, fact: Fact<'a>) -> Result<(), Error> {
        self.bulk(&[fact], &[]).await
    }

    /// Add multiple facts into Oso Cloud
    pub async fn bulk_tell<'a>(&self, facts: &[Fact<'a>]) -> Result<(), Error> {
        self.bulk(&[], facts).await
    }

    /// Deletes many facts at once. Does not throw an error when some of the facts are not found.
    ///
    /// `Value::any` and `Value::any_of_type` can be used as a wildcard in facts in delete.
    /// Does not throw an error when the facts to delete are not found.
    pub async fn bulk_delete<'a>(&self, facts: &[Fact<'a>]) -> Result<(), Error> {
        self.bulk(facts, &[]).await
    }

    /// Deletes and adds many facts in one atomic transaction. The deletions are performed before the adds.
    /// `Value::any` and `Value::any_of_type` can be used as a wildcard in facts in delete.
    /// Does not throw an error when the facts to delete are not found.
    pub async fn bulk<'a>(&self, delete: &[Fact<'a>], tell: &'a [Fact<'a>]) -> Result<(), Error> {
        self.client.bulk(delete, tell).await
    }

    /// Lists facts that are stored in Oso Cloud. Can be used to check the existence of a particular fact,
    /// or used to fetch all facts that have a particular argument
    pub async fn get<'a>(&self, fact: &Fact<'a>) -> Result<Vec<Fact<'static>>, Error> {
        let mut params = HashMap::new();

        for (i, a) in fact.args.iter().enumerate() {
            params.insert(format!("args.{i}.type"), a.type_.to_owned());
            params.insert(format!("args.{i}.id"), a.id.to_owned());
        }

        self.client.get("facts", params).await
    }

    fn with_no_context(&self) -> OsoWithContext<'_> {
        OsoWithContext {
            client: &self.client,
            context: vec![],
        }
    }

    pub async fn authorize<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        action: &str,
        resource: impl Into<Value<'a>>,
    ) -> Result<bool, Error> {
        self.with_no_context().authorize(actor, action, resource).await
    }

    pub async fn authorize_resources<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        action: &str,
        resources: Vec<Value<'a>>,
    ) -> Result<Vec<Value<'a>>, Error> {
        self.with_no_context()
            .authorize_resources(actor, action, resources)
            .await
    }

    pub async fn actions<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        resource: impl Into<Value<'a>>,
    ) -> Result<Vec<String>, Error> {
        self.with_no_context().actions(actor, resource).await
    }

    pub async fn list<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        action: &str,
        resource_type: &str,
    ) -> Result<Vec<String>, Error> {
        self.with_no_context().list(actor, action, resource_type).await
    }

    /// Query Oso Cloud for any predicate and any combination of concrete and wildcard arguments.
    ///
    /// Unlike `oso.get`, which only lists facts you've added, you can use `oso.query` to list
    /// derived information about any rule in your policy.
    pub async fn query<'a>(&self, fact: &Fact<'a>) -> Result<Vec<Fact<'static>>, Error> {
        self.with_no_context().query(fact).await
    }

    pub fn with_context<'a>(&'a self, context: Vec<Fact<'a>>) -> OsoWithContext<'a> {
        OsoWithContext {
            client: &self.client,
            context,
        }
    }
}

impl<'ctxt> OsoWithContext<'ctxt> {
    pub async fn authorize<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        action: &str,
        resource: impl Into<Value<'a>>,
    ) -> Result<bool, Error> {
        #[derive(Debug, Serialize)]
        struct AuthorizeRequest<'a> {
            actor_type: &'a str,
            actor_id: &'a str,
            action: &'a str,
            resource_type: &'a str,
            resource_id: &'a str,
            context_facts: &'a [Fact<'a>],
        }

        let actor = actor.into();
        let resource = resource.into();
        let (Some(actor_type), Some(actor_id), Some(resource_type), Some(resource_id)) = (
            actor.type_.as_ref(),
            actor.id.as_ref(),
            resource.type_.as_ref(),
            resource.id.as_ref(),
        ) else {
            if actor.type_.is_none() || actor.id.is_none() {
                return Err(Error::Input("Actor must be a concrete value. Try `oso.query` if you want to get all permitted actors".to_owned()));
            }
            if resource.type_.is_none() || resource.id.is_none() {
                return Err(Error::Input("Resource must be a concrete value. Try `oso.list` if you want to get all allowed resources".to_owned()));
            }
            unreachable!();
        };

        let body = AuthorizeRequest {
            actor_type,
            actor_id,
            action,
            resource_type,
            resource_id,
            context_facts: &self.context,
        };

        #[derive(Deserialize)]
        struct AuthorizeResponse {
            allowed: bool,
        }

        let resp: AuthorizeResponse = self.client.post("authorize", &body).await?;

        Ok(resp.allowed)
    }

    pub async fn authorize_resources<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        action: &str,
        mut resources: Vec<Value<'a>>,
    ) -> Result<Vec<Value<'a>>, Error> {
        #[derive(Debug, Serialize)]
        struct AuthorizeResourcesRequest<'a> {
            actor_type: &'a str,
            actor_id: &'a str,
            action: &'a str,
            resources: &'a Vec<Value<'a>>,
            context_facts: &'a Vec<Fact<'a>>,
        }

        #[derive(Deserialize)]
        struct AuthorizeResourcesResponse<'a> {
            results: Vec<Value<'a>>,
        }

        let actor = actor.into();
        let (Some(actor_type), Some(actor_id)) = (
            actor.type_.as_ref(),
            actor.id.as_ref(),
        ) else {
            return Err(Error::Input("Actor must be a concrete value. Try `oso.query` if you want to get all permitted actors".to_owned()));
        };

        let body = AuthorizeResourcesRequest {
            actor_type,
            actor_id,
            action,
            resources: &resources,
            context_facts: &self.context,
        };

        let resp: AuthorizeResourcesResponse = self.client.post("authorize_resources", &body).await?;

        resources.retain(|val| resp.results.contains(val));

        Ok(resources)
    }

    pub async fn actions<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        resource: impl Into<Value<'a>>,
    ) -> Result<Vec<String>, Error> {
        #[derive(Debug, Serialize)]
        struct ActionsRequest<'a> {
            actor_type: &'a str,
            actor_id: &'a str,
            resource_type: &'a str,
            resource_id: &'a str,
            context_facts: &'a Vec<Fact<'a>>,
        }

        #[derive(Deserialize)]
        struct ActionsResponse {
            results: Vec<String>,
        }

        let actor = actor.into();
        let resource = resource.into();

        let (Some(actor_type), Some(actor_id), Some(resource_type), Some(resource_id)) = (
            actor.type_.as_ref(),
            actor.id.as_ref(),
            resource.type_.as_ref(),
            resource.id.as_ref(),
        ) else {
            if actor.type_.is_none() || actor.id.is_none() {
                return Err(Error::Input("Actor must be a concrete value. Try `oso.query` if you want to get all permitted actors".to_owned()));
            }
            if resource.type_.is_none() || resource.id.is_none() {
                return Err(Error::Input("Resource must be a concrete value. Try `oso.query` if you want to get all allowed actions and resources".to_owned()));
            }
            unreachable!();
        };

        let body = ActionsRequest {
            actor_type,
            actor_id,
            resource_type,
            resource_id,
            context_facts: &self.context,
        };

        let resp: ActionsResponse = self.client.post("actions", &body).await?;
        Ok(resp.results)
    }

    pub async fn list<'a>(
        &self,
        actor: impl Into<Value<'a>>,
        action: &str,
        resource_type: &str,
    ) -> Result<Vec<String>, Error> {
        #[derive(Debug, Serialize)]
        struct ListRequest<'a> {
            actor_type: &'a str,
            actor_id: &'a str,
            action: &'a str,
            resource_type: &'a str,
            context_facts: &'a Vec<Fact<'a>>,
        }

        #[derive(Deserialize)]
        struct ListResponse {
            results: Vec<String>,
        }

        let actor = actor.into();

        let (Some(actor_type), Some(actor_id)) = (
            actor.type_.as_ref(),
            actor.id.as_ref(),
        ) else {
            return Err(Error::Input("Actor must be a concrete value. Try `oso.query` if you want to get all permitted actors".to_owned()));
        };

        let body = ListRequest {
            actor_type,
            actor_id,
            action,
            resource_type,
            context_facts: &self.context,
        };

        let resp: ListResponse = self.client.post("list", &body).await?;
        Ok(resp.results)
    }

    /// Query Oso Cloud for any predicate and any combination of concrete and wildcard arguments.
    ///
    /// Unlike `oso.get`, which only lists facts you've added, you can use `oso.query` to list
    /// derived information about any rule in your policy.
    pub async fn query<'a>(&self, fact: &Fact<'a>) -> Result<Vec<Fact<'static>>, Error> {
        #[derive(Debug, Serialize)]
        struct QueryRequest<'a> {
            fact: &'a Fact<'a>,
            context_facts: &'a Vec<Fact<'a>>,
        }

        let body = QueryRequest {
            fact,
            context_facts: &self.context,
        };

        #[derive(Deserialize)]
        struct QueryResponse {
            results: Vec<Fact<'static>>,
        }

        let resp: QueryResponse = self.client.post("query", &body).await?;

        Ok(resp.results)
    }
}
#[cfg(test)]
mod tests {}