From b27523b8a908a83cb9d69c5ec4c7f22f6645cd68 Mon Sep 17 00:00:00 2001 From: Manuel Blanco Date: Tue, 14 Nov 2023 07:18:27 -0300 Subject: [PATCH] [FEATURE] Implement Safe Casting in getPermissions Method (#13143) * [FEATURE] Implement Safe Casting in getPermissions Method This commit addresses a potential ClassCastException issue in the getPermissions method. Previously, the method executed a type cast from Object to Map without checking if this cast was safe, leading to a potential risk of runtime exceptions. Changes made: 1. Added a type check using 'instanceof' to ensure that the result from executeMethod.execute is indeed a Map before proceeding with the cast. 2. Iterated over the entries of the resultMap, and performed a safe cast for each key-value pair, ensuring they are of types String and Boolean, respectively. 3. In case the resultObject is not an instance of Map, the method now throws an IllegalStateException with a descriptive error message, including the unexpected object's class name. These changes enhance the robustness and reliability of the getPermissions method by preventing unsafe type casts and providing clearer error handling for unexpected types. * Run ./scripts/format.sh --------- Co-authored-by: Diego Molina --- .../selenium/safari/AddHasPermissions.java | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/java/src/org/openqa/selenium/safari/AddHasPermissions.java b/java/src/org/openqa/selenium/safari/AddHasPermissions.java index 7757579d7a113..96e49bdb54084 100644 --- a/java/src/org/openqa/selenium/safari/AddHasPermissions.java +++ b/java/src/org/openqa/selenium/safari/AddHasPermissions.java @@ -18,6 +18,7 @@ package org.openqa.selenium.safari; import com.google.auto.service.AutoService; +import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; import org.openqa.selenium.Capabilities; @@ -66,9 +67,21 @@ public void setPermissions(String permission, boolean value) { @Override public Map getPermissions() { - Map results = - (Map) executeMethod.execute(GET_PERMISSIONS, null); - return (Map) results.get("permissions"); + Object resultObject = executeMethod.execute(GET_PERMISSIONS, null); + + if (resultObject instanceof Map) { + Map resultMap = (Map) resultObject; + Map permissionMap = new HashMap<>(); + for (Map.Entry entry : resultMap.entrySet()) { + if (entry.getKey() instanceof String && entry.getValue() instanceof Boolean) { + permissionMap.put((String) entry.getKey(), (Boolean) entry.getValue()); + } + } + return permissionMap; + } else { + throw new IllegalStateException( + "Unexpected result type: " + resultObject.getClass().getName()); + } } }; }