-
Notifications
You must be signed in to change notification settings - Fork 274
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implements token handlers and tests #2787
Closed
stephen-crawford
wants to merge
3
commits into
opensearch-project:main
from
stephen-crawford:extensions
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
src/main/java/org/opensearch/security/authtoken/jwt/EncryptionDecryptionUtil.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
/* | ||
* SPDX-License-Identifier: Apache-2.0 | ||
* | ||
* The OpenSearch Contributors require contributions made to | ||
* this file be licensed under the Apache-2.0 license or a | ||
* compatible open source license. | ||
* | ||
* Modifications Copyright OpenSearch Contributors. See | ||
* GitHub history for details. | ||
*/ | ||
|
||
package org.opensearch.security.authtoken.jwt; | ||
|
||
import java.nio.charset.StandardCharsets; | ||
import java.util.Arrays; | ||
import java.util.Base64; | ||
|
||
import javax.crypto.Cipher; | ||
import javax.crypto.SecretKey; | ||
import javax.crypto.spec.SecretKeySpec; | ||
|
||
public class EncryptionDecryptionUtil { | ||
|
||
public static String encrypt(final String secret, final String data) { | ||
|
||
byte[] decodedKey = Base64.getDecoder().decode(secret); | ||
|
||
try { | ||
Cipher cipher = Cipher.getInstance("AES"); | ||
// rebuild key using SecretKeySpec | ||
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES"); | ||
cipher.init(Cipher.ENCRYPT_MODE, originalKey); | ||
byte[] cipherText = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8)); | ||
return Base64.getEncoder().encodeToString(cipherText); | ||
} catch (Exception e) { | ||
throw new RuntimeException("Error occurred while encrypting data", e); | ||
} | ||
} | ||
|
||
public static String decrypt(final String secret, final String encryptedString) { | ||
|
||
byte[] decodedKey = Base64.getDecoder().decode(secret); | ||
|
||
try { | ||
Cipher cipher = Cipher.getInstance("AES"); | ||
// rebuild key using SecretKeySpec | ||
SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES"); | ||
cipher.init(Cipher.DECRYPT_MODE, originalKey); | ||
byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString)); | ||
return new String(cipherText, StandardCharsets.UTF_8); | ||
} catch (Exception e) { | ||
throw new RuntimeException("Error occured while decrypting data", e); | ||
} | ||
} | ||
} |
191 changes: 191 additions & 0 deletions
191
src/main/java/org/opensearch/security/authtoken/jwt/JwtVendor.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,191 @@ | ||
/* | ||
* SPDX-License-Identifier: Apache-2.0 | ||
* | ||
* The OpenSearch Contributors require contributions made to | ||
* this file be licensed under the Apache-2.0 license or a | ||
* compatible open source license. | ||
* | ||
* Modifications Copyright OpenSearch Contributors. See | ||
* GitHub history for details. | ||
*/ | ||
|
||
package org.opensearch.security.authtoken.jwt; | ||
|
||
import java.time.Instant; | ||
import java.util.HashMap; | ||
import java.util.List; | ||
import java.util.Map; | ||
import java.util.Set; | ||
import java.util.function.LongSupplier; | ||
|
||
import com.google.common.base.Strings; | ||
import org.apache.cxf.jaxrs.json.basic.JsonMapObjectReaderWriter; | ||
import org.apache.cxf.rs.security.jose.jwk.JsonWebKey; | ||
import org.apache.cxf.rs.security.jose.jwk.KeyType; | ||
import org.apache.cxf.rs.security.jose.jwk.PublicKeyUse; | ||
import org.apache.cxf.rs.security.jose.jws.JwsUtils; | ||
import org.apache.cxf.rs.security.jose.jwt.JoseJwtProducer; | ||
import org.apache.cxf.rs.security.jose.jwt.JwtClaims; | ||
import org.apache.cxf.rs.security.jose.jwt.JwtToken; | ||
import org.apache.cxf.rs.security.jose.jwt.JwtUtils; | ||
import org.apache.logging.log4j.LogManager; | ||
import org.apache.logging.log4j.Logger; | ||
|
||
import org.opensearch.common.settings.Settings; | ||
import org.opensearch.common.transport.TransportAddress; | ||
import org.opensearch.common.util.concurrent.ThreadContext; | ||
import org.opensearch.security.securityconf.ConfigModel; | ||
import org.opensearch.security.support.ConfigConstants; | ||
import org.opensearch.security.user.User; | ||
import org.opensearch.threadpool.ThreadPool; | ||
|
||
public class JwtVendor { | ||
private static final Logger logger = LogManager.getLogger(JwtVendor.class); | ||
|
||
private static JsonMapObjectReaderWriter jsonMapReaderWriter = new JsonMapObjectReaderWriter(); | ||
|
||
private String claimsEncryptionKey; | ||
private JsonWebKey signingKey; | ||
private JoseJwtProducer jwtProducer; | ||
private final LongSupplier timeProvider; | ||
|
||
// TODO: Relocate/Remove them at once we make the descisions about the `roles` | ||
private ConfigModel configModel; | ||
private ThreadContext threadContext; | ||
|
||
public JwtVendor(Settings settings) { | ||
JoseJwtProducer jwtProducer = new JoseJwtProducer(); | ||
try { | ||
this.signingKey = createJwkFromSettings(settings); | ||
} catch (Exception e) { | ||
throw new RuntimeException(e); | ||
} | ||
this.jwtProducer = jwtProducer; | ||
if (settings.get("encryption_key") == null) { | ||
throw new RuntimeException("encryption_key cannot be null"); | ||
} else { | ||
this.claimsEncryptionKey = settings.get("encryption_key"); | ||
} | ||
timeProvider = System::currentTimeMillis; | ||
} | ||
|
||
// For testing the expiration in the future | ||
public JwtVendor(Settings settings, final LongSupplier timeProvider) { | ||
JoseJwtProducer jwtProducer = new JoseJwtProducer(); | ||
try { | ||
this.signingKey = createJwkFromSettings(settings); | ||
} catch (Exception e) { | ||
throw new RuntimeException(e); | ||
} | ||
this.jwtProducer = jwtProducer; | ||
if (settings.get("encryption_key") == null) { | ||
throw new RuntimeException("encryption_key cannot be null"); | ||
} else { | ||
this.claimsEncryptionKey = settings.get("encryption_key"); | ||
} | ||
this.timeProvider = timeProvider; | ||
} | ||
|
||
/* | ||
* The default configuration of this web key should be: | ||
* KeyType: OCTET | ||
* PublicKeyUse: SIGN | ||
* Encryption Algorithm: HS512 | ||
* */ | ||
static JsonWebKey createJwkFromSettings(Settings settings) throws Exception { | ||
String signingKey = settings.get("signing_key"); | ||
|
||
if (!Strings.isNullOrEmpty(signingKey)) { | ||
|
||
JsonWebKey jwk = new JsonWebKey(); | ||
|
||
jwk.setKeyType(KeyType.OCTET); | ||
jwk.setAlgorithm("HS512"); | ||
jwk.setPublicKeyUse(PublicKeyUse.SIGN); | ||
jwk.setProperty("k", signingKey); | ||
|
||
return jwk; | ||
} else { | ||
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."); | ||
} | ||
|
||
JsonWebKey jwk = new JsonWebKey(); | ||
|
||
for (String key : jwkSettings.keySet()) { | ||
jwk.setProperty(key, jwkSettings.get(key)); | ||
} | ||
|
||
return jwk; | ||
} | ||
} | ||
|
||
// TODO:Getting roles from User | ||
public Map<String, String> prepareClaimsForUser(User user, ThreadPool threadPool) { | ||
Map<String, String> claims = new HashMap<>(); | ||
this.threadContext = threadPool.getThreadContext(); | ||
final TransportAddress caller = threadContext.getTransient(ConfigConstants.OPENDISTRO_SECURITY_REMOTE_ADDRESS); | ||
Set<String> mappedRoles = mapRoles(user, caller); | ||
claims.put("sub", user.getName()); | ||
claims.put("roles", String.join(",", mappedRoles)); | ||
return claims; | ||
} | ||
|
||
public Set<String> mapRoles(final User user, final TransportAddress caller) { | ||
return this.configModel.mapSecurityRoles(user, caller); | ||
} | ||
|
||
public String createJwt(String issuer, String subject, String audience, Integer expirySeconds, List<String> roles) throws Exception { | ||
long timeMillis = timeProvider.getAsLong(); | ||
Instant now = Instant.ofEpochMilli(timeProvider.getAsLong()); | ||
|
||
jwtProducer.setSignatureProvider(JwsUtils.getSignatureProvider(signingKey)); | ||
JwtClaims jwtClaims = new JwtClaims(); | ||
JwtToken jwt = new JwtToken(jwtClaims); | ||
|
||
jwtClaims.setIssuer(issuer); | ||
|
||
jwtClaims.setIssuedAt(timeMillis); | ||
|
||
jwtClaims.setSubject(subject); | ||
|
||
jwtClaims.setAudience(audience); | ||
|
||
jwtClaims.setNotBefore(timeMillis); | ||
|
||
if (expirySeconds == null) { | ||
long expiryTime = timeProvider.getAsLong() + (300 * 1000); | ||
jwtClaims.setExpiryTime(expiryTime); | ||
} else if (expirySeconds > 0) { | ||
long expiryTime = timeProvider.getAsLong() + (expirySeconds * 1000); | ||
jwtClaims.setExpiryTime(expiryTime); | ||
} else { | ||
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` | ||
if (roles != null) { | ||
String listOfRoles = String.join(",", roles); | ||
jwtClaims.setProperty("er", EncryptionDecryptionUtil.encrypt(claimsEncryptionKey, listOfRoles)); | ||
} else { | ||
throw new Exception("Roles cannot be null"); | ||
} | ||
|
||
String encodedJwt = jwtProducer.processJwt(jwt); | ||
|
||
if (logger.isDebugEnabled()) { | ||
logger.debug( | ||
"Created JWT: " | ||
+ encodedJwt | ||
+ "\n" | ||
+ jsonMapReaderWriter.toJson(jwt.getJwsHeaders()) | ||
+ "\n" | ||
+ JwtUtils.claimsToJson(jwt.getClaims()) | ||
); | ||
} | ||
|
||
return encodedJwt; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
should we return some form of NoOp subject here instead of null?