Skip to content

Commit

Permalink
Spotless Apply
Browse files Browse the repository at this point in the history
Signed-off-by: Ryan Liang <jiallian@amazon.com>
  • Loading branch information
RyanL1997 committed Jun 29, 2023
1 parent 81b7818 commit 7546c05
Show file tree
Hide file tree
Showing 8 changed files with 46 additions and 43 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Check warning on line 36 in src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java#L36

Added line #L36 was not covered by tests
}
}

Expand Down
23 changes: 11 additions & 12 deletions src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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 {
Expand Down Expand Up @@ -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();
Expand All @@ -123,7 +122,7 @@ static JsonWebKey createJwkFromSettings(Settings settings) throws Exception {
}
}

//TODO:Getting roles from User
// TODO:Getting roles from User
public Map<String, String> prepareClaimsForUser(User user, ThreadPool threadPool) {
Map<String, String> claims = new HashMap<>();
this.threadContext = threadPool.getThreadContext();
Expand Down Expand Up @@ -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));
Expand All @@ -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())

Check warning on line 183 in src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java#L183

Added line #L183 was not covered by tests
+ "\n"
+ JwtUtils.claimsToJson(jwt.getClaims())

Check warning on line 185 in src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java

View check run for this annotation

Codecov / codecov/patch

src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java#L185

Added line #L185 was not covered by tests
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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();
Expand All @@ -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 {

Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand All @@ -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");
}
}
Expand All @@ -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 {
Expand All @@ -181,16 +181,15 @@ 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();

// 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);
Expand All @@ -207,8 +206,8 @@ private AuthCredentials extractCredentials0(final RestRequest request) {

final AuthCredentials ac = new AuthCredentials(subject, roles).markComplete();

for(Entry<String, Object> claim: claims.entrySet()) {
ac.addAttribute("attr.jwt."+claim.getKey(), String.valueOf(claim.getValue()));
for (Entry<String, Object> claim : claims.entrySet()) {
ac.addAttribute("attr.jwt." + claim.getKey(), String.valueOf(claim.getValue()));
}

return ac;
Expand All @@ -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;
Expand All @@ -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);
Expand All @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ public abstract class DynamicConfigModel {
public abstract List<ClientBlockRegistry<InetAddress>> getIpClientBlockRegistries();

public abstract Multimap<String, ClientBlockRegistry<String>> getAuthBackendClientBlockRegistries();

public abstract Settings getDynamicOnBehalfOfSettings();

protected final Map<String, String> authImplMap = new HashMap<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,8 +210,8 @@ public Multimap<String, ClientBlockRegistry<String>> 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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "]";
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 + "]";
}
}

Expand Down

0 comments on commit 7546c05

Please sign in to comment.