Skip to content

[Rust-Axum][Breaking Changes] Extracting Claims in Cookie/Header #20097

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

Merged
merged 3 commits into from
Nov 14, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ public class RustAxumServerCodegen extends AbstractRustCodegen implements Codege

// Grouping (Method, Operation) by Path.
private final Map<String, ArrayList<MethodOperation>> pathMethodOpMap = new HashMap<>();
private boolean havingAuthMethods = false;

// Logger
private final Logger LOGGER = LoggerFactory.getLogger(RustAxumServerCodegen.class);
Expand Down Expand Up @@ -595,21 +596,26 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation

@Override
public OperationsMap postProcessOperationsWithModels(final OperationsMap operationsMap, List<ModelMap> allModels) {
OperationMap operations = operationsMap.getOperations();
final OperationMap operations = operationsMap.getOperations();
operations.put("classnamePascalCase", camelize(operations.getClassname()));
List<CodegenOperation> operationList = operations.getOperation();

for (CodegenOperation op : operationList) {
postProcessOperationWithModels(op);
final boolean hasAuthMethod = operations.getOperation().stream()
.map(this::postProcessOperationWithModels)
.reduce(false, (a, b) -> a || b);
if (hasAuthMethod) {
operations.put("havingAuthMethod", true);
operations.getOperation().forEach(op -> op.vendorExtensions.put("havingAuthMethod", true));
this.havingAuthMethods = true;
}

return operationsMap;
}

private void postProcessOperationWithModels(final CodegenOperation op) {
private boolean postProcessOperationWithModels(final CodegenOperation op) {
boolean consumesJson = false;
boolean consumesPlainText = false;
boolean consumesFormUrlEncoded = false;
boolean hasAuthMethod = false;

if (op.consumes != null) {
for (Map<String, String> consume : op.consumes) {
Expand Down Expand Up @@ -666,17 +672,20 @@ private void postProcessOperationWithModels(final CodegenOperation op) {
for (CodegenSecurity s : op.authMethods) {
if (s.isApiKey && (s.isKeyInCookie || s.isKeyInHeader)) {
if (s.isKeyInCookie) {
op.vendorExtensions.put("x-has-cookie-auth-methods", "true");
op.vendorExtensions.put("x-api-key-cookie-name", toModelName(s.keyParamName));
op.vendorExtensions.put("x-has-cookie-auth-methods", true);
op.vendorExtensions.put("x-api-key-cookie-name", s.keyParamName);
} else {
op.vendorExtensions.put("x-has-header-auth-methods", "true");
op.vendorExtensions.put("x-api-key-header-name", toModelName(s.keyParamName));
op.vendorExtensions.put("x-has-header-auth-methods", true);
op.vendorExtensions.put("x-api-key-header-name", s.keyParamName);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug fix here. We must use keyParamName instead of transforming

}

op.vendorExtensions.put("x-has-auth-methods", "true");
op.vendorExtensions.put("x-has-auth-methods", true);
hasAuthMethod = true;
}
}
}

return hasAuthMethod;
}

@Override
Expand Down Expand Up @@ -772,6 +781,7 @@ public Map<String, Object> postProcessSupportingFileData(Map<String, Object> bun
.sorted(Comparator.comparing(a -> a.path))
.collect(Collectors.toList());
bundle.put("pathMethodOps", pathMethodOps);
if (havingAuthMethods) bundle.put("havingAuthMethods", true);

return super.postProcessSupportingFileData(bundle);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ conversion = [

[dependencies]
async-trait = "0.1"
axum = { version = "0.7" }
axum = "0.7"
axum-extra = { version = "0.9", features = ["cookie", "multipart"] }
base64 = "0.22"
bytes = "1"
Expand All @@ -62,7 +62,7 @@ tokio = { version = "1", default-features = false, features = [
] }
tracing = { version = "0.1", features = ["attributes"] }
uuid = { version = "1", features = ["serde"] }
validator = { version = "0.18", features = ["derive"] }
validator = { version = "0.19", features = ["derive"] }

[dev-dependencies]
tracing-subscriber = "0.3"
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,22 @@ pub mod {{classFilename}};
{{#isApiKey}}
{{#isKeyInCookie}}
/// Cookie Authentication.
#[async_trait::async_trait]
pub trait CookieAuthentication {
fn extract_token_from_cookie(&self, cookies: &axum_extra::extract::CookieJar, key: &str) -> Option<String>;
type Claims;

/// Extracting Claims from Cookie. Return None if the Claims is invalid.
async fn extract_claims_from_cookie(&self, cookies: &axum_extra::extract::CookieJar, key: &str) -> Option<Self::Claims>;
}
{{/isKeyInCookie}}
{{#isKeyInHeader}}
/// API Key Authentication - Header.
#[async_trait::async_trait]
pub trait ApiKeyAuthHeader {
fn extract_token_from_header(&self, headers: &axum::http::header::HeaderMap, key: &str) -> Option<String>;
type Claims;

/// Extracting Claims from Header. Return None if the Claims is invalid.
async fn extract_claims_from_header(&self, headers: &axum::http::header::HeaderMap, key: &str) -> Option<Self::Claims>;
}
{{/isKeyInHeader}}
{{/isApiKey}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ use crate::{models, types::*};
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait {{classnamePascalCase}} {
{{#havingAuthMethod}}
type Claims;

{{/havingAuthMethod}}
{{#operation}}
{{#summary}}
/// {{{.}}}.
Expand All @@ -31,12 +35,9 @@ pub trait {{classnamePascalCase}} {
host: Host,
cookies: CookieJar,
{{#vendorExtensions}}
{{#x-has-cookie-auth-methods}}
token_in_cookie: Option<String>,
{{/x-has-cookie-auth-methods}}
{{#x-has-header-auth-methods}}
token_in_header: Option<String>,
{{/x-has-header-auth-methods}}
{{#x-has-auth-methods}}
claims: Self::Claims,
{{/x-has-auth-methods}}
{{/vendorExtensions}}
{{#headerParams.size}}
header_params: models::{{{operationIdCamelCase}}}HeaderParams,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// {{{operationId}}} - {{{httpMethod}}} {{{basePathWithoutHost}}}{{{path}}}
#[tracing::instrument(skip_all)]
async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}<I, A>(
async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}<I, A{{#havingAuthMethod}}, C{{/havingAuthMethod}}>(
method: Method,
host: Host,
cookies: CookieJar,
Expand Down Expand Up @@ -54,25 +54,33 @@ async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}<I, A>(
) -> Result<Response, StatusCode>
where
I: AsRef<A> + Send + Sync,
A: apis::{{classFilename}}::{{classnamePascalCase}}{{#vendorExtensions}}{{#x-has-cookie-auth-methods}}+ apis::CookieAuthentication{{/x-has-cookie-auth-methods}}{{#x-has-header-auth-methods}}+ apis::ApiKeyAuthHeader{{/x-has-header-auth-methods}}{{/vendorExtensions}},
A: apis::{{classFilename}}::{{classnamePascalCase}}{{#havingAuthMethod}}<Claims = C>{{/havingAuthMethod}}{{#vendorExtensions}}{{#x-has-cookie-auth-methods}}+ apis::CookieAuthentication<Claims = C>{{/x-has-cookie-auth-methods}}{{#x-has-header-auth-methods}}+ apis::ApiKeyAuthHeader<Claims = C>{{/x-has-header-auth-methods}}{{/vendorExtensions}},
{
{{#vendorExtensions}}
{{#x-has-auth-methods}}
// Authentication
{{/x-has-auth-methods}}
{{#x-has-cookie-auth-methods}}
let token_in_cookie = api_impl.as_ref().extract_token_from_cookie(&cookies, "{{x-api-key-cookie-name}}");
let claims_in_cookie = api_impl.as_ref().extract_claims_from_cookie(&cookies, "{{x-api-key-cookie-name}}").await;
{{/x-has-cookie-auth-methods}}
{{#x-has-header-auth-methods}}
let token_in_header = api_impl.as_ref().extract_token_from_header(&headers, "{{x-api-key-header-name}}");
let claims_in_header = api_impl.as_ref().extract_claims_from_header(&headers, "{{x-api-key-header-name}}").await;
{{/x-has-header-auth-methods}}
{{#x-has-auth-methods}}
if let ({{#x-has-cookie-auth-methods}}None,{{/x-has-cookie-auth-methods}}{{#x-has-header-auth-methods}}None,{{/x-has-header-auth-methods}}) = ({{#x-has-cookie-auth-methods}}&token_in_cookie,{{/x-has-cookie-auth-methods}}{{#x-has-header-auth-methods}}&token_in_header,{{/x-has-header-auth-methods}}) {
let claims = None
{{#x-has-cookie-auth-methods}}
.or(claims_in_cookie)
{{/x-has-cookie-auth-methods}}
{{#x-has-header-auth-methods}}
.or(claims_in_header)
{{/x-has-header-auth-methods}}
;
let Some(claims) = claims else {
return Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
}
.status(StatusCode::UNAUTHORIZED)
.body(Body::empty())
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
};
{{/x-has-auth-methods}}
{{/vendorExtensions}}

Expand Down Expand Up @@ -182,12 +190,9 @@ where
host,
cookies,
{{#vendorExtensions}}
{{#x-has-cookie-auth-methods}}
token_in_cookie,
{{/x-has-cookie-auth-methods}}
{{#x-has-header-auth-methods}}
token_in_header,
{{/x-has-header-auth-methods}}
{{#x-has-auth-methods}}
claims,
{{/x-has-auth-methods}}
{{/vendorExtensions}}
{{#headerParams.size}}
header_params,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
/// Setup API Server.
pub fn new<I, A>(api_impl: I) -> Router
pub fn new<I, A{{#havingAuthMethods}}, C{{/havingAuthMethods}}>(api_impl: I) -> Router
where
I: AsRef<A> + Clone + Send + Sync + 'static,
A: {{#apiInfo}}{{#apis}}{{#operations}}apis::{{classFilename}}::{{classnamePascalCase}} + {{/operations}}{{/apis}}{{/apiInfo}}{{#authMethods}}{{#isApiKey}}{{#isKeyInCookie}}apis::CookieAuthentication + {{/isKeyInCookie}}{{#isKeyInHeader}}apis::ApiKeyAuthHeader + {{/isKeyInHeader}}{{/isApiKey}}{{/authMethods}}'static,
A: {{#apiInfo}}{{#apis}}{{#operations}}apis::{{classFilename}}::{{classnamePascalCase}}{{#havingAuthMethod}}<Claims = C>{{/havingAuthMethod}} + {{/operations}}{{/apis}}{{/apiInfo}}{{#authMethods}}{{#isApiKey}}{{#isKeyInCookie}}apis::CookieAuthentication<Claims = C> + {{/isKeyInCookie}}{{#isKeyInHeader}}apis::ApiKeyAuthHeader<Claims = C> + {{/isKeyInHeader}}{{/isApiKey}}{{/authMethods}}'static,
{{#havingAuthMethods}}C: Send + Sync + 'static,{{/havingAuthMethods}}
{
// build our application with a route
Router::new()
{{#pathMethodOps}}
.route("{{{basePathWithoutHost}}}{{{path}}}",
{{#methodOperations}}{{{method}}}({{{operationID}}}::<I, A>){{^-last}}.{{/-last}}{{/methodOperations}}
{{#methodOperations}}{{{method}}}({{{operationID}}}::<I, A{{#vendorExtensions}}{{#havingAuthMethod}}, C{{/havingAuthMethod}}{{/vendorExtensions}}>){{^-last}}.{{/-last}}{{/methodOperations}}
)
{{/pathMethodOps}}
.with_state(api_impl)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ conversion = [

[dependencies]
async-trait = "0.1"
axum = { version = "0.7" }
axum = "0.7"
axum-extra = { version = "0.9", features = ["cookie", "multipart"] }
base64 = "0.22"
bytes = "1"
Expand All @@ -40,7 +40,7 @@ tokio = { version = "1", default-features = false, features = [
] }
tracing = { version = "0.1", features = ["attributes"] }
uuid = { version = "1", features = ["serde"] }
validator = { version = "0.18", features = ["derive"] }
validator = { version = "0.19", features = ["derive"] }

[dev-dependencies]
tracing-subscriber = "0.3"
Original file line number Diff line number Diff line change
@@ -1,18 +1,26 @@
pub mod payments;

/// API Key Authentication - Header.
#[async_trait::async_trait]
pub trait ApiKeyAuthHeader {
fn extract_token_from_header(
type Claims;

/// Extracting Claims from Header. Return None if the Claims is invalid.
async fn extract_claims_from_header(
&self,
headers: &axum::http::header::HeaderMap,
key: &str,
) -> Option<String>;
) -> Option<Self::Claims>;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

User Impl this trait to extract Claims (e.g: JWT) from Header/Cookie.

}
/// Cookie Authentication.
#[async_trait::async_trait]
pub trait CookieAuthentication {
fn extract_token_from_cookie(
type Claims;

/// Extracting Claims from Cookie. Return None if the Claims is invalid.
async fn extract_claims_from_cookie(
&self,
cookies: &axum_extra::extract::CookieJar,
key: &str,
) -> Option<String>;
) -> Option<Self::Claims>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ pub enum PostMakePaymentResponse {
#[async_trait]
#[allow(clippy::ptr_arg)]
pub trait Payments {
type Claims;

/// Get payment method by id.
///
/// GetPaymentMethodById - GET /v71/paymentMethods/{id}
Expand Down Expand Up @@ -68,7 +70,7 @@ pub trait Payments {
method: Method,
host: Host,
cookies: CookieJar,
token_in_cookie: Option<String>,
claims: Self::Claims,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extracted Claims (in previous step) is injected into Operation. User then can do whatever he/she wants with the Claims (e.g: get AccountID from the Claims)

body: Option<models::Payment>,
) -> Result<PostMakePaymentResponse, ()>;
}
Loading
Loading