Struct cedar_policy::Context

source ·
pub struct Context(/* private fields */);
Expand description

the Context object for an authorization request

Implementations§

source§

impl Context

source

pub fn empty() -> Self

Create an empty Context

use cedar_policy::Context;
let c = Context::empty();
// let request: Request = Request::new(Some(principal), Some(action), Some(resource), c);
source

pub fn from_pairs( pairs: impl IntoIterator<Item = (String, RestrictedExpression)>, ) -> Self

Create a Context from a map of key to “restricted expression”, or a Vec of (key, restricted expression) pairs, or any other iterator of (key, restricted expression) pairs.

use cedar_policy::{Context, RestrictedExpression};
use std::collections::HashMap;
use std::str::FromStr;
let data : serde_json::Value = serde_json::json!({
    "sub": "1234",
    "groups": {
        "1234": {
            "group_id": "abcd",
            "group_name": "test-group"
        }
    }
});
let mut groups: HashMap<String, RestrictedExpression> = HashMap::new();
groups.insert("key".to_string(), RestrictedExpression::from_str(&data.to_string()).unwrap());
groups.insert("age".to_string(), RestrictedExpression::from_str("18").unwrap());
let context = Context::from_pairs(groups);
let request: Request = Request::new(Some(p), Some(a), Some(r), context);
source

pub fn from_json_str( json: &str, schema: Option<(&Schema, &EntityUid)>, ) -> Result<Self, ContextJsonError>

Create a Context from a string containing JSON (which must be a JSON object, not any other JSON type, or you will get an error here). JSON here must use the __entity and __extn escapes for entity references, extension values, etc.

If a schema is provided, this will inform the parsing: for instance, it will allow __entity and __extn escapes to be implicit, and it will error if attributes have the wrong types (e.g., string instead of integer). Since different Actions have different schemas for Context, you also must specify the Action for schema-based parsing.

use cedar_policy::{Context, RestrictedExpression};
use std::collections::HashMap;
use std::str::FromStr;
let data =r#"{
    "sub": "1234",
    "groups": {
        "1234": {
            "group_id": "abcd",
            "group_name": "test-group"
        }
    }
}"#;
let context = Context::from_json_str(data, None).unwrap();
let request: Request = Request::new(Some(p), Some(a), Some(r), context);
source

pub fn from_json_value( json: Value, schema: Option<(&Schema, &EntityUid)>, ) -> Result<Self, ContextJsonError>

Create a Context from a serde_json::Value (which must be a JSON object, not any other JSON type, or you will get an error here). JSON here must use the __entity and __extn escapes for entity references, extension values, etc.

If a schema is provided, this will inform the parsing: for instance, it will allow __entity and __extn escapes to be implicit, and it will error if attributes have the wrong types (e.g., string instead of integer). Since different Actions have different schemas for Context, you also must specify the Action for schema-based parsing.

use cedar_policy::{Context, RestrictedExpression, Schema};
use std::collections::HashMap;
use std::str::FromStr;
let data = serde_json::json!(
{
    "sub": "1234"
});
let schema_data =r#"
    {
      "": {
        "entityTypes": {},
          "actions": {
            "view": {
               "appliesTo": {
                 "principalTypes": [],
                  "resourceTypes": [],
                  "context": {
                    "type": "Record",
                    "attributes": {
                      "sub": { "type": "Long" }
                    }
                  }
                }
              }
          }
      }
    }"#;
let a_eid = EntityId::from_str("view").unwrap();
let a_name: EntityTypeName = EntityTypeName::from_str("Action").unwrap();
let action = EntityUid::from_type_name_and_id(a_name, a_eid);
let schema = Schema::from_str(schema_data).unwrap();
let context = Context::from_json_value(data, Some((&schema, &action))).unwrap();
let request: Request = Request::new(Some(principal), Some(action), Some(resource), context);
source

pub fn from_json_file( json: impl Read, schema: Option<(&Schema, &EntityUid)>, ) -> Result<Self, ContextJsonError>

Create a Context from a JSON file. The JSON file must contain a JSON object, not any other JSON type, or you will get an error here. JSON here must use the __entity and __extn escapes for entity references, extension values, etc.

If a schema is provided, this will inform the parsing: for instance, it will allow __entity and __extn escapes to be implicit, and it will error if attributes have the wrong types (e.g., string instead of integer). Since different Actions have different schemas for Context, you also must specify the Action for schema-based parsing.

let mut json = File::open("json_file.txt").expect("failed");
let context = Context::from_json_file(&json, None).unwrap();
let request: Request = Request::new(Some(p), Some(a), Some(r), context);

Trait Implementations§

source§

impl Clone for Context

source§

fn clone(&self) -> Context

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Context

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl RefCast for Context

source§

type From = Context

source§

fn ref_cast(_from: &Self::From) -> &Self

source§

fn ref_cast_mut(_from: &mut Self::From) -> &mut Self

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> ToOwned for T
where T: Clone,

source§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

source§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.