From 7546c056d97b47d243108e9154f7be12afd653d2 Mon Sep 17 00:00:00 2001 From: Ryan Liang Date: Thu, 29 Jun 2023 11:50:58 -0700 Subject: [PATCH] Spotless Apply Signed-off-by: Ryan Liang --- .../security/SecurityConfigurationTests.java | 1 - .../jwt/EncryptionDecryptionUtil.java | 3 +- .../security/authtoken/jwt/JwtVendor.java | 23 ++++---- .../http/HTTPOnBehalfOfJwtAuthenticator.java | 53 ++++++++++--------- .../securityconf/DynamicConfigModel.java | 1 + .../securityconf/DynamicConfigModelV7.java | 4 +- .../securityconf/impl/v6/ConfigV6.java | 2 +- .../securityconf/impl/v7/ConfigV7.java | 2 +- 8 files changed, 46 insertions(+), 43 deletions(-) diff --git a/src/integrationTest/java/org/opensearch/security/SecurityConfigurationTests.java b/src/integrationTest/java/org/opensearch/security/SecurityConfigurationTests.java index 458340eee9..b35495e23e 100644 --- a/src/integrationTest/java/org/opensearch/security/SecurityConfigurationTests.java +++ b/src/integrationTest/java/org/opensearch/security/SecurityConfigurationTests.java @@ -15,7 +15,6 @@ import java.util.Map; import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope; -import com.fasterxml.jackson.databind.JsonNode; import org.awaitility.Awaitility; import org.junit.BeforeClass; import org.junit.ClassRule; diff --git a/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java b/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java index 16d1248820..54461f6b7e 100644 --- a/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java +++ b/src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java @@ -33,8 +33,7 @@ public static String encrypt(final String secret, final String data) { byte[] cipherText = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); return Base64.getEncoder().encodeToString(cipherText); } catch (Exception e) { - throw new RuntimeException( - "Error occured while encrypting data", e); + throw new RuntimeException("Error occured while encrypting data", e); } } diff --git a/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java b/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java index 5328453c98..f2f59b111b 100644 --- a/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java +++ b/src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java @@ -49,7 +49,7 @@ public class JwtVendor { private JoseJwtProducer jwtProducer; private final LongSupplier timeProvider; - //TODO: Relocate/Remove them at once we make the descisions about the `roles` + // TODO: Relocate/Remove them at once we make the descisions about the `roles` private ConfigModel configModel; private ThreadContext threadContext; @@ -69,7 +69,7 @@ public JwtVendor(Settings settings) { timeProvider = System::currentTimeMillis; } - //For testing the expiration in the future + // For testing the expiration in the future public JwtVendor(Settings settings, final LongSupplier timeProvider) { JoseJwtProducer jwtProducer = new JoseJwtProducer(); try { @@ -109,8 +109,7 @@ static JsonWebKey createJwkFromSettings(Settings settings) throws Exception { Settings jwkSettings = settings.getAsSettings("jwt").getAsSettings("key"); if (jwkSettings.isEmpty()) { - throw new Exception( - "Settings for key is missing. Please specify at least the option signing_key with a shared secret."); + throw new Exception("Settings for key is missing. Please specify at least the option signing_key with a shared secret."); } JsonWebKey jwk = new JsonWebKey(); @@ -123,7 +122,7 @@ static JsonWebKey createJwkFromSettings(Settings settings) throws Exception { } } - //TODO:Getting roles from User + // TODO:Getting roles from User public Map prepareClaimsForUser(User user, ThreadPool threadPool) { Map claims = new HashMap<>(); this.threadContext = threadPool.getThreadContext(); @@ -166,7 +165,7 @@ public String createJwt(String issuer, String subject, String audience, Integer throw new Exception("The expiration time should be a positive integer"); } - //TODO: IF USER ENABLES THE BWC MODE, WE ARE EXPECTING TO SET PLAIN TEXT ROLE AS `dr` + // TODO: IF USER ENABLES THE BWC MODE, WE ARE EXPECTING TO SET PLAIN TEXT ROLE AS `dr` if (roles != null) { String listOfRoles = String.join(",", roles); jwtClaims.setProperty("er", EncryptionDecryptionUtil.encrypt(claimsEncryptionKey, listOfRoles)); @@ -178,12 +177,12 @@ public String createJwt(String issuer, String subject, String audience, Integer if (logger.isDebugEnabled()) { logger.debug( - "Created JWT: " - + encodedJwt - + "\n" - + jsonMapReaderWriter.toJson(jwt.getJwsHeaders()) - + "\n" - + JwtUtils.claimsToJson(jwt.getClaims()) + "Created JWT: " + + encodedJwt + + "\n" + + jsonMapReaderWriter.toJson(jwt.getJwsHeaders()) + + "\n" + + JwtUtils.claimsToJson(jwt.getClaims()) ); } diff --git a/src/main/java/org/opensearch/security/http/HTTPOnBehalfOfJwtAuthenticator.java b/src/main/java/org/opensearch/security/http/HTTPOnBehalfOfJwtAuthenticator.java index 1fabd0874c..c980956fb8 100644 --- a/src/main/java/org/opensearch/security/http/HTTPOnBehalfOfJwtAuthenticator.java +++ b/src/main/java/org/opensearch/security/http/HTTPOnBehalfOfJwtAuthenticator.java @@ -51,7 +51,7 @@ public class HTTPOnBehalfOfJwtAuthenticator implements HTTPAuthenticator { private static final Pattern BEARER = Pattern.compile("^\\s*Bearer\\s.*", Pattern.CASE_INSENSITIVE); private static final String BEARER_PREFIX = "bearer "; - //TODO: TO SEE IF WE NEED THE FINAL FOR FOLLOWING + // TODO: TO SEE IF WE NEED THE FINAL FOR FOLLOWING private JwtParser jwtParser; private String subjectKey; @@ -64,7 +64,7 @@ public HTTPOnBehalfOfJwtAuthenticator() { } // FOR TESTING - public HTTPOnBehalfOfJwtAuthenticator(String signingKey, String encryptionKey){ + public HTTPOnBehalfOfJwtAuthenticator(String signingKey, String encryptionKey) { this.signingKey = signingKey; this.encryptionKey = encryptionKey; init(); @@ -73,7 +73,7 @@ public HTTPOnBehalfOfJwtAuthenticator(String signingKey, String encryptionKey){ private void init() { try { - if(signingKey == null || signingKey.length() == 0) { + if (signingKey == null || signingKey.length() == 0) { log.error("signingKey must not be null or empty. JWT authentication will not work"); } else { @@ -95,7 +95,7 @@ private void init() { log.debug("No public ECDSA key, try other algos ({})", e.toString()); } - if(key != null) { + if (key != null) { jwtParser = Jwts.parser().setSigningKey(key); } else { jwtParser = Jwts.parser().setSigningKey(decoded); @@ -138,7 +138,7 @@ private AuthCredentials extractCredentials0(final RestRequest request) { String jwtToken = request.header(HttpHeaders.AUTHORIZATION); if (jwtToken == null || jwtToken.length() == 0) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("No JWT token found in '{}' header", HttpHeaders.AUTHORIZATION); } return null; @@ -149,10 +149,10 @@ private AuthCredentials extractCredentials0(final RestRequest request) { } final int index; - if((index = jwtToken.toLowerCase().indexOf(BEARER_PREFIX)) > -1) { //detect Bearer - jwtToken = jwtToken.substring(index+BEARER_PREFIX.length()); + if ((index = jwtToken.toLowerCase().indexOf(BEARER_PREFIX)) > -1) { // detect Bearer + jwtToken = jwtToken.substring(index + BEARER_PREFIX.length()); } else { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("No Bearer scheme found in header"); } } @@ -164,14 +164,14 @@ private AuthCredentials extractCredentials0(final RestRequest request) { final String audience = claims.getAudience(); - //TODO: GET ROLESCLAIM DEPENDING ON THE STATUS OF BWC MODE. ON: er / OFF: dr + // TODO: GET ROLESCLAIM DEPENDING ON THE STATUS OF BWC MODE. ON: er / OFF: dr Object rolesObject = null; String[] roles; try { rolesObject = claims.get("er"); } catch (Throwable e) { - log.debug("No encrypted role founded in the claim, continue searching for decrypted roles."); + log.debug("No encrypted role founded in the claim, continue searching for decrypted roles."); } try { @@ -181,8 +181,7 @@ private AuthCredentials extractCredentials0(final RestRequest request) { } if (rolesObject == null) { - log.warn( - "Failed to get roles from JWT claims. Check if this key is correct and available in the JWT payload."); + log.warn("Failed to get roles from JWT claims. Check if this key is correct and available in the JWT payload."); roles = new String[0]; } else { final String rolesClaim = rolesObject.toString(); @@ -190,7 +189,7 @@ private AuthCredentials extractCredentials0(final RestRequest request) { // Extracting roles based on the compatbility mode String decryptedRoles = rolesClaim; if (rolesObject == claims.get("er")) { - //TODO: WHERE TO GET THE ENCRYTION KEY + // TODO: WHERE TO GET THE ENCRYTION KEY decryptedRoles = EncryptionDecryptionUtil.decrypt(encryptionKey, rolesClaim); } roles = Arrays.stream(decryptedRoles.split(",")).map(String::trim).toArray(String[]::new); @@ -207,8 +206,8 @@ private AuthCredentials extractCredentials0(final RestRequest request) { final AuthCredentials ac = new AuthCredentials(subject, roles).markComplete(); - for(Entry claim: claims.entrySet()) { - ac.addAttribute("attr.jwt."+claim.getKey(), String.valueOf(claim.getValue())); + for (Entry claim : claims.entrySet()) { + ac.addAttribute("attr.jwt." + claim.getKey(), String.valueOf(claim.getValue())); } return ac; @@ -217,7 +216,7 @@ private AuthCredentials extractCredentials0(final RestRequest request) { log.error("Cannot authenticate user with JWT because of ", e); return null; } catch (Exception e) { - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Invalid or expired JWT token.", e); } return null; @@ -234,27 +233,33 @@ public String getType() { return "onbehalfof_jwt"; } - //TODO: Extract the audience (ext_id) and inject it into thread context + // TODO: Extract the audience (ext_id) and inject it into thread context protected String extractSubject(final Claims claims, final RestRequest request) { String subject = claims.getSubject(); - if(subjectKey != null) { + if (subjectKey != null) { // try to get roles from claims, first as Object to avoid having to catch the ExpectedTypeException Object subjectObject = claims.get(subjectKey, Object.class); - if(subjectObject == null) { + if (subjectObject == null) { log.warn("Failed to get subject from JWT claims, check if subject_key '{}' is correct.", subjectKey); return null; } // We expect a String. If we find something else, convert to String but issue a warning - if(!(subjectObject instanceof String)) { - log.warn("Expected type String in the JWT for subject_key {}, but value was '{}' ({}). Will convert this value to String.", subjectKey, subjectObject, subjectObject.getClass()); + if (!(subjectObject instanceof String)) { + log.warn( + "Expected type String in the JWT for subject_key {}, but value was '{}' ({}). Will convert this value to String.", + subjectKey, + subjectObject, + subjectObject.getClass() + ); } subject = String.valueOf(subjectObject); } return subject; } - private static PublicKey getPublicKey(final byte[] keyBytes, final String algo) throws NoSuchAlgorithmException, InvalidKeySpecException { + private static PublicKey getPublicKey(final byte[] keyBytes, final String algo) throws NoSuchAlgorithmException, + InvalidKeySpecException { X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance(algo); return kf.generatePublic(spec); @@ -263,8 +268,8 @@ private static PublicKey getPublicKey(final byte[] keyBytes, final String algo) @Subscribe public void onDynamicConfigModelChanged(DynamicConfigModel dcm) { - //TODO: #2615 FOR CONFIGURATION - //For Testing + // TODO: #2615 FOR CONFIGURATION + // For Testing signingKey = "abcd1234"; encryptionKey = RandomStringUtils.randomAlphanumeric(16); } diff --git a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModel.java b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModel.java index 9a7c7c40da..e3d10878da 100644 --- a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModel.java +++ b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModel.java @@ -104,6 +104,7 @@ public abstract class DynamicConfigModel { public abstract List> getIpClientBlockRegistries(); public abstract Multimap> getAuthBackendClientBlockRegistries(); + public abstract Settings getDynamicOnBehalfOfSettings(); protected final Map authImplMap = new HashMap<>(); diff --git a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java index facdadba98..a386e70093 100644 --- a/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java +++ b/src/main/java/org/opensearch/security/securityconf/DynamicConfigModelV7.java @@ -210,8 +210,8 @@ public Multimap> getAuthBackendClientBlockRe @Override public Settings getDynamicOnBehalfOfSettings() { return Settings.builder() - .put(Settings.builder().loadFromSource(config.dynamic.on_behalf_of.configAsJson(), XContentType.JSON).build()) - .build(); + .put(Settings.builder().loadFromSource(config.dynamic.on_behalf_of.configAsJson(), XContentType.JSON).build()) + .build(); } private void buildAAA() { diff --git a/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java b/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java index 8a27b20717..01375b1f97 100644 --- a/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java +++ b/src/main/java/org/opensearch/security/securityconf/impl/v6/ConfigV6.java @@ -384,7 +384,7 @@ public void setEncryptionKey(String encryptionKey) { @Override public String toString() { - return "OnBehalfOf [signing_key=" + signingKey + ", encryption_key=" + encryptionKey +"]"; + return "OnBehalfOf [signing_key=" + signingKey + ", encryption_key=" + encryptionKey + "]"; } } diff --git a/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java b/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java index f3e848049a..9052c40cda 100644 --- a/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java +++ b/src/main/java/org/opensearch/security/securityconf/impl/v7/ConfigV7.java @@ -513,7 +513,7 @@ public void setEncryptionKey(String encryptionKey) { @Override public String toString() { - return "OnBehalfOf [signing_key=" + signingKey + ", encryption_key=" + encryptionKey +"]"; + return "OnBehalfOf [signing_key=" + signingKey + ", encryption_key=" + encryptionKey + "]"; } }