Skip to content

Commit

Permalink
Change tests to expect exception
Browse files Browse the repository at this point in the history
Signed-off-by: Craig Perkins <[email protected]>
  • Loading branch information
cwperks committed Oct 12, 2023
1 parent 83ab045 commit 7355de4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 9 deletions.
5 changes: 3 additions & 2 deletions src/main/java/org/opensearch/security/util/KeyUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.apache.logging.log4j.Logger;
import org.opensearch.OpenSearchSecurityException;
import org.opensearch.SpecialPermission;
Expand Down Expand Up @@ -68,10 +69,10 @@ public JwtParserBuilder run() {
}

if (Objects.nonNull(key)) {
return Jwts.parser().setSigningKey(key);
return Jwts.parser().verifyWith(Keys.hmacShaKeyFor(key.getEncoded()));
}

return Jwts.parser().setSigningKey(decoded);
return Jwts.parser().verifyWith(Keys.hmacShaKeyFor(decoded));
} catch (Throwable e) {
log.error("Error while creating JWT authenticator", e);
throw new OpenSearchSecurityException(e.toString(), e);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,14 @@
import org.junit.Assert;
import org.junit.Test;

import org.opensearch.OpenSearchSecurityException;
import org.opensearch.common.settings.Settings;
import org.opensearch.security.user.AuthCredentials;
import org.opensearch.security.util.FakeRestRequest;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

public class HTTPJwtAuthenticatorTest {

final static byte[] secretKeyBytes = new byte[1024];
Expand Down Expand Up @@ -68,13 +72,15 @@ public void testEmptyKey() throws Exception {

@Test
public void testBadKey() throws Exception {

final AuthCredentials credentials = extractCredentialsFromJwtHeader(
Settings.builder().put("signing_key", BaseEncoding.base64().encode(new byte[] { 1, 3, 3, 4, 3, 6, 7, 8, 3, 10 })),
Jwts.builder().setSubject("Leonard McCoy")
);

Assert.assertNull(credentials);
try {
final AuthCredentials credentials = extractCredentialsFromJwtHeader(
Settings.builder().put("signing_key", BaseEncoding.base64().encode(new byte[] { 1, 3, 3, 4, 3, 6, 7, 8, 3, 10 })),
Jwts.builder().setSubject("Leonard McCoy")
);
fail("Expected WeakKeyException");
} catch (OpenSearchSecurityException e) {
assertTrue("Expected error message to contain WeakKeyException", e.getMessage().contains("WeakKeyException"));
}
}

@Test
Expand Down

0 comments on commit 7355de4

Please sign in to comment.