Skip to content

Commit

Permalink
chore(jans-cedarling): run cargo fmt and add missing license headers
Browse files Browse the repository at this point in the history
Signed-off-by: rmarinn <[email protected]>
  • Loading branch information
rmarinn committed Dec 21, 2024
1 parent ac7f80c commit 36525fa
Show file tree
Hide file tree
Showing 66 changed files with 1,728 additions and 1,628 deletions.
60 changes: 35 additions & 25 deletions jans-cedarling/cedarling/examples/authorize_with_jwt_validation.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,27 @@
/*
* This software is available under the Apache-2.0 license.
* See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
*
* Copyright (c) 2024, Gluu, Inc.
*/
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

use std::collections::{HashMap, HashSet};

use cedarling::{
AuthorizationConfig, BootstrapConfig, Cedarling, IdTokenTrustMode, JwtConfig, LogConfig,
LogLevel, LogTypeConfig, PolicyStoreConfig, PolicyStoreSource, Request, ResourceData,
TokenValidationConfig, WorkloadBoolOp,
AuthorizationConfig,
BootstrapConfig,
Cedarling,
IdTokenTrustMode,
JwtConfig,
LogConfig,
LogLevel,
LogTypeConfig,
PolicyStoreConfig,
PolicyStoreSource,
Request,
ResourceData,
TokenValidationConfig,
WorkloadBoolOp,
};
use jsonwebtoken::Algorithm;
use std::collections::{HashMap, HashSet};

static POLICY_STORE_RAW_YAML: &str =
include_str!("../../test_files/policy-store_with_trusted_issuers_ok.yaml");
Expand All @@ -21,14 +31,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// using specific algorithms: `HS256` and `RS256`. Only tokens signed with these algorithms
// will be accepted; others will be marked as invalid during validation.
let jwt_config = JwtConfig {
jwks: None,
jwt_sig_validation: true,
jwt_status_validation: false,
id_token_trust_mode: IdTokenTrustMode::None,
jwks: None,
jwt_sig_validation: true,
jwt_status_validation: false,
id_token_trust_mode: IdTokenTrustMode::None,
signature_algorithms_supported: HashSet::from_iter([Algorithm::HS256, Algorithm::RS256]),
access_token_config: TokenValidationConfig::access_token(),
id_token_config: TokenValidationConfig::id_token(),
userinfo_token_config: TokenValidationConfig::userinfo_token(),
access_token_config: TokenValidationConfig::access_token(),
id_token_config: TokenValidationConfig::id_token(),
userinfo_token_config: TokenValidationConfig::userinfo_token(),
};

// You must change this with your own tokens
Expand All @@ -42,7 +52,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let cedarling = Cedarling::new(&BootstrapConfig {
application_name: "test_app".to_string(),
log_config: LogConfig {
log_type: LogTypeConfig::StdOut,
log_type: LogTypeConfig::StdOut,
log_level: LogLevel::INFO,
},
policy_store_config: PolicyStoreConfig {
Expand All @@ -62,15 +72,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// on a specific resource. Each token (access, ID, and userinfo) is required for the
// authorization process, alongside resource and action details.
let result = cedarling.authorize(Request {
access_token: Some(access_token),
id_token: Some(id_token),
access_token: Some(access_token),
id_token: Some(id_token),
userinfo_token: Some(userinfo_token),
action: "Jans::Action::\"Update\"".to_string(),
context: serde_json::json!({}),
resource: ResourceData {
id: "random_id".to_string(),
action: "Jans::Action::\"Update\"".to_string(),
context: serde_json::json!({}),
resource: ResourceData {
id: "random_id".to_string(),
resource_type: "Jans::Issue".to_string(),
payload: HashMap::from_iter([(
payload: HashMap::from_iter([(
"org_id".to_string(),
serde_json::Value::String("some_long_id".to_string()),
)]),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,38 @@
/*
* This software is available under the Apache-2.0 license.
* See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
*
* Copyright (c) 2024, Gluu, Inc.
*/
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

use std::collections::HashMap;

use cedarling::{
AuthorizationConfig, BootstrapConfig, Cedarling, JwtConfig, LogConfig, LogLevel, LogTypeConfig,
PolicyStoreConfig, PolicyStoreSource, Request, ResourceData, WorkloadBoolOp,
AuthorizationConfig,
BootstrapConfig,
Cedarling,
JwtConfig,
LogConfig,
LogLevel,
LogTypeConfig,
PolicyStoreConfig,
PolicyStoreSource,
Request,
ResourceData,
WorkloadBoolOp,
};
use std::collections::HashMap;

static POLICY_STORE_RAW: &str = include_str!("../../test_files/policy-store_ok.yaml");

fn main() -> Result<(), Box<dyn std::error::Error>> {
let cedarling = Cedarling::new(&BootstrapConfig {
application_name: "test_app".to_string(),
log_config: LogConfig {
log_type: LogTypeConfig::StdOut,
application_name: "test_app".to_string(),
log_config: LogConfig {
log_type: LogTypeConfig::StdOut,
log_level: LogLevel::INFO,
},
policy_store_config: PolicyStoreConfig {
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_RAW.to_string()),
},
jwt_config: JwtConfig::new_without_validation(),
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig {
use_user_principal: true,
use_workload_principal: true,
Expand Down Expand Up @@ -113,15 +122,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let userinfo_token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwczovL2FkbWluLXVpLXRlc3QuZ2x1dS5vcmciLCJzdWIiOiJib0c4ZGZjNU1LVG4zN283Z3NkQ2V5cUw4THBXUXRnb080MW0xS1p3ZHEwIiwiY2xpZW50X2lkIjoiNWI0NDg3YzQtOGRiMS00MDlkLWE2NTMtZjkwN2I4MDk0MDM5IiwiYXVkIjoiNWI0NDg3YzQtOGRiMS00MDlkLWE2NTMtZjkwN2I4MDk0MDM5IiwidXNlcm5hbWUiOiJhZG1pbkBnbHV1Lm9yZyIsIm5hbWUiOiJEZWZhdWx0IEFkbWluIFVzZXIiLCJlbWFpbCI6ImFkbWluQGdsdXUub3JnIiwiY291bnRyeSI6IlVTIiwianRpIjoidXNyaW5mb190a25fanRpIn0.NoR53vPZFpfb4vFk85JH9RPx7CHsaJMZwrH3fnB-N60".to_string();

let result = cedarling.authorize(Request {
access_token: Some(access_token),
id_token: Some(id_token),
access_token: Some(access_token),
id_token: Some(id_token),
userinfo_token: Some(userinfo_token),
action: "Jans::Action::\"Update\"".to_string(),
context: serde_json::json!({}),
resource: ResourceData {
id: "random_id".to_string(),
action: "Jans::Action::\"Update\"".to_string(),
context: serde_json::json!({}),
resource: ResourceData {
id: "random_id".to_string(),
resource_type: "Jans::Issue".to_string(),
payload: HashMap::from_iter([
payload: HashMap::from_iter([
(
"org_id".to_string(),
serde_json::Value::String("some_long_id".to_string()),
Expand Down
35 changes: 22 additions & 13 deletions jans-cedarling/cedarling/examples/log_init.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,30 @@
/*
* This software is available under the Apache-2.0 license.
* See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
*
* Copyright (c) 2024, Gluu, Inc.
*/
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

// The following macro uses conditional compilation to include this file code
// only when the target platform is NOT WebAssembly. This is not required to
// use the library but is needed here since Cedarling compiles binding to WASM
// and `use std::env` prevents that compilation.
#![cfg(not(target_family = "wasm"))]

use std::env;

use cedarling::{
AuthorizationConfig, BootstrapConfig, Cedarling, JwtConfig, LogConfig, LogLevel, LogStorage,
LogTypeConfig, MemoryLogConfig, PolicyStoreConfig, PolicyStoreSource, WorkloadBoolOp,
AuthorizationConfig,
BootstrapConfig,
Cedarling,
JwtConfig,
LogConfig,
LogLevel,
LogStorage,
LogTypeConfig,
MemoryLogConfig,
PolicyStoreConfig,
PolicyStoreSource,
WorkloadBoolOp,
};
use std::env;

// The human-readable policy and schema file is located in next folder:
// `test_files\policy-store_ok`
Expand Down Expand Up @@ -47,15 +56,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {

println!("Cedarling initialized with log type: {:?}", log_type);
let cedarling = Cedarling::new(&BootstrapConfig {
application_name: "test_app".to_string(),
log_config: LogConfig {
application_name: "test_app".to_string(),
log_config: LogConfig {
log_type,
log_level: LogLevel::INFO,
},
policy_store_config: PolicyStoreConfig {
policy_store_config: PolicyStoreConfig {
source: PolicyStoreSource::Yaml(POLICY_STORE_RAW.to_string()),
},
jwt_config: JwtConfig::new_without_validation(),
jwt_config: JwtConfig::new_without_validation(),
authorization_config: AuthorizationConfig {
use_user_principal: true,
use_workload_principal: true,
Expand Down
17 changes: 8 additions & 9 deletions jans-cedarling/cedarling/src/authz/authorize_result.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
/*
* This software is available under the Apache-2.0 license.
* See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
*
* Copyright (c) 2024, Gluu, Inc.
*/
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

use std::collections::HashSet;

use cedar_policy::Decision;
use serde::ser::SerializeStruct;
use serde::{Serialize, Serializer};
use std::collections::HashSet;

use crate::bootstrap_config::WorkloadBoolOp;

Expand All @@ -19,10 +18,10 @@ pub struct AuthorizeResult {
user_workload_operator: WorkloadBoolOp,
/// Result of authorization where principal is `Jans::Workload`
#[serde(serialize_with = "serialize_opt_response")]
pub workload: Option<cedar_policy::Response>,
pub workload: Option<cedar_policy::Response>,
/// Result of authorization where principal is `Jans::User`
#[serde(serialize_with = "serialize_opt_response")]
pub person: Option<cedar_policy::Response>,
pub person: Option<cedar_policy::Response>,
}

/// Custom serializer for an Option<String> which converts `None` to an empty string and vice versa.
Expand Down
71 changes: 35 additions & 36 deletions jans-cedarling/cedarling/src/authz/entities/create.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,32 @@
/*
* This software is available under the Apache-2.0 license.
* See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
*
* Copyright (c) 2024, Gluu, Inc.
*/

use std::{
collections::{HashMap, HashSet},
str::FromStr,
};
// This software is available under the Apache-2.0 license.
// See https://www.apache.org/licenses/LICENSE-2.0.txt for full text.
//
// Copyright (c) 2024, Gluu, Inc.

use std::collections::{HashMap, HashSet};
use std::str::FromStr;

use cedar_policy::{EntityId, EntityTypeName, EntityUid, RestrictedExpression};

use super::trait_as_expression::AsExpression;
use crate::common::cedar_schema::CedarSchemaJson;
use crate::common::cedar_schema::cedar_json::{
CedarSchemaEntityShape, CedarSchemaRecord, CedarType, GetCedarTypeError, SchemaDefinedType,
CedarSchemaEntityShape,
CedarSchemaRecord,
CedarType,
GetCedarTypeError,
SchemaDefinedType,
};
use crate::common::{cedar_schema::CedarSchemaJson, policy_store::ClaimMappings};
use crate::jwt::Token;
use crate::jwt::{TokenClaim, TokenClaimTypeError, TokenClaims};
use cedar_policy::{EntityId, EntityTypeName, EntityUid, RestrictedExpression};
use crate::common::policy_store::ClaimMappings;
use crate::jwt::{Token, TokenClaim, TokenClaimTypeError, TokenClaims};

pub const CEDAR_POLICY_SEPARATOR: &str = "::";

/// Meta information about an entity type.
/// Is used to store in `static` variable.
#[derive(Debug)]
pub(crate) struct EntityMetadata<'a> {
pub entity_type: EntityParsedTypeName<'a>,
pub entity_type: EntityParsedTypeName<'a>,
pub entity_id_data_key: &'a str,
}

Expand All @@ -39,7 +40,6 @@ impl<'a> EntityMetadata<'a> {
}

/// Create entity from token data.
//
// we also can create entity using the ['create_entity'] function.
pub fn create_entity(
&'a self,
Expand Down Expand Up @@ -146,13 +146,13 @@ fn entity_meta_attributes(
.attributes
.iter()
.map(|(attribute_name, attribute)| {
attribute
.get_type()
.map(|attr_type| EntityAttributeMetadata {
attribute_name: attribute_name.as_str(),
attribute.get_type().map(|attr_type| {
EntityAttributeMetadata {
attribute_name: attribute_name.as_str(),
cedar_policy_type: attr_type,
is_required: attribute.is_required(),
})
is_required: attribute.is_required(),
}
})
})
.collect::<Result<Vec<_>, _>>()
}
Expand Down Expand Up @@ -216,11 +216,11 @@ pub fn create_entity(
pub struct EntityAttributeMetadata<'a> {
// The name of the attribute in the cedar policy
// mapped one-to-one with the attribute in the token data.
pub attribute_name: &'a str,
pub attribute_name: &'a str,
// The type of the cedar policy attribute.
pub cedar_policy_type: CedarType,
// if this attribute is required
pub is_required: bool,
pub is_required: bool,
}

/// Get the cedar policy expression value for a given type.
Expand Down Expand Up @@ -263,9 +263,8 @@ fn get_expression(
CedarType::Boolean => Ok(claim.as_bool()?.to_expression()),
CedarType::TypeName(cedar_typename) => {
match schema.find_type(cedar_typename, base_entity_typename.namespace) {
Some(SchemaDefinedType::Entity(_)) => {
get_entity_expression(cedar_typename, base_entity_typename, claim)
},
Some(SchemaDefinedType::Entity(_)) =>
get_entity_expression(cedar_typename, base_entity_typename, claim),
Some(SchemaDefinedType::CommonType(record)) => {
let record_typename =
EntityParsedTypeName::new(cedar_typename, base_entity_typename.namespace);
Expand All @@ -278,10 +277,11 @@ fn get_expression(
)
})
},
None => Err(CreateCedarEntityError::FindType(
EntityParsedTypeName::new(cedar_typename, base_entity_typename.namespace)
.full_type_name(),
)),
None =>
Err(CreateCedarEntityError::FindType(
EntityParsedTypeName::new(cedar_typename, base_entity_typename.namespace)
.full_type_name(),
)),
}
},
CedarType::Set(cedar_type) => {
Expand Down Expand Up @@ -341,13 +341,12 @@ fn get_record_expression(
Some(m) => m.apply_mapping(token_claim.value()).into(),
// if we do not have mapping, and value is json object, return TokenPayload based on it.
// if value is not json object, return empty value
None => {
None =>
if let Some(map) = token_claim.value().as_object() {
TokenClaims::from_json_map(map.to_owned())
} else {
TokenClaims::default()
}
},
},
};

let mut record_restricted_exps = Vec::new();
Expand Down
Loading

0 comments on commit 36525fa

Please sign in to comment.