From 2185b6d8a80d78e3b1b1421f99cab884705d3cbf Mon Sep 17 00:00:00 2001 From: mo khan Date: Fri, 4 Jul 2025 13:29:34 -0600 Subject: refactor: start to refactor the sparkle policies --- src/authorization/cedar_authorizer.rs | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 432102ef..17867aba 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -1,10 +1,9 @@ use super::authorizer::Authorizer; use cedar_policy::{ Authorizer as CedarAuth, Context, Entities, EntityId, EntityTypeName, EntityUid, PolicySet, - Request as CedarRequest, RestrictedExpression, + Request as CedarRequest, }; use envoy_types::ext_authz::v3::pb::CheckRequest; -use std::collections::HashMap; use std::fs; use std::str::FromStr; @@ -86,14 +85,7 @@ impl Authorizer for CedarAuthorizer { return true; } - let headers = &http_request.headers; - - let bearer_token = headers - .get("authorization") - .and_then(|auth| auth.strip_prefix("Bearer ")) - .unwrap_or(""); - - match self.create_cedar_request(bearer_token, &http_request.path.to_string()) { + match self.create_cedar_request(http_request.clone()) { Ok(cedar_request) => { let entities = Entities::empty(); let response = @@ -117,9 +109,14 @@ impl Authorizer for CedarAuthorizer { impl CedarAuthorizer { fn create_cedar_request( &self, - bearer_token: &str, - path: &str, + http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { + let headers = &http_request.headers; + let bearer_token = headers + .get("authorization") + .and_then(|auth| auth.strip_prefix("Bearer ")) + .unwrap_or(""); + // Create principal entity let principal_id = EntityId::from_str("client")?; let principal_type = EntityTypeName::from_str("User")?; @@ -135,18 +132,17 @@ impl CedarAuthorizer { let resource_type = EntityTypeName::from_str("Resource")?; let resource = EntityUid::from_type_name_and_id(resource_type, resource_id); - // Create context with bearer token and path - let mut context_map = HashMap::new(); + let mut context_map = std::collections::HashMap::new(); if !bearer_token.is_empty() { context_map.insert( "bearer_token".to_string(), - RestrictedExpression::from_str(&format!("\"{bearer_token}\""))?, + cedar_policy::RestrictedExpression::from_str(bearer_token)?, ); } - if !path.is_empty() { + if !http_request.path.is_empty() { context_map.insert( "path".to_string(), - RestrictedExpression::from_str(&format!("\"{path}\""))?, + cedar_policy::RestrictedExpression::from_str(&http_request.path.to_string())?, ); } -- cgit v1.2.3 From 784e0740a6ca7684feba3fb4f26d68e098b5c826 Mon Sep 17 00:00:00 2001 From: mo khan Date: Fri, 4 Jul 2025 16:39:37 -0600 Subject: refactor: map from http request to cedar request --- src/authorization/cedar_authorizer.rs | 8 ++++---- tests/authorization/cedar_authorizer_test.rs | 20 ++++++++------------ tests/authorization/check_service_test.rs | 17 +++++++---------- 3 files changed, 19 insertions(+), 26 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 17867aba..4eeaf645 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -85,7 +85,7 @@ impl Authorizer for CedarAuthorizer { return true; } - match self.create_cedar_request(http_request.clone()) { + match self.map_from(http_request.clone()) { Ok(cedar_request) => { let entities = Entities::empty(); let response = @@ -107,7 +107,7 @@ impl Authorizer for CedarAuthorizer { } impl CedarAuthorizer { - fn create_cedar_request( + fn map_from( &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { @@ -136,13 +136,13 @@ impl CedarAuthorizer { if !bearer_token.is_empty() { context_map.insert( "bearer_token".to_string(), - cedar_policy::RestrictedExpression::from_str(bearer_token)?, + cedar_policy::RestrictedExpression::new_string(bearer_token.to_string()), ); } if !http_request.path.is_empty() { context_map.insert( "path".to_string(), - cedar_policy::RestrictedExpression::from_str(&http_request.path.to_string())?, + cedar_policy::RestrictedExpression::new_string(http_request.path.clone()), ); } diff --git a/tests/authorization/cedar_authorizer_test.rs b/tests/authorization/cedar_authorizer_test.rs index 79f83c00..317ef67f 100644 --- a/tests/authorization/cedar_authorizer_test.rs +++ b/tests/authorization/cedar_authorizer_test.rs @@ -8,12 +8,10 @@ mod tests { #[test] fn test_cedar_authorizer_allows_valid_token() { let request = build_request(|item: &mut HttpRequest| { - item.headers = build_with(|item: &mut HashMap| { - item.insert( - String::from("authorization"), - String::from("Bearer valid-token"), - ); - }); + item.headers = build_headers(vec![( + "authorization".to_string(), + "Bearer valid-token".to_string(), + )]); }); assert!(build_cedar_authorizer().authorize(request)); @@ -22,12 +20,10 @@ mod tests { #[test] fn test_cedar_authorizer_denies_invalid_token() { let request = build_request(|item: &mut HttpRequest| { - item.headers = build_with(|item: &mut HashMap| { - item.insert( - String::from("authorization"), - String::from("Bearer invalid-token"), - ); - }); + item.headers = build_headers(vec![( + "authorization".to_string(), + "Bearer invalid-token".to_string(), + )]); }); assert!(!build_cedar_authorizer().authorize(request)); diff --git a/tests/authorization/check_service_test.rs b/tests/authorization/check_service_test.rs index a4b8f2ee..fe45712d 100644 --- a/tests/authorization/check_service_test.rs +++ b/tests/authorization/check_service_test.rs @@ -14,6 +14,7 @@ mod tests { #[tokio::test] async fn test_check_allows_valid_bearer_token() { let request = tonic::Request::new(build_request(|item: &mut HttpRequest| { + item.path = String::from("/"); item.headers = build_headers(vec![( "authorization".to_string(), format!("Bearer {}", String::from("valid-token")), @@ -100,13 +101,13 @@ mod tests { #[tokio::test] async fn test_table() { let test_cases = vec![ - ("Bearer valid-token", true), - ("Bearer invalid-token", false), - ("Basic valid-token", false), - ("", false), + ("Bearer valid-token", tonic::Code::Ok), + ("Bearer invalid-token", tonic::Code::Unauthenticated), + ("Basic valid-token", tonic::Code::Unauthenticated), + ("", tonic::Code::Unauthenticated), ]; - for (auth_value, should_succeed) in test_cases { + for (auth_value, expected_status_code) in test_cases { let request = tonic::Request::new(build_request(|item: &mut HttpRequest| { item.headers = build_headers(vec![("authorization".to_string(), auth_value.to_string())]); @@ -118,11 +119,7 @@ mod tests { let check_response = response.unwrap().into_inner(); let status = check_response.status.unwrap(); - if should_succeed { - assert_eq!(status.code, tonic::Code::Ok as i32); - } else { - assert_eq!(status.code, tonic::Code::Unauthenticated as i32); - } + assert_eq!(status.code, expected_status_code as i32); } } -- cgit v1.2.3 From e821b395783f2494f48ad941c606bec615e3b44e Mon Sep 17 00:00:00 2001 From: mo khan Date: Fri, 4 Jul 2025 17:44:34 -0600 Subject: refactor: extract method to convert http request to cedar context --- src/authorization/cedar_authorizer.rs | 26 ++++++++++++++++---------- tests/authorization/check_service_test.rs | 27 ++++++++++++++++++++------- 2 files changed, 36 insertions(+), 17 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 4eeaf645..e56640f9 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -111,12 +111,6 @@ impl CedarAuthorizer { &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { - let headers = &http_request.headers; - let bearer_token = headers - .get("authorization") - .and_then(|auth| auth.strip_prefix("Bearer ")) - .unwrap_or(""); - // Create principal entity let principal_id = EntityId::from_str("client")?; let principal_type = EntityTypeName::from_str("User")?; @@ -132,7 +126,22 @@ impl CedarAuthorizer { let resource_type = EntityTypeName::from_str("Resource")?; let resource = EntityUid::from_type_name_and_id(resource_type, resource_id); + let context = self.context_from(http_request); + CedarRequest::new(principal, action, resource, context?, None) + .map_err(|e| Box::new(e) as Box) + } + + fn context_from( + &self, + http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, + ) -> Result { let mut context_map = std::collections::HashMap::new(); + + let headers = &http_request.headers; + let bearer_token = headers + .get("authorization") + .and_then(|auth| auth.strip_prefix("Bearer ")) + .unwrap_or(""); if !bearer_token.is_empty() { context_map.insert( "bearer_token".to_string(), @@ -146,9 +155,6 @@ impl CedarAuthorizer { ); } - let context = Context::from_pairs(context_map.into_iter().collect::>())?; - - CedarRequest::new(principal, action, resource, context, None) - .map_err(|e| Box::new(e) as Box) + Context::from_pairs(context_map.into_iter().collect::>()) } } diff --git a/tests/authorization/check_service_test.rs b/tests/authorization/check_service_test.rs index 4ff7a89b..73812fa1 100644 --- a/tests/authorization/check_service_test.rs +++ b/tests/authorization/check_service_test.rs @@ -125,7 +125,6 @@ mod tests { #[tokio::test] async fn test_public_sparkle_endpoints() { - // {status: tonic::Code::Ok, http: &HTTPRequest{Method: "GET", Path: "/"}}, // {status: tonic::Code::Ok, http: &HTTPRequest{Method: "GET", Path: "/application.js"}}, // {status: tonic::Code::Ok, http: &HTTPRequest{Method: "GET", Path: "/callback"}}, // {status: tonic::Code::Ok, http: &HTTPRequest{Method: "GET", Path: "/dashboard", Headers: loggedInHeaders}}, @@ -147,12 +146,26 @@ mod tests { // {status: tonic::Code::PermissionDenied, http: &HTTPRequest{Method: "GET", Path: "/dashboard", Headers: invalidHeaders}}, // {status: tonic::Code::PermissionDenied, http: &HTTPRequest{Method: "POST", Path: "/sparkles"}}, - let test_cases = vec![( - "GET", - "/", - "sparkle.staging.runway.gitlab.net", - tonic::Code::Ok, - )]; + let test_cases = vec![ + ( + "GET", + "/", + "sparkle.staging.runway.gitlab.net", + tonic::Code::Ok, + ), + ( + "GET", + "/application.js", + "sparkle.staging.runway.gitlab.net", + tonic::Code::Ok, + ), + ( + "GET", + "/callback", + "sparkle.staging.runway.gitlab.net", + tonic::Code::Ok, + ), + ]; for (method, path, host, expected_status_code) in test_cases { let request = tonic::Request::new(build_request(|item: &mut HttpRequest| { -- cgit v1.2.3 From c6dd31046b369e6ac44ee85f6206a4384f9dd148 Mon Sep 17 00:00:00 2001 From: mo khan Date: Fri, 4 Jul 2025 18:13:28 -0600 Subject: refactor: extract method to parse principal --- src/authorization/cedar_authorizer.rs | 63 ++++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 20 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index e56640f9..1780eddd 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -85,6 +85,20 @@ impl Authorizer for CedarAuthorizer { return true; } + if http_request.host == "sparkle.staging.runway.gitlab.net" + && http_request.method == "GET" + && http_request.path == "/application.js" + { + return true; + } + + if http_request.host == "sparkle.staging.runway.gitlab.net" + && http_request.method == "GET" + && http_request.path == "/callback" + { + return true; + } + match self.map_from(http_request.clone()) { Ok(cedar_request) => { let entities = Entities::empty(); @@ -111,10 +125,7 @@ impl CedarAuthorizer { &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { - // Create principal entity - let principal_id = EntityId::from_str("client")?; - let principal_type = EntityTypeName::from_str("User")?; - let principal = EntityUid::from_type_name_and_id(principal_type, principal_id); + let principal = self.principal_from(&http_request)?; // Create action entity let action_id = EntityId::from_str("check")?; @@ -131,30 +142,42 @@ impl CedarAuthorizer { .map_err(|e| Box::new(e) as Box) } + fn principal_from( + &self, + _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, + ) -> Result> { + let principal_id = EntityId::from_str("client")?; + let principal_type = EntityTypeName::from_str("User")?; + let principal = EntityUid::from_type_name_and_id(principal_type, principal_id); + Ok(principal) + } + fn context_from( &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result { - let mut context_map = std::collections::HashMap::new(); + let mut items = std::collections::HashMap::new(); + + items.insert("bearer_token".to_string(), self.token_from(&http_request)); + items.insert("path".to_string(), self.safe_string(&http_request.path)); - let headers = &http_request.headers; - let bearer_token = headers + Context::from_pairs(items.into_iter().collect::>()) + } + + fn token_from( + &self, + http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, + ) -> cedar_policy::RestrictedExpression { + let bearer_token = &http_request + .headers .get("authorization") .and_then(|auth| auth.strip_prefix("Bearer ")) .unwrap_or(""); - if !bearer_token.is_empty() { - context_map.insert( - "bearer_token".to_string(), - cedar_policy::RestrictedExpression::new_string(bearer_token.to_string()), - ); - } - if !http_request.path.is_empty() { - context_map.insert( - "path".to_string(), - cedar_policy::RestrictedExpression::new_string(http_request.path.clone()), - ); - } - Context::from_pairs(context_map.into_iter().collect::>()) + self.safe_string(bearer_token) + } + + fn safe_string(&self, item: &str) -> cedar_policy::RestrictedExpression { + cedar_policy::RestrictedExpression::new_string(item.to_string()) } } -- cgit v1.2.3 From 7f045aced7b556f46911aafb0a23764577d84e82 Mon Sep 17 00:00:00 2001 From: mo khan Date: Fri, 4 Jul 2025 18:15:44 -0600 Subject: refactor: extract method to parse permission --- src/authorization/cedar_authorizer.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 1780eddd..6f5b8e63 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -126,11 +126,7 @@ impl CedarAuthorizer { http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { let principal = self.principal_from(&http_request)?; - - // Create action entity - let action_id = EntityId::from_str("check")?; - let action_type = EntityTypeName::from_str("Action")?; - let action = EntityUid::from_type_name_and_id(action_type, action_id); + let permission = self.permission_from(&http_request)?; // Create resource entity let resource_id = EntityId::from_str("resource")?; @@ -138,7 +134,7 @@ impl CedarAuthorizer { let resource = EntityUid::from_type_name_and_id(resource_type, resource_id); let context = self.context_from(http_request); - CedarRequest::new(principal, action, resource, context?, None) + CedarRequest::new(principal, permission, resource, context?, None) .map_err(|e| Box::new(e) as Box) } @@ -152,6 +148,16 @@ impl CedarAuthorizer { Ok(principal) } + fn permission_from( + &self, + _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, + ) -> Result> { + let action_id = EntityId::from_str("check")?; + let action_type = EntityTypeName::from_str("Action")?; + let action = EntityUid::from_type_name_and_id(action_type, action_id); + Ok(action) + } + fn context_from( &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, -- cgit v1.2.3 From 0ba8f6c8ecaa366afbb90fcddbc58fcd395fd03d Mon Sep 17 00:00:00 2001 From: mo khan Date: Fri, 4 Jul 2025 18:22:27 -0600 Subject: refactor: inline variables --- src/authorization/cedar_authorizer.rs | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 6f5b8e63..f90e8d8b 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -127,13 +127,9 @@ impl CedarAuthorizer { ) -> Result> { let principal = self.principal_from(&http_request)?; let permission = self.permission_from(&http_request)?; - - // Create resource entity - let resource_id = EntityId::from_str("resource")?; - let resource_type = EntityTypeName::from_str("Resource")?; - let resource = EntityUid::from_type_name_and_id(resource_type, resource_id); - + let resource = self.resource_from(&http_request)?; let context = self.context_from(http_request); + CedarRequest::new(principal, permission, resource, context?, None) .map_err(|e| Box::new(e) as Box) } @@ -142,20 +138,30 @@ impl CedarAuthorizer { &self, _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { - let principal_id = EntityId::from_str("client")?; - let principal_type = EntityTypeName::from_str("User")?; - let principal = EntityUid::from_type_name_and_id(principal_type, principal_id); - Ok(principal) + Ok(EntityUid::from_type_name_and_id( + EntityTypeName::from_str("User")?, + EntityId::from_str("client")?, + )) } fn permission_from( &self, _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { - let action_id = EntityId::from_str("check")?; - let action_type = EntityTypeName::from_str("Action")?; - let action = EntityUid::from_type_name_and_id(action_type, action_id); - Ok(action) + Ok(EntityUid::from_type_name_and_id( + EntityTypeName::from_str("Action")?, + EntityId::from_str("check")?, + )) + } + + fn resource_from( + &self, + _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, + ) -> Result> { + Ok(EntityUid::from_type_name_and_id( + EntityTypeName::from_str("Resource")?, + EntityId::from_str("resource")?, + )) } fn context_from( -- cgit v1.2.3 From 6c6f1a7225022ae285bd6603aa0a2a81afc8baf3 Mon Sep 17 00:00:00 2001 From: mo khan Date: Fri, 4 Jul 2025 18:39:27 -0600 Subject: refactor: move hard coded checks with cedar policy --- etc/authzd/policy0.cedar | 12 ++++++++++++ src/authorization/cedar_authorizer.rs | 28 +++++----------------------- 2 files changed, 17 insertions(+), 23 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/etc/authzd/policy0.cedar b/etc/authzd/policy0.cedar index 034e81b5..56457622 100644 --- a/etc/authzd/policy0.cedar +++ b/etc/authzd/policy0.cedar @@ -18,3 +18,15 @@ when { context.path like "*.html" ) }; + +permit(principal, action, resource) +when { + context has host && context has method && context has path && ( + context.host == "sparkle.staging.runway.gitlab.net" && + context.method == "GET" && ( + context.path == "/" || + context.path == "/app.js" || + context.path == "/callback" + ) + ) +}; diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index f90e8d8b..96a406d8 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -78,27 +78,6 @@ impl Authorizer for CedarAuthorizer { "Processing HTTP request" ); - if http_request.host == "sparkle.staging.runway.gitlab.net" - && http_request.method == "GET" - && http_request.path == "/" - { - return true; - } - - if http_request.host == "sparkle.staging.runway.gitlab.net" - && http_request.method == "GET" - && http_request.path == "/application.js" - { - return true; - } - - if http_request.host == "sparkle.staging.runway.gitlab.net" - && http_request.method == "GET" - && http_request.path == "/callback" - { - return true; - } - match self.map_from(http_request.clone()) { Ok(cedar_request) => { let entities = Entities::empty(); @@ -109,6 +88,7 @@ impl Authorizer for CedarAuthorizer { matches!(response.decision(), cedar_policy::Decision::Allow) } Err(e) => { + println!("error: {}", e); tracing::error!( error = %e, path = %http_request.path, @@ -128,9 +108,9 @@ impl CedarAuthorizer { let principal = self.principal_from(&http_request)?; let permission = self.permission_from(&http_request)?; let resource = self.resource_from(&http_request)?; - let context = self.context_from(http_request); + let context = self.context_from(http_request)?; - CedarRequest::new(principal, permission, resource, context?, None) + CedarRequest::new(principal, permission, resource, context, None) .map_err(|e| Box::new(e) as Box) } @@ -171,6 +151,8 @@ impl CedarAuthorizer { let mut items = std::collections::HashMap::new(); items.insert("bearer_token".to_string(), self.token_from(&http_request)); + items.insert("host".to_string(), self.safe_string(&http_request.host)); + items.insert("method".to_string(), self.safe_string(&http_request.method)); items.insert("path".to_string(), self.safe_string(&http_request.path)); Context::from_pairs(items.into_iter().collect::>()) -- cgit v1.2.3 From fc4bbd8efd805411239406c6323a37537d4534f2 Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 5 Jul 2025 11:29:37 -0600 Subject: fix: fix typo in cedar policy file --- etc/authzd/policy0.cedar | 1 + src/authorization/cedar_authorizer.rs | 110 +++++++++++++-------------- tests/authorization/cedar_authorizer_test.rs | 18 +++-- tests/authorization/check_service_test.rs | 4 +- 4 files changed, 68 insertions(+), 65 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/etc/authzd/policy0.cedar b/etc/authzd/policy0.cedar index 75cf8178..e1037457 100644 --- a/etc/authzd/policy0.cedar +++ b/etc/authzd/policy0.cedar @@ -44,6 +44,7 @@ when { ) || ( context.method == "POST" && ( context.path == "/sparkles/restore" + ) ) ) }; diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 96a406d8..9fb7513a 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -49,58 +49,7 @@ impl CedarAuthorizer { Ok(policies) } -} - -impl Default for CedarAuthorizer { - fn default() -> Self { - Self::new_from(std::path::Path::new("/etc/authzd")) - } -} - -impl Authorizer for CedarAuthorizer { - fn authorize(&self, request: CheckRequest) -> bool { - let http_request = match request - .attributes - .as_ref() - .and_then(|attr| attr.request.as_ref()) - .and_then(|req| req.http.as_ref()) - { - Some(http) => http, - None => return false, - }; - - tracing::info!( - method = %http_request.method, - host = %http_request.host, - path = %http_request.path, - scheme = %http_request.scheme, - protocol = %http_request.protocol, - "Processing HTTP request" - ); - match self.map_from(http_request.clone()) { - Ok(cedar_request) => { - let entities = Entities::empty(); - let response = - self.authorizer - .is_authorized(&cedar_request, &self.policies, &entities); - - matches!(response.decision(), cedar_policy::Decision::Allow) - } - Err(e) => { - println!("error: {}", e); - tracing::error!( - error = %e, - path = %http_request.path, - "Failed to create Cedar request" - ); - false - } - } - } -} - -impl CedarAuthorizer { fn map_from( &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, @@ -110,8 +59,9 @@ impl CedarAuthorizer { let resource = self.resource_from(&http_request)?; let context = self.context_from(http_request)?; - CedarRequest::new(principal, permission, resource, context, None) - .map_err(|e| Box::new(e) as Box) + Ok(CedarRequest::new( + principal, permission, resource, context, None, + )?) } fn principal_from( @@ -147,7 +97,7 @@ impl CedarAuthorizer { fn context_from( &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, - ) -> Result { + ) -> Result> { let mut items = std::collections::HashMap::new(); items.insert("bearer_token".to_string(), self.token_from(&http_request)); @@ -155,7 +105,7 @@ impl CedarAuthorizer { items.insert("method".to_string(), self.safe_string(&http_request.method)); items.insert("path".to_string(), self.safe_string(&http_request.path)); - Context::from_pairs(items.into_iter().collect::>()) + Ok(Context::from_pairs(items.into_iter().collect::>())?) } fn token_from( @@ -175,3 +125,53 @@ impl CedarAuthorizer { cedar_policy::RestrictedExpression::new_string(item.to_string()) } } + +impl Default for CedarAuthorizer { + fn default() -> Self { + Self::new_from(std::path::Path::new("/etc/authzd")) + } +} + +impl Authorizer for CedarAuthorizer { + fn authorize(&self, request: CheckRequest) -> bool { + let http_request = match request + .attributes + .as_ref() + .and_then(|attr| attr.request.as_ref()) + .and_then(|req| req.http.as_ref()) + { + Some(http) => http, + None => return false, + }; + + tracing::info!( + method = %http_request.method, + host = %http_request.host, + path = %http_request.path, + scheme = %http_request.scheme, + protocol = %http_request.protocol, + "Processing HTTP request" + ); + + let entities = Entities::empty(); + + match self.map_from(http_request.clone()) { + Ok(cedar_request) => { + let response = + self.authorizer + .is_authorized(&cedar_request, &self.policies, &entities); + + matches!(response.decision(), cedar_policy::Decision::Allow) + } + Err(e) => { + println!("error: {}", e); + tracing::error!( + error = %e, + path = %http_request.path, + "Failed to create Cedar request" + ); + false + } + } + } +} diff --git a/tests/authorization/cedar_authorizer_test.rs b/tests/authorization/cedar_authorizer_test.rs index 317ef67f..ccf8a1f8 100644 --- a/tests/authorization/cedar_authorizer_test.rs +++ b/tests/authorization/cedar_authorizer_test.rs @@ -5,16 +5,18 @@ mod tests { use envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest; use std::collections::HashMap; + fn subject() -> authzd::CedarAuthorizer { + build_cedar_authorizer() + } + #[test] fn test_cedar_authorizer_allows_valid_token() { - let request = build_request(|item: &mut HttpRequest| { + assert!(subject().authorize(build_request(|item: &mut HttpRequest| { item.headers = build_headers(vec![( "authorization".to_string(), "Bearer valid-token".to_string(), )]); - }); - - assert!(build_cedar_authorizer().authorize(request)); + }))); } #[test] @@ -26,7 +28,7 @@ mod tests { )]); }); - assert!(!build_cedar_authorizer().authorize(request)); + assert!(!subject().authorize(request)); } #[test] @@ -35,7 +37,7 @@ mod tests { item.headers = HashMap::new(); }); - assert!(!build_cedar_authorizer().authorize(request)); + assert!(!subject().authorize(request)); } #[test] @@ -55,7 +57,7 @@ mod tests { ]); }); - assert!(build_cedar_authorizer().authorize(request)); + assert!(subject().authorize(request)); } #[test] @@ -75,6 +77,6 @@ mod tests { ]); }); - assert!(build_cedar_authorizer().authorize(request)); + assert!(subject().authorize(request)); } } diff --git a/tests/authorization/check_service_test.rs b/tests/authorization/check_service_test.rs index 5ea0cb95..a32f2a2c 100644 --- a/tests/authorization/check_service_test.rs +++ b/tests/authorization/check_service_test.rs @@ -224,13 +224,13 @@ mod tests { "GET", "/dashboard", "sparkle.staging.runway.gitlab.net", - tonic::Code::PermissionDenied, + tonic::Code::Unauthenticated, ), ( "POST", "/sparkles", "sparkle.staging.runway.gitlab.net", - tonic::Code::PermissionDenied, + tonic::Code::Unauthenticated, ), ]; -- cgit v1.2.3 From 2c46c12427c6ae44e6ca96e6cef7522e4435482d Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 5 Jul 2025 11:58:02 -0600 Subject: chore: log the decision and diagnostics --- src/authorization/cedar_authorizer.rs | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 9fb7513a..db54aaed 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -10,13 +10,16 @@ use std::str::FromStr; #[derive(Debug)] pub struct CedarAuthorizer { policies: PolicySet, + entities: cedar_policy::Entities, authorizer: CedarAuth, } impl CedarAuthorizer { pub fn new(policies: cedar_policy::PolicySet) -> CedarAuthorizer { + let entities = Entities::empty(); CedarAuthorizer { policies, + entities, authorizer: CedarAuth::new(), } } @@ -31,7 +34,6 @@ impl CedarAuthorizer { } let mut policies = PolicySet::new(); - for entry in fs::read_dir(path)? { let file_path = entry?.path(); @@ -144,24 +146,26 @@ impl Authorizer for CedarAuthorizer { None => return false, }; - tracing::info!( - method = %http_request.method, - host = %http_request.host, - path = %http_request.path, - scheme = %http_request.scheme, - protocol = %http_request.protocol, - "Processing HTTP request" - ); - - let entities = Entities::empty(); - match self.map_from(http_request.clone()) { Ok(cedar_request) => { let response = self.authorizer - .is_authorized(&cedar_request, &self.policies, &entities); + .is_authorized(&cedar_request, &self.policies, &self.entities); + + let decision = response.decision(); + + tracing::info!( + method = %http_request.method, + host = %http_request.host, + path = %http_request.path, + scheme = %http_request.scheme, + protocol = %http_request.protocol, + decision = ?decision, + diagnostics = ?response.diagnostics(), + "Processing HTTP request" + ); - matches!(response.decision(), cedar_policy::Decision::Allow) + matches!(decision, cedar_policy::Decision::Allow) } Err(e) => { println!("error: {}", e); -- cgit v1.2.3 From 836e6658fabdab957ab2ce7be973a5de31247750 Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 5 Jul 2025 12:12:56 -0600 Subject: refactor: provide cedar entities in constructor --- src/authorization/cedar_authorizer.rs | 19 ++++++++++++------- tests/support/factory_bot.rs | 2 +- 2 files changed, 13 insertions(+), 8 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index db54aaed..4b697680 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -9,14 +9,16 @@ use std::str::FromStr; #[derive(Debug)] pub struct CedarAuthorizer { - policies: PolicySet, - entities: cedar_policy::Entities, authorizer: CedarAuth, + entities: cedar_policy::Entities, + policies: PolicySet, } impl CedarAuthorizer { - pub fn new(policies: cedar_policy::PolicySet) -> CedarAuthorizer { - let entities = Entities::empty(); + pub fn new( + policies: cedar_policy::PolicySet, + entities: cedar_policy::Entities, + ) -> CedarAuthorizer { CedarAuthorizer { policies, entities, @@ -24,8 +26,11 @@ impl CedarAuthorizer { } } - pub fn new_from(path: &std::path::Path) -> CedarAuthorizer { - Self::new(Self::load_from(path).unwrap_or_else(|_| PolicySet::default())) + pub fn new_from(path: &std::path::Path, entities: cedar_policy::Entities) -> CedarAuthorizer { + Self::new( + Self::load_from(path).unwrap_or_else(|_| PolicySet::default()), + entities, + ) } fn load_from(path: &std::path::Path) -> Result> { @@ -130,7 +135,7 @@ impl CedarAuthorizer { impl Default for CedarAuthorizer { fn default() -> Self { - Self::new_from(std::path::Path::new("/etc/authzd")) + Self::new_from(std::path::Path::new("/etc/authzd"), Entities::empty()) } } diff --git a/tests/support/factory_bot.rs b/tests/support/factory_bot.rs index 15c6f1f3..051b248c 100644 --- a/tests/support/factory_bot.rs +++ b/tests/support/factory_bot.rs @@ -39,7 +39,7 @@ pub fn build_headers(headers: Vec<(String, String)>) -> HashMap pub fn build_cedar_authorizer() -> authzd::CedarAuthorizer { let realpath = std::fs::canonicalize("./etc/authzd").unwrap(); let path = realpath.as_path(); - authzd::CedarAuthorizer::new_from(path) + authzd::CedarAuthorizer::new_from(path, cedar_policy::Entities::empty()) } pub async fn build_channel(addr: SocketAddr) -> Channel { -- cgit v1.2.3 From a9be59c733e63b57bf872bdc82495a6d93308577 Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 5 Jul 2025 12:16:04 -0600 Subject: refactor: remove cedar aliases --- src/authorization/cedar_authorizer.rs | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 4b697680..5fe0dd64 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -1,17 +1,13 @@ use super::authorizer::Authorizer; -use cedar_policy::{ - Authorizer as CedarAuth, Context, Entities, EntityId, EntityTypeName, EntityUid, PolicySet, - Request as CedarRequest, -}; -use envoy_types::ext_authz::v3::pb::CheckRequest; +use cedar_policy::{Context, Entities, EntityId, EntityTypeName, EntityUid}; use std::fs; use std::str::FromStr; #[derive(Debug)] pub struct CedarAuthorizer { - authorizer: CedarAuth, + authorizer: cedar_policy::Authorizer, entities: cedar_policy::Entities, - policies: PolicySet, + policies: cedar_policy::PolicySet, } impl CedarAuthorizer { @@ -22,30 +18,32 @@ impl CedarAuthorizer { CedarAuthorizer { policies, entities, - authorizer: CedarAuth::new(), + authorizer: cedar_policy::Authorizer::new(), } } pub fn new_from(path: &std::path::Path, entities: cedar_policy::Entities) -> CedarAuthorizer { Self::new( - Self::load_from(path).unwrap_or_else(|_| PolicySet::default()), + Self::load_from(path).unwrap_or_else(|_| cedar_policy::PolicySet::default()), entities, ) } - fn load_from(path: &std::path::Path) -> Result> { + fn load_from( + path: &std::path::Path, + ) -> Result> { if !path.exists() || !path.is_dir() { - return Ok(PolicySet::default()); + return Ok(cedar_policy::PolicySet::default()); } - let mut policies = PolicySet::new(); + let mut policies = cedar_policy::PolicySet::new(); for entry in fs::read_dir(path)? { let file_path = entry?.path(); if let Some(extension) = file_path.extension() { if extension == "cedar" { let content = fs::read_to_string(&file_path)?; - let file_policies = PolicySet::from_str(&content)?; + let file_policies = cedar_policy::PolicySet::from_str(&content)?; for policy in file_policies.policies() { policies.add(policy.clone())?; @@ -60,13 +58,13 @@ impl CedarAuthorizer { fn map_from( &self, http_request: envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, - ) -> Result> { + ) -> Result> { let principal = self.principal_from(&http_request)?; let permission = self.permission_from(&http_request)?; let resource = self.resource_from(&http_request)?; let context = self.context_from(http_request)?; - Ok(CedarRequest::new( + Ok(cedar_policy::Request::new( principal, permission, resource, context, None, )?) } @@ -140,7 +138,7 @@ impl Default for CedarAuthorizer { } impl Authorizer for CedarAuthorizer { - fn authorize(&self, request: CheckRequest) -> bool { + fn authorize(&self, request: envoy_types::ext_authz::v3::pb::CheckRequest) -> bool { let http_request = match request .attributes .as_ref() -- cgit v1.2.3 From 3b6b2b3029e0b9ba185028db0eb77a3d46998a5c Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 5 Jul 2025 12:18:58 -0600 Subject: refactor: inline cedar policy namespace --- src/authorization/cedar_authorizer.rs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 5fe0dd64..6b901e5d 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -1,5 +1,4 @@ use super::authorizer::Authorizer; -use cedar_policy::{Context, Entities, EntityId, EntityTypeName, EntityUid}; use std::fs; use std::str::FromStr; @@ -73,9 +72,9 @@ impl CedarAuthorizer { &self, _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { - Ok(EntityUid::from_type_name_and_id( - EntityTypeName::from_str("User")?, - EntityId::from_str("client")?, + Ok(cedar_policy::EntityUid::from_type_name_and_id( + cedar_policy::EntityTypeName::from_str("User")?, + cedar_policy::EntityId::from_str("client")?, )) } @@ -83,9 +82,9 @@ impl CedarAuthorizer { &self, _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { - Ok(EntityUid::from_type_name_and_id( - EntityTypeName::from_str("Action")?, - EntityId::from_str("check")?, + Ok(cedar_policy::EntityUid::from_type_name_and_id( + cedar_policy::EntityTypeName::from_str("Action")?, + cedar_policy::EntityId::from_str("check")?, )) } @@ -93,9 +92,9 @@ impl CedarAuthorizer { &self, _http_request: &envoy_types::pb::envoy::service::auth::v3::attribute_context::HttpRequest, ) -> Result> { - Ok(EntityUid::from_type_name_and_id( - EntityTypeName::from_str("Resource")?, - EntityId::from_str("resource")?, + Ok(cedar_policy::EntityUid::from_type_name_and_id( + cedar_policy::EntityTypeName::from_str("Resource")?, + cedar_policy::EntityId::from_str("resource")?, )) } @@ -110,7 +109,9 @@ impl CedarAuthorizer { items.insert("method".to_string(), self.safe_string(&http_request.method)); items.insert("path".to_string(), self.safe_string(&http_request.path)); - Ok(Context::from_pairs(items.into_iter().collect::>())?) + Ok(cedar_policy::Context::from_pairs( + items.into_iter().collect::>(), + )?) } fn token_from( @@ -133,7 +134,10 @@ impl CedarAuthorizer { impl Default for CedarAuthorizer { fn default() -> Self { - Self::new_from(std::path::Path::new("/etc/authzd"), Entities::empty()) + Self::new_from( + std::path::Path::new("/etc/authzd"), + cedar_policy::Entities::empty(), + ) } } -- cgit v1.2.3 From a0594f92033f2e9a09ba69261421684b9bf57185 Mon Sep 17 00:00:00 2001 From: mo khan Date: Sat, 5 Jul 2025 13:16:23 -0600 Subject: chore: remove println! --- src/authorization/cedar_authorizer.rs | 1 - 1 file changed, 1 deletion(-) (limited to 'src/authorization/cedar_authorizer.rs') diff --git a/src/authorization/cedar_authorizer.rs b/src/authorization/cedar_authorizer.rs index 6b901e5d..64287414 100644 --- a/src/authorization/cedar_authorizer.rs +++ b/src/authorization/cedar_authorizer.rs @@ -175,7 +175,6 @@ impl Authorizer for CedarAuthorizer { matches!(decision, cedar_policy::Decision::Allow) } Err(e) => { - println!("error: {}", e); tracing::error!( error = %e, path = %http_request.path, -- cgit v1.2.3