gmunozfe commented on code in PR #4021: URL: https://github.com/apache/incubator-kie-kogito-runtimes/pull/4021#discussion_r2565209307
########## quarkus/addons/jwt-parser/runtime/src/main/java/org/kie/kogito/addons/jwt/JwtParserWorkItemHandler.java: ########## @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.kogito.addons.jwt; + +import java.util.Map; +import java.util.Optional; + +import org.kie.kogito.internal.process.workitem.KogitoWorkItem; +import org.kie.kogito.internal.process.workitem.KogitoWorkItemHandler; +import org.kie.kogito.internal.process.workitem.KogitoWorkItemManager; +import org.kie.kogito.internal.process.workitem.WorkItemTransition; +import org.kie.kogito.jackson.utils.JsonObjectUtils; +import org.kie.kogito.process.workitems.impl.DefaultKogitoWorkItemHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; + +/** + * WorkItem handler for JWT token parsing operations in SonataFlow + */ +public class JwtParserWorkItemHandler extends DefaultKogitoWorkItemHandler { + + public static final String NAME = "jwt-parser"; + public static final String TOKEN_PARAM = "token"; + public static final String CLAIM_PARAM = "claim"; + public static final String OPERATION_PARAM = "operation"; + + // Operations + public static final String PARSE_OPERATION = "parse"; + public static final String EXTRACT_USER_OPERATION = "extractUser"; + public static final String EXTRACT_CLAIM_OPERATION = "extractClaim"; + + private static final Logger logger = LoggerFactory.getLogger(JwtParserWorkItemHandler.class); + + private final JwtTokenParser jwtTokenParser; + + public JwtParserWorkItemHandler() { + this.jwtTokenParser = new JwtTokenParser(); + } + + public JwtParserWorkItemHandler(JwtTokenParser jwtTokenParser) { + this.jwtTokenParser = jwtTokenParser; + } + + @Override + public String getName() { + return NAME; + } + + @Override + public Optional<WorkItemTransition> activateWorkItemHandler(KogitoWorkItemManager manager, KogitoWorkItemHandler handler, KogitoWorkItem workItem, WorkItemTransition transition) { + try { + Map<String, Object> parameters = workItem.getParameters(); + String token = (String) parameters.get(TOKEN_PARAM); Review Comment: If token is not present or blank, it's better to detect it at this point, but it's a robustness check ########## quarkus/addons/jwt-parser/runtime/src/main/java/org/kie/kogito/addons/jwt/JwtTokenParser.java: ########## @@ -0,0 +1,118 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.kogito.addons.jwt; + +import java.util.Base64; + +import org.kie.kogito.jackson.utils.ObjectMapperFactory; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +/** + * JWT Token Parser utility for extracting claims from JWT tokens + * Used by SonataFlow workflows to parse JWT tokens and access claims + */ +public class JwtTokenParser { + + private static final String BEARER = "Bearer "; + + /** + * Parses a JWT token and returns the payload as a JsonNode + * + * @param token The JWT token string (can include "Bearer " prefix) + * @return JsonNode containing the JWT payload/claims + * @throws RuntimeException if token parsing fails + */ + public JsonNode parseToken(String token) { + if (token == null || token.trim().isEmpty()) { + throw new IllegalArgumentException("JWT token cannot be null or empty"); + } + + // Remove "Bearer " prefix if present + String cleanToken = token.startsWith(BEARER) ? token.substring(BEARER.length()) : token; + + try { + // Parse JWT token without signature verification (for claim extraction only) + // In production, you might want to verify signatures with proper keys + String[] parts = cleanToken.split("\\."); + if (parts.length != 3) { + throw new IllegalArgumentException("Invalid JWT token format"); + } + + // Decode the payload (second part) using Base64 + StringBuilder payloadBuilder = new StringBuilder(parts[1]); + // Add padding if necessary using StringBuilder for efficiency + while (payloadBuilder.length() % 4 != 0) { + payloadBuilder.append('='); + } + + // Parse the JSON payload directly from bytes using ObjectMapperFactory singleton + return ObjectMapperFactory.get().readTree(Base64.getUrlDecoder().decode(payloadBuilder.toString())); + + } catch (Exception e) { + throw new RuntimeException("Failed to parse JWT token: " + e.getMessage(), e); + } + } + + /** + * Extracts a specific claim from a JWT token + * + * @param token The JWT token string + * @param claimName The name of the claim to extract + * @return The claim value as a JsonNode, or null if not found + */ + public JsonNode extractClaim(String token, String claimName) { + JsonNode payload = parseToken(token); + return payload.get(claimName); + } + + /** + * Extracts user information from standard JWT claims + * + * @param token The JWT token string + * @return JsonNode containing user info (sub, preferred_username, email, etc.) + */ + public JsonNode extractUser(String token) { + JsonNode payload = parseToken(token); + ObjectNode userInfo = ObjectMapperFactory.get().createObjectNode(); + + // Standard JWT claims for user identification + if (payload.has("sub")) { + userInfo.set("sub", payload.get("sub")); + } + if (payload.has("preferred_username")) { + userInfo.set("preferred_username", payload.get("preferred_username")); + } + if (payload.has("email")) { + userInfo.set("email", payload.get("email")); + } + if (payload.has("name")) { + userInfo.set("name", payload.get("name")); + } + if (payload.has("given_name")) { + userInfo.set("given_name", payload.get("given_name")); + } + if (payload.has("family_name")) { + userInfo.set("family_name", payload.get("family_name")); + } Review Comment: This similar pattern could be isolated in a loop to be less verbose with better readibility and maintainability. ```suggestion String[] claims = { "sub", "preferred_username", "email", "name", "given_name", "family_name" }; for (String claim : claims) { if (payload.has(claim)) { userInfo.set(claim, payload.get(claim)); } } ``` ########## quarkus/addons/jwt-parser/runtime/src/main/java/org/kie/kogito/addons/jwt/JwtParserWorkItemHandler.java: ########## @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.kogito.addons.jwt; + +import java.util.Map; +import java.util.Optional; + +import org.kie.kogito.internal.process.workitem.KogitoWorkItem; +import org.kie.kogito.internal.process.workitem.KogitoWorkItemHandler; +import org.kie.kogito.internal.process.workitem.KogitoWorkItemManager; +import org.kie.kogito.internal.process.workitem.WorkItemTransition; +import org.kie.kogito.jackson.utils.JsonObjectUtils; +import org.kie.kogito.process.workitems.impl.DefaultKogitoWorkItemHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; + +/** + * WorkItem handler for JWT token parsing operations in SonataFlow + */ +public class JwtParserWorkItemHandler extends DefaultKogitoWorkItemHandler { + + public static final String NAME = "jwt-parser"; + public static final String TOKEN_PARAM = "token"; + public static final String CLAIM_PARAM = "claim"; + public static final String OPERATION_PARAM = "operation"; + + // Operations + public static final String PARSE_OPERATION = "parse"; + public static final String EXTRACT_USER_OPERATION = "extractUser"; + public static final String EXTRACT_CLAIM_OPERATION = "extractClaim"; + + private static final Logger logger = LoggerFactory.getLogger(JwtParserWorkItemHandler.class); + + private final JwtTokenParser jwtTokenParser; + + public JwtParserWorkItemHandler() { + this.jwtTokenParser = new JwtTokenParser(); + } + + public JwtParserWorkItemHandler(JwtTokenParser jwtTokenParser) { + this.jwtTokenParser = jwtTokenParser; + } + + @Override + public String getName() { + return NAME; + } + + @Override + public Optional<WorkItemTransition> activateWorkItemHandler(KogitoWorkItemManager manager, KogitoWorkItemHandler handler, KogitoWorkItem workItem, WorkItemTransition transition) { + try { + Map<String, Object> parameters = workItem.getParameters(); + String token = (String) parameters.get(TOKEN_PARAM); + String operation = (String) parameters.getOrDefault(OPERATION_PARAM, PARSE_OPERATION); + + logger.debug("Executing JWT parser operation: {}", operation); + + JsonNode result; + switch (operation.toLowerCase()) { + case EXTRACT_USER_OPERATION: + result = jwtTokenParser.extractUser(token); + break; + case EXTRACT_CLAIM_OPERATION: + String claimName = (String) parameters.get(CLAIM_PARAM); + if (claimName == null) { + throw new IllegalArgumentException("Claim name is required for extractClaim operation"); + } + result = jwtTokenParser.extractClaim(token, claimName); + break; + case PARSE_OPERATION: + default: + result = jwtTokenParser.parseToken(token); + break; + } + + // Complete the work item with the parsed result + // Use JsonObjectUtils.fromValue to ensure proper serialization for workflow data access + // Note: "Result" with capital R is the standard constant used by SonataFlow + return Optional.of(handler.completeTransition(workItem.getPhaseStatus(), Map.of("Result", JsonObjectUtils.fromValue(result)))); Review Comment: Instead of adding previous comment, you could use `SWFConstants.RESULT` ########## quarkus/addons/jwt-parser/runtime/src/main/java/org/kie/kogito/addons/jwt/JwtParserWorkItemHandler.java: ########## @@ -0,0 +1,104 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.kie.kogito.addons.jwt; + +import java.util.Map; +import java.util.Optional; + +import org.kie.kogito.internal.process.workitem.KogitoWorkItem; +import org.kie.kogito.internal.process.workitem.KogitoWorkItemHandler; +import org.kie.kogito.internal.process.workitem.KogitoWorkItemManager; +import org.kie.kogito.internal.process.workitem.WorkItemTransition; +import org.kie.kogito.jackson.utils.JsonObjectUtils; +import org.kie.kogito.process.workitems.impl.DefaultKogitoWorkItemHandler; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.databind.JsonNode; + +/** + * WorkItem handler for JWT token parsing operations in SonataFlow + */ +public class JwtParserWorkItemHandler extends DefaultKogitoWorkItemHandler { + + public static final String NAME = "jwt-parser"; + public static final String TOKEN_PARAM = "token"; + public static final String CLAIM_PARAM = "claim"; + public static final String OPERATION_PARAM = "operation"; + + // Operations + public static final String PARSE_OPERATION = "parse"; + public static final String EXTRACT_USER_OPERATION = "extractUser"; + public static final String EXTRACT_CLAIM_OPERATION = "extractClaim"; Review Comment: If comparison is done as lower case, probably it's better to have as lower here, wdyt? -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
