Skip to content

Commit

Permalink
Merge pull request #5 from lilgreenbird/msal
Browse files Browse the repository at this point in the history
cleanup and exclude lib
  • Loading branch information
srnagar authored Oct 5, 2020
2 parents 9c28d98 + da75dcc commit 0d509af
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 62 deletions.
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ repositories {
dependencies {
compile 'org.osgi:org.osgi.core:6.0.0',
'org.osgi:org.osgi.compendium:5.0.0'
compileOnly 'com.azure:azure-security-keyvault-keys:4.2.0',
compileOnly 'com.azure:azure-security-keyvault-keys:4.2.1',
'com.azure:azure-identity:1.1.0',
'org.antlr:antlr4-runtime:4.7.2',
'com.google.code.gson:gson:2.8.6',
Expand All @@ -133,6 +133,6 @@ dependencies {
'com.google.code.gson:gson:2.8.6',
'org.bouncycastle:bcprov-jdk15on:1.65',
'com.azure:azure-security-keyvault-keys:4.2.0',
'com.azure:azure-identity:1.1.0',
'com.azure:azure-identity:1.1.3',
'com.h2database:h2:1.4.200'
}
8 changes: 7 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@

<!-- Driver Dependencies -->
<azure.keyvault.version>4.2.1</azure.keyvault.version>
<azure.identity.version>1.1.2</azure.identity.version>
<azure.identity.version>1.1.3</azure.identity.version>
<osgi.core.version>6.0.0</osgi.core.version>
<osgi.comp.version>5.0.0</osgi.comp.version>
<antlr.runtime.version>4.7.2</antlr.runtime.version>
Expand Down Expand Up @@ -93,6 +93,12 @@
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>${azure.identity.version}</version>
<exclusions>
<exclusion>
<groupId>stax</groupId>
<artifactId>stax-api</artifactId>
</exclusion>
</exclusions>
</dependency>

<!-- dependencies for ANTLR -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenCredential;
import com.azure.core.credential.TokenRequestContext;
import com.azure.core.util.logging.ClientLogger;
import com.microsoft.aad.msal4j.ClientCredentialFactory;
import com.microsoft.aad.msal4j.ClientCredentialParameters;
import com.microsoft.aad.msal4j.ConfidentialClientApplication;
Expand All @@ -30,7 +29,6 @@
*/
@Immutable
class KeyVaultTokenCredential implements TokenCredential {
private final ClientLogger logger = new ClientLogger(KeyVaultTokenCredential.class);
private final String clientId;
private final String clientSecret;
private final SQLServerKeyVaultAuthenticationCallback authenticationCallback;
Expand Down Expand Up @@ -139,7 +137,7 @@ private ConfidentialClientApplication getConfidentialClientApplication() {
try {
applicationBuilder = applicationBuilder.authority(authorization);
} catch (MalformedURLException e) {
throw logger.logExceptionAsWarning(new IllegalStateException(e));
throw new RuntimeException(e);
}
return applicationBuilder.build();
}
Expand All @@ -157,7 +155,7 @@ private Mono<AccessToken> authenticateWithConfidentialClientCache(TokenRequestCo
try {
return confidentialClientApplication.acquireTokenSilently(parametersBuilder.build());
} catch (MalformedURLException e) {
return getFailedCompletableFuture(logger.logExceptionAsError(new RuntimeException(e)));
return getFailedCompletableFuture(new RuntimeException(e));
}
}).map(ar -> new AccessToken(ar.accessToken(),
OffsetDateTime.ofInstant(ar.expiresOnDate().toInstant(), ZoneOffset.UTC))).filter(t -> !t.isExpired());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ public class SQLServerColumnEncryptionAzureKeyVaultProvider extends SQLServerCol

private final static java.util.logging.Logger akvLogger = java.util.logging.Logger
.getLogger("com.microsoft.sqlserver.jdbc.SQLServerColumnEncryptionAzureKeyVaultProvider");
public static final int KEY_NAME_INDEX = 4;
public static final int KEY_URL_SPLIT_LENGTH_WITH_VERSION = 6;
public static final String KEY_URL_DELIMITER = "/";
private static final int KEY_NAME_INDEX = 4;
private static final int KEY_URL_SPLIT_LENGTH_WITH_VERSION = 6;
private static final String KEY_URL_DELIMITER = "/";
private HttpPipeline keyVaultPipeline;
private KeyVaultTokenCredential keyVaultTokenCredential;

Expand Down Expand Up @@ -124,8 +124,8 @@ public SQLServerColumnEncryptionAzureKeyVaultProvider(String clientId, String cl
}

/**
* Constructs a SQLServerColumnEncryptionAzureKeyVaultProvider to authenticate to AAD. This is used by
* KeyVaultClient at runtime to authenticate to Azure Key Vault.
* Constructs a SQLServerColumnEncryptionAzureKeyVaultProvider to authenticate to AAD. This is used by KeyVault
* client at runtime to authenticate to Azure Key Vault.
*
* @throws SQLServerException
* when an error occurs
Expand All @@ -135,8 +135,8 @@ public SQLServerColumnEncryptionAzureKeyVaultProvider(String clientId, String cl
}

/**
* Constructs a SQLServerColumnEncryptionAzureKeyVaultProvider to authenticate to AAD. This is used by
* KeyVaultClient at runtime to authenticate to Azure Key Vault.
* Constructs a SQLServerColumnEncryptionAzureKeyVaultProvider to authenticate to AAD. This is used by KeyVault
* client at runtime to authenticate to Azure Key Vault.
*
* @param clientId
* Identifier of the client requesting the token.
Expand All @@ -155,7 +155,7 @@ public SQLServerColumnEncryptionAzureKeyVaultProvider(String clientId, String cl

/**
* Constructs a SQLServerColumnEncryptionAzureKeyVaultProvider using the provided TokenCredential to authenticate to
* AAD. This is used by KeyVaultClient at runtime to authenticate to Azure Key Vault.
* AAD. This is used by KeyVault client at runtime to authenticate to Azure Key Vault.
*
* @param tokenCredential
* The TokenCredential to use to authenticate to Azure Key Vault.
Expand All @@ -173,38 +173,18 @@ public SQLServerColumnEncryptionAzureKeyVaultProvider(TokenCredential tokenCrede
setCredential(tokenCredential);
}

/**
* Constructs a SQLServerColumnEncryptionAzureKeyVaultProvider with a callback function to authenticate to AAD and
* an executor service.. This is used by KeyVaultClient at runtime to authenticate to Azure Key Vault.
*
* This constructor is present to maintain backwards compatibility with 6.0 version of the driver. Deprecated for
* removal in next stable release.
*
* @param authenticationCallback
* - Callback function used for authenticating to AAD.
* @param executorService
* - The ExecutorService, previously used to create the keyVaultClient, but not in use anymore. - This
* parameter can be passed as 'null'
* @throws SQLServerException
* when an error occurs
*/
@Deprecated
public SQLServerColumnEncryptionAzureKeyVaultProvider(
SQLServerKeyVaultAuthenticationCallback authenticationCallback,
ExecutorService executorService) throws SQLServerException {
this(authenticationCallback);
}

/**
* Constructs a SQLServerColumnEncryptionAzureKeyVaultProvider with a callback function to authenticate to AAD. This
* is used by KeyVaultClient at runtime to authenticate to Azure Key Vault.
* is used by KeyVault client at runtime to authenticate to Azure Key Vault.
*
* This constructor is present to maintain backwards compatibility with 8.0 version of the driver. Deprecated for
* removal in next stable release.
*
* @param authenticationCallback
* - Callback function used for authenticating to AAD.
* @throws SQLServerException
* when an error occurs
*/
@Deprecated
public SQLServerColumnEncryptionAzureKeyVaultProvider(
SQLServerKeyVaultAuthenticationCallback authenticationCallback) throws SQLServerException {
if (null == authenticationCallback) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@
*/
public interface SQLServerKeyVaultAuthenticationCallback {

/**
* Returns the acesss token of the authentication request
*
* @param authority
* - Identifier of the authority, a URL.
* @param resource
* - Identifier of the target resource that is the recipient of the requested token, a URL.
* @param scope
* - The scope of the authentication request.
* @return access token
*/
String getAccessToken(String authority, String resource, String scope);
/**
* Returns the acesss token of the authentication request
*
* @param authority
* - Identifier of the authority, a URL.
* @param resource
* - Identifier of the target resource that is the recipient of the requested token, a URL.
* @param scope
* - The scope of the authentication request.
* @return access token
*/
String getAccessToken(String authority, String resource, String scope);
}
Original file line number Diff line number Diff line change
Expand Up @@ -253,25 +253,34 @@ static SqlFedAuthToken getMSIAuthToken(String resource, String msiClientId) thro
// IMDS upgrade time can take up to 70s
final int imdsUpgradeTimeInMs = 70 * 1000;
final List<Integer> retrySlots = new ArrayList<>();
final String msiEndpoint = System.getenv("MSI_ENDPOINT");
final String msiSecret = System.getenv("MSI_SECRET");

StringBuilder urlString = new StringBuilder();
int retry = 1, maxRetry = 1;

// MSI_ENDPOINT and MSI_SECRET can be used instead of IDENTITY_ENDPOINT and IDENTITY_HEADER
String identityEndpoint = System.getenv("IDENTITY_ENDPOINT");
if (null == identityEndpoint || identityEndpoint.trim().isEmpty()) {
identityEndpoint = System.getenv("MSI_ENDPOINT");
}

String identityHeader = System.getenv("IDENTITY_HEADER");
if (null == identityHeader || identityHeader.trim().isEmpty()) {
identityHeader = System.getenv("MSI_SECRET");
}

/*
* isAzureFunction is used for identifying if the current client application is running in a Virtual Machine
* (without MSI environment variables) or App Service/Function (with MSI environment variables) as the APIs to
* be called for acquiring MSI Token are different for both cases.
* (without Managed Identity environment variables) or App Service/Function (with Managed Identity environment
* variables) as the APIs to be called for acquiring MSI Token are different for both cases.
*/
boolean isAzureFunction = null != msiEndpoint && !msiEndpoint.isEmpty() && null != msiSecret
&& !msiSecret.isEmpty();
boolean isAzureFunction = null != identityEndpoint && !identityEndpoint.isEmpty() && null != identityHeader
&& !identityHeader.isEmpty();

if (isAzureFunction) {
urlString.append(msiEndpoint).append("?api-version=2019-08-01&resource=").append(resource);
urlString.append(identityEndpoint).append("?api-version=2019-08-01&resource=").append(resource);
} else {
urlString.append(ActiveDirectoryAuthentication.AZURE_REST_MSI_URL).append("&resource=").append(resource);
// Retry acquiring access token upto 20 times due to possible IMDS upgrade (Applies to VM only)
// Retry acquiring access token up to 20 times due to possible IMDS upgrade (Applies to VM only)
maxRetry = 20;
// Simplified variant of Exponential BackOff
for (int x = 0; x < maxRetry; x++) {
Expand All @@ -293,14 +302,14 @@ static SqlFedAuthToken getMSIAuthToken(String resource, String msiClientId) thro
connection.setRequestMethod("GET");

if (isAzureFunction) {
connection.setRequestProperty("X-IDENTITY-HEADER", msiSecret);
connection.setRequestProperty("X-IDENTITY-HEADER", identityHeader);
if (connectionlogger.isLoggable(Level.FINER)) {
connectionlogger.finer("Using Azure Function/App Service MSI auth: " + urlString);
connectionlogger.finer("Using Azure Function/App Service Managed Identity auth: " + urlString);
}
} else {
connection.setRequestProperty("Metadata", "true");
if (connectionlogger.isLoggable(Level.FINER)) {
connectionlogger.finer("Using Azure MSI auth: " + urlString);
connectionlogger.finer("Using Azure Managed Identity auth: " + urlString);
}
}

Expand Down

0 comments on commit 0d509af

Please sign in to comment.