Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow proc-macro to be used multiple times on the same endpoint #41

Merged
merged 3 commits into from
Jul 16, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

### Changed

- allow proc-macro to be used multiple times on the same endpoint #41

## [v3.0.1] - 2022-05-31
### Added
Expand Down
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ default = ["macro-check"]
macro-check = ["actix-grants-proc-macro"]

[dependencies]
actix-web = { version = "4.0", default-features = false, features = ["macros"] }
actix-web = { version = "4.3", default-features = false, features = ["macros"] }
actix-grants-proc-macro = { path = "./proc-macro", version = "2.0.1", optional = true }

[dev-dependencies]
actix-rt = "2"
serde = { version = "1.0", features = ["derive"] }
parse-display = "0.8.2"
2 changes: 1 addition & 1 deletion proc-macro/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ proc-macro2 = "1.0"
syn = { version = "1.0", features = ["full", "derive", "extra-traits"] }

[dev-dependencies]
actix-web = { version = "4.0", default-features = false }
actix-web = { version = "4.3", default-features = false }
actix-web-grants = { path = "../" }
9 changes: 6 additions & 3 deletions proc-macro/src/expand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,13 @@ impl ToTokens for HasPermissions {
.map(|t| t.to_token_stream())
.unwrap_or(quote! {String});

let arg_name = format!("_auth_details_{}", fn_args.len());
let arg_name = syn::Ident::new(&arg_name, Span::call_site());

let condition = if let Some(expr) = &self.args.secure {
quote!(if _auth_details_.#check_fn(&[#args]) && #expr)
quote!(if #arg_name.#check_fn(&[#args]) && #expr)
} else {
quote!(if _auth_details_.#check_fn(&[#args]))
quote!(if #arg_name.#check_fn(&[#args]))
};

let resp = if let Some(expr) = &self.args.error_fn {
Expand All @@ -89,7 +92,7 @@ impl ToTokens for HasPermissions {
let stream = quote! {
#(#fn_attrs)*
#func_vis #fn_async fn #fn_name #fn_generics(
_auth_details_: actix_web_grants::permissions::AuthDetails<#type_>,
#arg_name: actix_web_grants::permissions::AuthDetails<#type_>,
#fn_args
) -> actix_web::Either<#fn_output, actix_web::HttpResponse> {
use actix_web_grants::permissions::{PermissionsCheck, RolesCheck};
Expand Down
37 changes: 13 additions & 24 deletions tests/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,25 @@ use actix_web::error::ErrorUnauthorized;
use actix_web::http::header::{HeaderValue, AUTHORIZATION};
use actix_web::{test, Error};
use serde::Deserialize;
use std::fmt::{Display, Formatter};
use std::str::FromStr;

pub const ROLE_ADMIN: &str = "ROLE_ADMIN";
pub const ROLE_MANAGER: &str = "ROLE_MANAGER";

#[derive(PartialEq, Clone)]
#[derive(parse_display::Display, parse_display::FromStr, PartialEq, Clone)]
#[display(style = "SNAKE_CASE")]
pub enum Role {
ADMIN,
MANAGER,
}

#[derive(parse_display::Display, parse_display::FromStr, PartialEq, Clone)]
#[display(style = "SNAKE_CASE")]
pub enum Permission {
READ,
WRITE,
}

pub async fn extract(req: &ServiceRequest) -> Result<Vec<String>, Error> {
let auth_header: Option<&str> = req
.headers()
Expand All @@ -32,7 +40,7 @@ pub async fn extract(req: &ServiceRequest) -> Result<Vec<String>, Error> {
.ok_or_else(|| ErrorUnauthorized("Authorization header incorrect!"))
}

pub async fn enum_extract(req: &ServiceRequest) -> Result<Vec<Role>, Error> {
pub async fn enum_extract<T: FromStr>(req: &ServiceRequest) -> Result<Vec<T>, Error> {
let auth_header: Option<&str> = req
.headers()
.get(AUTHORIZATION)
Expand All @@ -44,8 +52,8 @@ pub async fn enum_extract(req: &ServiceRequest) -> Result<Vec<Role>, Error> {
.map(|header| {
header
.split(",")
.map(|name| name.into())
.collect::<Vec<Role>>()
.filter_map(|name| T::from_str(name).ok())
.collect::<Vec<T>>()
})
.ok_or_else(|| ErrorUnauthorized("Authorization header incorrect!"))
}
Expand All @@ -60,22 +68,3 @@ pub async fn test_body(resp: ServiceResponse, expected_body: &str) {
pub struct NamePayload {
pub name: Option<String>,
}

impl Display for Role {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Role::ADMIN => write!(f, "ADMIN"),
Role::MANAGER => write!(f, "MANAGER"),
}
}
}

impl From<&str> for Role {
fn from(value: &str) -> Self {
match value {
"ADMIN" => Role::ADMIN,
"MANAGER" => Role::MANAGER,
_ => panic!("Unexpected enum value"),
}
}
}
4 changes: 3 additions & 1 deletion tests/permissions_check/guard_check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ async fn get_user_response(uri: &str, role: &str) -> ServiceResponse {
async fn get_user_response_with_enum(uri: &str, role: &str) -> ServiceResponse {
let mut app = test::init_service(
App::new()
.wrap(GrantsMiddleware::with_extractor(common::enum_extract))
.wrap(GrantsMiddleware::with_extractor(
common::enum_extract::<Role>,
))
.service(
web::resource("/admin")
.to(|| async { HttpResponse::Ok().finish() })
Expand Down
4 changes: 3 additions & 1 deletion tests/permissions_check/manual_check/enum_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ async fn test_forbidden() {
async fn get_user_response(uri: &str, role: &str) -> ServiceResponse {
let mut app = test::init_service(
App::new()
.wrap(GrantsMiddleware::with_extractor(common::enum_extract))
.wrap(GrantsMiddleware::with_extractor(
common::enum_extract::<Role>,
))
.service(different_body)
.service(only_admin),
)
Expand Down
35 changes: 33 additions & 2 deletions tests/proc_macro/type_feature.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::common;
use crate::common::Permission;
use crate::common::Role::{self, ADMIN, MANAGER};
use actix_grants_proc_macro::has_permissions;
use actix_web::dev::ServiceResponse;
use actix_web::http::header::AUTHORIZATION;
use actix_web::http::StatusCode;
Expand Down Expand Up @@ -27,6 +29,14 @@ async fn incorrect_enum_secure() -> HttpResponse {
HttpResponse::Ok().finish()
}

// Combine different type of Role & Permissions
#[get("/role_and_permission_enums_secure")]
#[has_roles("ADMIN", type = "Role")]
#[has_permissions("Permission::WRITE", type = "Permission")]
async fn role_and_permission_enums_secure() -> HttpResponse {
HttpResponse::Ok().finish()
}

#[actix_rt::test]
async fn test_http_response_for_imported_enum() {
let test_admin = get_user_response("/imported_enum_secure", &ADMIN.to_string()).await;
Expand All @@ -36,6 +46,21 @@ async fn test_http_response_for_imported_enum() {
assert_eq!(StatusCode::FORBIDDEN, test_manager.status());
}

#[actix_rt::test]
async fn test_http_response_for_role_and_permission_enums() {
let test_admin_with_write = get_user_response(
"/role_and_permission_enums_secure",
&format!("{ADMIN},WRITE"),
)
.await;
// there is no `write` permission
let test_admin =
get_user_response("/role_and_permission_enums_secure", &ADMIN.to_string()).await;

assert_eq!(StatusCode::OK, test_admin_with_write.status());
assert_eq!(StatusCode::FORBIDDEN, test_admin.status());
}

#[actix_rt::test]
async fn test_http_response_for_full_path_enum() {
let test_admin = get_user_response("/full_path_enum_secure", &ADMIN.to_string()).await;
Expand All @@ -55,10 +80,16 @@ async fn test_incorrect_http_response() {
async fn get_user_response(uri: &str, role: &str) -> ServiceResponse {
let mut app = test::init_service(
App::new()
.wrap(GrantsMiddleware::with_extractor(common::enum_extract))
.wrap(GrantsMiddleware::with_extractor(
common::enum_extract::<Role>,
))
.wrap(GrantsMiddleware::with_extractor(
common::enum_extract::<Permission>,
))
.service(imported_path_enum_secure)
.service(full_path_enum_secure)
.service(incorrect_enum_secure),
.service(incorrect_enum_secure)
.service(role_and_permission_enums_secure),
)
.await;

Expand Down
Loading