Skip to content

Commit

Permalink
Applied PR feedback.
Browse files Browse the repository at this point in the history
  • Loading branch information
vcolin7 committed Aug 16, 2024
1 parent ea24a07 commit e2ac44d
Show file tree
Hide file tree
Showing 6 changed files with 123 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.Key;
import java.security.KeyFactory;
Expand Down Expand Up @@ -199,8 +200,8 @@ private AccessToken getAccessTokenByHttpRequest() {
} else {
accessToken = AccessTokenUtil.getAccessToken(resource, managedIdentity);
}
} catch (Throwable t) {
LOGGER.log(WARNING, "Could not obtain access token to authenticate with.", t);
} catch (UnsupportedEncodingException e) {
LOGGER.log(WARNING, "Could not obtain access token to authenticate with.", e);
}

LOGGER.exiting("KeyVaultClient", "getAccessTokenByHttpRequest", accessToken);
Expand All @@ -214,6 +215,8 @@ private AccessToken getAccessTokenByHttpRequest() {
* @return The list of aliases.
*/
public List<String> getAliases() {
LOGGER.entering("KeyVaultClient", "getAliases");

ArrayList<String> result = new ArrayList<>();
HashMap<String, String> headers = new HashMap<>();

Expand All @@ -227,10 +230,9 @@ public List<String> getAliases() {

if (response != null) {
try {
certificateListResult =
(CertificateListResult) JsonConverterUtil.fromJson(CertificateListResult.class, response);
} catch (Throwable t) {
LOGGER.log(WARNING, "Failed to parse certificate list response");
certificateListResult = JsonConverterUtil.fromJson(CertificateListResult.class, response);
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse certificate list response", e);
}
}

Expand All @@ -248,6 +250,8 @@ public List<String> getAliases() {
}
}

LOGGER.exiting("KeyVaultClient", "getAliases", result);

return result;
}

Expand All @@ -258,6 +262,8 @@ public List<String> getAliases() {
* @return The certificate bundle.
*/
private CertificateBundle getCertificateBundle(String alias) {
LOGGER.entering("KeyVaultClient", "getCertificateBundle", alias);

CertificateBundle result = null;
HashMap<String, String> headers = new HashMap<>();

Expand All @@ -268,12 +274,14 @@ private CertificateBundle getCertificateBundle(String alias) {

if (response != null) {
try {
result = (CertificateBundle) JsonConverterUtil.fromJson(CertificateBundle.class, response);
} catch (Throwable t) {
LOGGER.log(WARNING, "Failed to parse certificate bundle response");
result = JsonConverterUtil.fromJson(CertificateBundle.class, response);
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse certificate bundle response", e);
}
}

LOGGER.exiting("KeyVaultClient", "getCertificateBundle", result);

return result;
}

Expand Down Expand Up @@ -338,14 +346,16 @@ public Key getKey(String alias, char[] password) {
// Return KeyVaultPrivateKey if certificate is not exportable because if the service needs to obtain the
// private key for authentication, and we can't access private key(which is not exportable), we will use
// the Azure Key Vault Secrets API to obtain the private key (keyless).
LOGGER.exiting("KeyVaultClient", "getKey", null);

String keyType2 = keyType.contains("-HSM") ? keyType.substring(0, keyType.indexOf("-HSM")) : keyType;

return Optional.ofNullable(certificateBundle)
KeyVaultPrivateKey key = Optional.ofNullable(certificateBundle)
.map(CertificateBundle::getKid)
.map(kid -> new KeyVaultPrivateKey(keyType2, kid, this))
.orElse(null);

LOGGER.exiting("KeyVaultClient", "getKey", key);

return key;
}

String certificateSecretUri = certificateBundle.getSid();
Expand Down Expand Up @@ -374,10 +384,10 @@ public Key getKey(String alias, char[] password) {
String contentType = null;

try {
secretBundle = (SecretBundle) JsonConverterUtil.fromJson(SecretBundle.class, body);
secretBundle = JsonConverterUtil.fromJson(SecretBundle.class, body);
contentType = secretBundle.getContentType();
} catch (Throwable t) {
LOGGER.log(WARNING, "Failed to parse secret bundle response");
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse secret bundle response.", e);
}

if ("application/x-pkcs12".equals(contentType)) {
Expand All @@ -397,8 +407,8 @@ public Key getKey(String alias, char[] password) {
} else if ("application/x-pem-file".equals(contentType)) {
try {
key = createPrivateKeyFromPem(secretBundle.getValue(), keyType);
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException ex) {
LOGGER.log(WARNING, "Unable to decode key", ex);
} catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException | IllegalArgumentException e) {
LOGGER.log(WARNING, "Unable to decode key", e);
}
}

Expand All @@ -419,6 +429,8 @@ public Key getKey(String alias, char[] password) {
* @return Signature.
*/
public byte[] getSignedWithPrivateKey(String digestName, String digestValue, String keyId) {
LOGGER.entering("KeyVaultClient", "getSignedWithPrivateKey", new Object[] { digestName, digestValue, keyId });

SignResult result = null;
String bodyString = String.format("{\"alg\": \"" + digestName + "\", \"value\": \"%s\"}", digestValue);
Map<String, String> headers = new HashMap<>();
Expand All @@ -430,17 +442,23 @@ public byte[] getSignedWithPrivateKey(String digestName, String digestValue, Str

if (response != null) {
try {
result = (SignResult) JsonConverterUtil.fromJson(SignResult.class, response);
} catch (Throwable t) {
LOGGER.log(WARNING, "Failed to parse sign result response");
result = JsonConverterUtil.fromJson(SignResult.class, response);
} catch (IOException e) {
LOGGER.log(WARNING, "Failed to parse sign result response.", e);
}
}

byte[] signature;

if (result != null) {
return Base64.getUrlDecoder().decode(result.getValue());
signature = Base64.getUrlDecoder().decode(result.getValue());
} else {
signature = new byte[0];
}

return new byte[0];
LOGGER.exiting("KeyVaultClient", "getSignedWithPrivateKey", signature);

return signature;
}

/**
Expand All @@ -458,6 +476,8 @@ public byte[] getSignedWithPrivateKey(String digestName, String digestValue, Str
private PrivateKey createPrivateKeyFromPem(String pemString, String keyType)
throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {

LOGGER.entering("KeyVaultClient", "createPrivateKeyFromPem", new Object[] { pemString, keyType });

StringBuilder builder = new StringBuilder();

try (BufferedReader reader = new BufferedReader(new StringReader(pemString))) {
Expand All @@ -482,7 +502,10 @@ private PrivateKey createPrivateKeyFromPem(String pemString, String keyType)
byte[] bytes = Base64.getDecoder().decode(builder.toString());
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance(keyType);
PrivateKey privateKey = factory.generatePrivate(spec);

LOGGER.exiting("KeyVaultClient", "createPrivateKeyFromPem", privateKey);

return factory.generatePrivate(spec);
return privateKey;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ public boolean isExpired() {
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("accessToken", this.accessToken);
jsonWriter.writeNumberField("expiresIn", this.expiresIn);
jsonWriter.writeStringField("access_token", this.accessToken);
jsonWriter.writeNumberField("expires_in", this.expiresIn);

return jsonWriter.writeEndObject();
}
Expand All @@ -105,9 +105,9 @@ public static AccessToken fromJson(JsonReader jsonReader) throws IOException {

reader.nextToken();

if ("accessToken".equals(fieldName)) {
if ("access_token".equals(fieldName)) {
deserializedAccessToken.accessToken = reader.getString();
} else if ("expiresIn".equals(fieldName)) {
} else if ("expires_in".equals(fieldName)) {
deserializedAccessToken.expiresIn = reader.getLong();
} else {
reader.skipChildren();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,49 +16,56 @@
*/
public class CertificateListResult implements JsonSerializable<CertificateListResult> {
/**
* Stores the value.
* Stores the list of certificates.
*/
private List<CertificateItem> value;

/**
* Get the value.
* Stores the link to the next certificates page.
*/
private String nextLink;

/**
* Get the list of certificates in this page.
*
* @return the id.
* @return The list of certificates in this page.
*/
public List<CertificateItem> getValue() {
return value;
}

/**
* Set the value.
* Set the list of certificates in this page.
*
* @param value the value.
* @param value the list of certificates in this page.
*/
public void setValue(List<CertificateItem> value) {
this.value = value;
}

/**
* Get the NextLint
* @return the nextLink
* Get the link to the next certificates page.
*
* @return The link to the next certificates page.
*/
public String getNextLink() {
return nextLink;
}

/**
* Set the NextLink
* @param nextLink the nextLink
* Set the link to the next certificates page.
*
* @param nextLink The link to the next certificates page.
*/
public void setNextLink(String nextLink) {
this.nextLink = nextLink;
}

private String nextLink;

@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeArrayField("value", value, JsonWriter::writeJson);
jsonWriter.writeStringField("nextLink", nextLink);

return jsonWriter.writeEndObject();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ public void setValue(String value) {
@Override
public JsonWriter toJson(JsonWriter jsonWriter) throws IOException {
jsonWriter.writeStartObject();
jsonWriter.writeStringField("kid", kid);
jsonWriter.writeStringField("value", value);

return jsonWriter.writeEndObject();
}
Expand All @@ -80,8 +82,7 @@ public static SignResult fromJson(JsonReader jsonReader) throws IOException {
if ("kid".equals(fieldName)) {
deserializedSignResult.kid = reader.getString();
} else if ("value".equals(fieldName)) {
deserializedSignResult.value =
reader.getNullable(nonNullReader -> new Base64Url(nonNullReader.getString()).toString());
deserializedSignResult.value = new Base64Url(reader.getString()).toString();
} else {
reader.skipChildren();
}
Expand Down
Loading

0 comments on commit e2ac44d

Please sign in to comment.