diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index af1e214791527..9e5c7b72a60c0 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -124,7 +124,7 @@ com.azure:azure-developer-loadtesting;1.0.32;1.2.0-beta.2 com.azure:azure-digitaltwins-core;1.5.9;1.6.0-beta.1 com.azure:azure-health-deidentification;1.0.0;1.1.0-beta.2 com.azure:azure-health-insights-radiologyinsights;1.1.10;1.2.0-beta.1 -com.azure:azure-identity;1.18.7;1.19.0-beta.3 +com.azure:azure-identity;1.18.7;1.19.0 com.azure:azure-identity-extensions;1.2.10;1.3.0-beta.1 com.azure:azure-identity-broker;1.1.24;1.2.0-beta.1 com.azure:azure-identity-broker-samples;1.0.0-beta.1;1.0.0-beta.1 diff --git a/sdk/identity/azure-identity-broker-samples/pom.xml b/sdk/identity/azure-identity-broker-samples/pom.xml index 81c44a9d06057..9561f932cf181 100644 --- a/sdk/identity/azure-identity-broker-samples/pom.xml +++ b/sdk/identity/azure-identity-broker-samples/pom.xml @@ -34,7 +34,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 com.azure diff --git a/sdk/identity/azure-identity-broker/pom.xml b/sdk/identity/azure-identity-broker/pom.xml index b85196ac00fb8..61fc6b060e2b9 100644 --- a/sdk/identity/azure-identity-broker/pom.xml +++ b/sdk/identity/azure-identity-broker/pom.xml @@ -36,7 +36,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 diff --git a/sdk/identity/azure-identity-perf/pom.xml b/sdk/identity/azure-identity-perf/pom.xml index 7ad9e6612dcd3..16fa8d9f9c4f6 100644 --- a/sdk/identity/azure-identity-perf/pom.xml +++ b/sdk/identity/azure-identity-perf/pom.xml @@ -25,7 +25,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 com.azure diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 9b662e4e4fece..f55bbae34228b 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -1,27 +1,37 @@ # Release History -## 1.19.0-beta.3 (Unreleased) +## 1.19.0 (2026-10-29) ### Features Added -- Added support for user-assigned managed identities on Azure Arc in `ManagedIdentityCredential` and `DefaultAzureCredential`. - -### Breaking Changes +- Added `enableAzureProxy()` method to `WorkloadIdentityCredentialBuilder` to enable custom token proxy support for Azure Kubernetes clusters. When enabled, the credential attempts to use a custom token proxy configured through environment variables (`AZURE_KUBERNETES_TOKEN_PROXY`, `AZURE_KUBERNETES_CA_FILE`, `AZURE_KUBERNETES_CA_DATA`, `AZURE_KUBERNETES_SNI_NAME`). ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) ### Bugs Fixed -- Disabled MSAL's internal retry for Confidential Client, Managed Identity and Public Client Applications. ([#48472](https://github.com/Azure/azure-sdk-for-java/pull/48472)) -- Fixed misleading authentication error reporting when token requests are interrupted or the JVM shuts down. ([#50585](https://github.com/Azure/azure-sdk-for-java/issues/50585)) -- Fixed IMDS discovery in `DefaultAzureCredential` to wait for HTTP response headers with a read timeout, allowing the credential chain to continue when a local endpoint accepts connections but does not respond, while preserving fallback on probe setup failures. ([#50517](https://github.com/Azure/azure-sdk-for-java/pull/50517)) - Fixed `OnBehalfOfCredential` token cache lookup to remain bound to the configured user assertion, preventing a cached token acquired for one user from being returned for another user with matching scopes. ([#50618](https://github.com/Azure/azure-sdk-for-java/pull/50618)) ### Other Changes -- Improved `AzureDeveloperCliCredential` error handling to extract meaningful messages from `azd auth token` JSON output, providing cleaner error messages to users. +- Upgraded `azure-core` from `1.60.0` to version `1.61.0`. +- Upgraded `azure-core-http-netty` from `1.16.8` to version `1.17.0`. -#### Dependency Updates +--- -- Upgraded `msal4j` from `1.23.1` to `1.26.0`. +The updates below only denote differences between this release and previous 1.19.0 beta releases, not the 1.18.x stable implementation. + +### Bugs Fixed + +- Fixed verification of `AZURE_KUBERNETES_SNI_NAME` being skipped when the proxy certificate already matched the proxy URL hostname. The configured name is now checked during TLS handshakes, including connections opened by automatic HTTP retries, before sending the service-account assertion. Certificate DNS wildcards that match exactly one label remain supported. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- Fixed the AKS token proxy accepting CA bundles containing a valid certificate followed by a malformed certificate entry. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- Fixed authentication failures when a previously loaded proxy CA file temporarily disappears during rotation. The existing fallback for an empty CA file is unchanged. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- Fixed a race between proxy CA reloads and socket factory creation that could leave requests using the previous CA configuration. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- Fixed blocking I/O in the internal AKS proxy transport's reactive send and response-body APIs running on subscriber threads. These operations now use a blocking-I/O scheduler. Synchronous body reads, including those used by the MSAL bridge, stay on the calling thread to avoid starvation when that scheduler is saturated. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- Fixed the AKS token proxy converting I/O failures while opening response streams for HTTP statuses below 400 into empty bodies. These failures now propagate. HTTP error responses without a body still retain their error status. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- Fixed the proxy transport leaking into subsequent credentials built with the same `WorkloadIdentityCredentialBuilder` after proxy settings were removed. Proxy options are now applied to a per-credential copy instead of mutating the builder. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) + +### Other Changes + +- Added AKS identity binding usage guidance and an opt-in example for `WorkloadIdentityCredentialBuilder.enableAzureProxy()`. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) ## 1.18.7 (2026-10-01) diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index 40a5114a066a7..dfbc788bf5244 100644 --- a/sdk/identity/azure-identity/README.md +++ b/sdk/identity/azure-identity/README.md @@ -46,7 +46,7 @@ To take dependency on a particular version of the library that isn't present in com.azure azure-identity - 1.18.4 + 1.19.0 ``` [//]: # ({x-version-update-end}) @@ -146,6 +146,52 @@ public void createDefaultAzureCredentialForVSCode() { } ``` +### Authenticate with AKS identity bindings + +[Azure Kubernetes Service (AKS) identity bindings](https://learn.microsoft.com/azure/aks/identity-bindings-concepts) +let multiple clusters share a user-assigned managed identity through a single AKS-managed federated identity +credential, avoiding the limit of 20 federated identity credentials per managed identity. + +Use `WorkloadIdentityCredential` directly and call `enableAzureProxy()` to route authentication through the AKS token +proxy. This option is disabled by default and isn't supported by `DefaultAzureCredential` or `ManagedIdentityCredential`. + +The identity binding API requires `azure-identity` `1.19.0-beta.2` or a later version containing this feature. +It isn't included in `1.18.x` packages. If your BOM selects a `1.18.x` version, override it with an identity binding-enabled +version. + +```java readme-sample-workloadidentitybinding +WorkloadIdentityCredential credential = new WorkloadIdentityCredentialBuilder() + .enableAzureProxy() + .build(); +``` + +First [configure the AKS identity binding and Kubernetes permissions](https://learn.microsoft.com/azure/aks/identity-bindings). +The pod must use an authorized service account and have the `azure.workload.identity/use: "true"` label and +`azure.workload.identity/use-identity-binding: "true"` annotation. For Jobs and Deployments, set these on the pod template. +The workload identity webhook provides the configuration: + +| Environment variable | Purpose | +| --- | --- | +| `AZURE_CLIENT_ID` | Client ID of the user-assigned managed identity, not its object ID. | +| `AZURE_TENANT_ID` | Microsoft Entra tenant ID. | +| `AZURE_FEDERATED_TOKEN_FILE` | Projected Kubernetes service account token file. | +| `AZURE_AUTHORITY_HOST` | Microsoft Entra authority. Keep this set to the authority, not the proxy URL. | +| `AZURE_KUBERNETES_TOKEN_PROXY` | HTTPS token proxy endpoint. It must not contain credentials, query parameters, or a fragment. | +| `AZURE_KUBERNETES_SNI_NAME` | TLS server name used to verify the proxy certificate. | +| `AZURE_KUBERNETES_CA_FILE` or `AZURE_KUBERNETES_CA_DATA` | Trusted CA bundle, either a file path or inline PEM text. Don't set both or Base64 encode the inline text. | + +The credential reloads changes to a CA file on subsequent network requests. A temporarily missing or empty file during +rotation retains the previously loaded CA; an invalid nonempty bundle fails authentication. If neither CA setting is +provided, the platform trust store is used. + +Enabling the option without any proxy settings uses the direct workload identity flow. Partial or invalid proxy +configuration fails instead of silently falling back to direct authentication. With proxy configuration present, +a dedicated HTTP transport is set on a copy of the credential options. A custom HTTP pipeline retains its usual +precedence over HTTP client settings. + +An identity binding authorizes token acquisition, not access to Azure resources. Assign Azure roles to the managed +identity separately when resource access is required. + ## Managed Identity support The [Managed identity authentication](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/overview) is supported indirectly via `DefaultAzureCredential` or directly via `ManagedIdentityCredential` for the following Azure Services: diff --git a/sdk/identity/azure-identity/TROUBLESHOOTING.md b/sdk/identity/azure-identity/TROUBLESHOOTING.md index 51e03e83617d9..352bfe8e6dc9c 100644 --- a/sdk/identity/azure-identity/TROUBLESHOOTING.md +++ b/sdk/identity/azure-identity/TROUBLESHOOTING.md @@ -273,7 +273,9 @@ Get-AzAccessToken -ResourceUrl "https://management.core.windows.net" |---|-------------------------------------------------------------------------------------------------------------------------------|---| |`CredentialUnavailableException` raised with message. "WorkloadIdentityCredential authentication unavailable. The workload options are not fully configured."| The `WorkloadIdentityCredential` requires `clientId`, `tenantId` and `tokenFilePath` to authenticate with Microsoft Entra ID. |
  • If using `DefaultAzureCredential` then:
    • Ensure client ID is specified via `workloadIdentityClientId` setter or `AZURE_CLIENT_ID` env variable.
    • Ensure tenant ID is specified via `AZURE_TENANT_ID` env variable.
    • Ensure token file path is specified via `AZURE_FEDERATED_TOKEN_FILE` env variable.
    • Ensure authority host is specified via `AZURE_AUTHORITY_HOST` env variable.
  • If using `WorkloadIdentityCredential` then:
    • Ensure tenant ID is specified via `tenantId` setter on credential builder or `AZURE_TENANT_ID` env variable.
    • Ensure client ID is specified via `clientId` setter on the credential builder or `AZURE_CLIENT_ID` env variable.
    • Ensure token file path is specified via `tokenFilePath` setter on the credential builder or `AZURE_FEDERATED_TOKEN_FILE` environment variable.
  • Consult the [product troubleshooting guide](https://azure.github.io/azure-workload-identity/docs/troubleshooting.html) for other issues.
|`CredentialUnavailableException` raised with message. "WorkloadIdentityCredential authentication unavailable. The request to the authority host was invalid."| The configured properties for workload identity are invalid. | Ensure the properties for workload identity are correctly configured on the credential builder and right permissions are assigned to the workload identity. -|In an application using [Azure Kubernetes Service identity bindings](https://learn.microsoft.com/azure/aks/identity-bindings-concepts):
  • AADSTS700211: No matching federated identity record found for presented assertion issuer ...
  • AADSTS700212: No matching federated identity record found for presented assertion audience 'api://AKSIdentityBinding'.
|`WorkloadIdentityCredential` isn't configured to use the identity binding proxy|Call `WorkloadIdentityCredentialBuilder.enableAzureProxy()` while building the credential. +|In an application using [Azure Kubernetes Service identity bindings](https://learn.microsoft.com/azure/aks/identity-bindings-concepts):
  • AADSTS700211: No matching federated identity record found for presented assertion issuer ...
  • AADSTS700212: No matching federated identity record found for presented assertion audience 'api://AKSIdentityBinding'.
|`WorkloadIdentityCredential` isn't configured to use the identity binding proxy, or its binding and permissions aren't configured.|Use `WorkloadIdentityCredential` directly and call `WorkloadIdentityCredentialBuilder.enableAzureProxy()`. Confirm that the webhook supplied `AZURE_KUBERNETES_TOKEN_PROXY` and the pod uses an authorized service account. `DefaultAzureCredential` and `ManagedIdentityCredential` don't support identity binding mode.| +|Invalid AKS proxy configuration.|The proxy URL is missing or invalid, both CA sources are configured, or inline CA data is empty.|Use an absolute HTTPS proxy URL without credentials, a query, or a fragment. Set at most one of `AZURE_KUBERNETES_CA_FILE` and `AZURE_KUBERNETES_CA_DATA`; inline data must be PEM text, not Base64. Keep `AZURE_AUTHORITY_HOST` set to the Microsoft Entra authority.| +|TLS failure when connecting to the AKS token proxy.|The proxy certificate isn't trusted or doesn't match `AZURE_KUBERNETES_SNI_NAME`.|Check the webhook's CA and TLS server-name settings. Ensure the CA file exists on first use. Missing or empty files during rotation retain an already loaded CA, but invalid nonempty bundles fail authentication. Never disable TLS verification.| ## Troubleshoot `IntelliJCredential` authentication issues diff --git a/sdk/identity/azure-identity/pom.xml b/sdk/identity/azure-identity/pom.xml index 0a23ae2eab17d..32a1c0ac8b50b 100644 --- a/sdk/identity/azure-identity/pom.xml +++ b/sdk/identity/azure-identity/pom.xml @@ -6,7 +6,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 Microsoft Azure client library for Identity This module contains client library for Microsoft Azure Identity. diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredential.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredential.java index a0c04ff2d9526..98bcc3b90d319 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredential.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredential.java @@ -22,19 +22,18 @@ import static com.azure.identity.ManagedIdentityCredential.AZURE_FEDERATED_TOKEN_FILE; /** - *

Workload Identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) - * to access other Azure resources without the need for a service principal or managed identity. With Workload Identity - * authentication, applications authenticate themselves using their own identity, rather than using a shared service - * principal or managed identity. Under the hood, Workload Identity authentication uses the concept of Service Account - * Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using Workload - * Identity authentication, you can avoid the need to manage and rotate service principals or managed identities for - * each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don't - * need to worry about storing and securing sensitive credentials themselves. - * The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires - * a token using the service account credentials available in the Azure Kubernetes environment. + *

Authenticates workloads on Kubernetes by exchanging a projected service account token for a Microsoft Entra + * access token. The identity's federated identity credential defines which service account tokens are trusted, + * without requiring the application to manage a secret or certificate. * Refer to Microsoft Entra Workload ID * for more information.

* + *

Azure Kubernetes Service (AKS) identity bindings allow multiple clusters to share a user-assigned managed identity + * through a single AKS-managed federated identity credential. To route token exchanges through the AKS token proxy, + * call {@link WorkloadIdentityCredentialBuilder#enableAzureProxy()} when constructing this credential. + * Identity binding mode is disabled by default and is not supported by {@link DefaultAzureCredential} or + * {@link ManagedIdentityCredential}. The binding and Kubernetes permissions must be configured separately.

+ * *

Sample: Construct WorkloadIdentityCredential

* *

The following code sample demonstrates the creation of a {@link WorkloadIdentityCredential}, diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredentialBuilder.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredentialBuilder.java index d036657ee0bad..5ebad0185e120 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredentialBuilder.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/WorkloadIdentityCredentialBuilder.java @@ -6,6 +6,7 @@ import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; +import com.azure.identity.implementation.IdentityClientOptions; import com.azure.identity.implementation.customtokenproxy.CustomTokenProxyConfiguration; import com.azure.identity.implementation.customtokenproxy.CustomTokenProxyHttpClient; import com.azure.identity.implementation.customtokenproxy.ProxyConfig; @@ -16,18 +17,11 @@ /** * Fluent credential builder for instantiating a {@link WorkloadIdentityCredential}. * - *

Workload Identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) - * to access other Azure resources without the need for a service principal or managed identity. With Workload Identity - * authentication, applications authenticate themselves using their own identity, rather than using a shared service - * principal or managed identity. Under the hood, Workload Identity authentication uses the concept of Service Account - * Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using Workload - * Identity authentication, you can avoid the need to manage and rotate service principals or managed identities for - * each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don't - * need to worry about storing and securing sensitive credentials themselves. - * The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires - * a token using the service account credentials available in the Azure Kubernetes environment. + *

Workload identity authentication exchanges a projected Kubernetes service account token for a Microsoft Entra + * access token, without requiring an application secret or certificate. The credential reads its tenant ID, client ID, + * and token file path from the workload identity environment variables unless they are configured on this builder. * Refer to Microsoft Entra Workload ID - * for more information.

+ * for more information. To use Azure Kubernetes Service identity bindings, opt in with {@link #enableAzureProxy()}.

* *

Sample: Construct WorkloadIdentityCredential

* @@ -71,10 +65,36 @@ public WorkloadIdentityCredentialBuilder tokenFilePath(String tokenFilePath) { } /** - * Enables the custom token proxy feature for clusters running in Azure. - * When enabled, the credential will attempt to use a custom token proxy configured through - * environment variables (AZURE_KUBERNETES_TOKEN_PROXY, AZURE_KUBERNETES_CA_FILE, - * AZURE_KUBERNETES_CA_DATA, AZURE_KUBERNETES_SNI_NAME). + * Enables Azure Kubernetes Service (AKS) identity bindings. When proxy configuration is present, authentication + * requests are sent through the AKS token proxy instead of directly to Microsoft Entra ID. + * + *

This feature is disabled by default and requires using {@link WorkloadIdentityCredential} directly. + * It is not supported by {@link DefaultAzureCredential} or {@link ManagedIdentityCredential}. The AKS identity + * binding and Kubernetes permissions must be configured separately. See + * AKS identity bindings.

+ * + *

The AKS webhook supplies {@code AZURE_KUBERNETES_TOKEN_PROXY}, {@code AZURE_KUBERNETES_SNI_NAME}, + * and either {@code AZURE_KUBERNETES_CA_FILE} or {@code AZURE_KUBERNETES_CA_DATA}. Inline CA data must be PEM encoded, + * not Base64 encoded. If neither CA setting is provided, the platform trust store is used. Changes to a CA file + * are reloaded on subsequent network requests. Missing or empty files during rotation retain the previously loaded + * CA; invalid nonempty certificate bundles fail authentication.

+ * + *

If no proxy settings are present, the credential uses direct authentication. Incomplete or invalid proxy + * configuration fails rather than falling back to direct authentication. When a proxy is configured, its dedicated + * transport is set on a copy of the credential options, replacing any client set with + * {@link #httpClient(com.azure.core.http.HttpClient)}. A custom HTTP pipeline retains its usual precedence over + * HTTP client settings. + * Keep the authority host set to the Microsoft Entra authority, not the proxy URL.

+ * + *

Sample: Enable AKS identity bindings

+ * + * + *
+     * WorkloadIdentityCredential credential = new WorkloadIdentityCredentialBuilder()
+     *     .enableAzureProxy()
+     *     .build();
+     * 
+ * * * @return An updated instance of this builder with Azure proxy enabled. */ @@ -87,6 +107,7 @@ public WorkloadIdentityCredentialBuilder enableAzureProxy() { * Creates new {@link WorkloadIdentityCredential} with the configured options set. * * @return a {@link WorkloadIdentityCredential} with the current configurations. + * @throws IllegalArgumentException if required workload identity settings are missing or proxy configuration is invalid. */ public WorkloadIdentityCredential build() { Configuration configuration = identityClientOptions.getConfiguration() == null @@ -105,14 +126,14 @@ public WorkloadIdentityCredential build() { ValidationUtil.validate(this.getClass().getSimpleName(), LOGGER, "Client ID", clientIdInput, "Tenant ID", tenantIdInput, "Service Token File Path", federatedTokenFilePathInput); + IdentityClientOptions options = identityClientOptions.clone(); if (enableAzureProxy) { ProxyConfig proxyConfig = CustomTokenProxyConfiguration.parseAndValidate(configuration); if (proxyConfig != null) { - identityClientOptions.setHttpClient(new CustomTokenProxyHttpClient(proxyConfig)); + options.setHttpClient(new CustomTokenProxyHttpClient(proxyConfig)); } } - return new WorkloadIdentityCredential(tenantIdInput, clientIdInput, federatedTokenFilePathInput, - identityClientOptions.clone()); + return new WorkloadIdentityCredential(tenantIdInput, clientIdInput, federatedTokenFilePathInput, options); } } diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfiguration.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfiguration.java index 9c789aa758a65..7ac59afcd026b 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfiguration.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfiguration.java @@ -7,8 +7,11 @@ import java.net.URI; import java.net.URL; +import java.net.MalformedURLException; import java.nio.charset.StandardCharsets; import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Paths; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; @@ -48,13 +51,21 @@ public static ProxyConfig parseAndValidate(Configuration configuration) { URL proxyUrl = validateProxyUrl(tokenProxyUrl); + if (!CoreUtils.isNullOrEmpty(caFile) && !Files.isRegularFile(Paths.get(caFile))) { + throw LOGGER.logExceptionAsError( + new IllegalArgumentException("AZURE_KUBERNETES_CA_FILE must identify an existing certificate file.")); + } + byte[] caCertBytes = null; if (!CoreUtils.isNullOrEmpty(caData)) { + if (caData.trim().isEmpty()) { + throw LOGGER.logExceptionAsError( + new IllegalArgumentException("AZURE_KUBERNETES_CA_DATA must not contain only whitespace.")); + } caCertBytes = caData.getBytes(StandardCharsets.UTF_8); } - ProxyConfig config = new ProxyConfig(proxyUrl, sniName, caFile, caCertBytes); - return config; + return new ProxyConfig(proxyUrl, sniName, caFile, caCertBytes); } private static URL validateProxyUrl(String endpoint) { @@ -65,37 +76,38 @@ private static URL validateProxyUrl(String endpoint) { try { URI tokenProxy = new URI(endpoint); - if (!"https".equals(tokenProxy.getScheme())) { + if (!"https".equalsIgnoreCase(tokenProxy.getScheme())) { throw LOGGER.logExceptionAsError(new IllegalArgumentException( "Custom token endpoint must use https scheme, got: " + tokenProxy.getScheme())); } if (tokenProxy.getRawUserInfo() != null) { throw LOGGER.logExceptionAsError( - new IllegalArgumentException("Custom token endpoint URL must not contain user info: " + endpoint)); + new IllegalArgumentException("Custom token endpoint URL must not contain user info.")); } if (tokenProxy.getRawQuery() != null) { throw LOGGER.logExceptionAsError( - new IllegalArgumentException("Custom token endpoint URL must not contain a query: " + endpoint)); + new IllegalArgumentException("Custom token endpoint URL must not contain a query.")); } if (tokenProxy.getRawFragment() != null) { throw LOGGER.logExceptionAsError( - new IllegalArgumentException("Custom token endpoint URL must not contain a fragment: " + endpoint)); + new IllegalArgumentException("Custom token endpoint URL must not contain a fragment.")); } - if (tokenProxy.getRawPath() == null || tokenProxy.getRawPath().isEmpty()) { - tokenProxy = new URI(tokenProxy.getScheme(), null, tokenProxy.getHost(), tokenProxy.getPort(), "/", - null, null); + if (CoreUtils.isNullOrEmpty(tokenProxy.getHost()) + || tokenProxy.getPort() < -1 + || tokenProxy.getPort() > 65535) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException( + "AZURE_KUBERNETES_TOKEN_PROXY must be an absolute HTTPS URL with a valid host and port.")); } return tokenProxy.toURL(); - } catch (URISyntaxException | IllegalArgumentException e) { - throw LOGGER.logExceptionAsError(new IllegalArgumentException("Failed to normalize proxy URL path", e)); - } catch (Exception e) { - throw new RuntimeException("Unexpected error while validating proxy URL: " + endpoint, e); + } catch (URISyntaxException | MalformedURLException e) { + throw LOGGER.logExceptionAsError( + new IllegalArgumentException("AZURE_KUBERNETES_TOKEN_PROXY must be a valid absolute HTTPS URL.", e)); } } diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClient.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClient.java index ef2c7f0446a6d..0306c09f39af6 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClient.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClient.java @@ -8,19 +8,20 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; +import java.net.IDN; import java.net.MalformedURLException; -import java.net.URI; +import java.net.Socket; import java.net.URL; import java.nio.file.Files; -import java.nio.file.Path; +import java.nio.file.NoSuchFileException; import java.nio.file.Paths; import java.security.KeyStore; +import java.security.GeneralSecurityException; import java.security.cert.Certificate; -import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; +import java.security.cert.CertificateException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -28,9 +29,13 @@ import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509ExtendedTrustManager; +import javax.net.ssl.X509TrustManager; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpRequest; @@ -42,25 +47,21 @@ import com.azure.identity.implementation.SniSslSocketFactory; import reactor.core.publisher.Mono; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +import reactor.core.scheduler.Schedulers; public class CustomTokenProxyHttpClient implements HttpClient { private static final ClientLogger LOGGER = new ClientLogger(CustomTokenProxyHttpClient.class); - private final ProxyConfig proxyConfig; - private volatile SSLContext cachedSSLContext; - private volatile byte[] cachedFileContentHash; - private volatile int cachedFileContentLength; - private volatile SSLSocketFactory cachedSslSocketFactory; + private SSLContext cachedSSLContext; + private byte[] cachedCaData; + private SSLSocketFactory cachedSslSocketFactory; private final URL proxyUrl; private final String sniName; private final byte[] caData; private final String caFile; public CustomTokenProxyHttpClient(ProxyConfig proxyConfig) { - this.proxyConfig = proxyConfig; this.proxyUrl = proxyConfig.getTokenProxyUrl(); this.sniName = proxyConfig.getSniName(); this.caData = proxyConfig.getCaData(); @@ -69,230 +70,213 @@ public CustomTokenProxyHttpClient(ProxyConfig proxyConfig) { @Override public Mono send(HttpRequest request) { - return Mono.fromCallable(() -> sendSync(request, Context.NONE)); + return send(request, Context.NONE); + } + + @Override + public Mono send(HttpRequest request, Context context) { + return Mono.fromCallable(() -> sendSync(request, context)) + .subscribeOn(Schedulers.boundedElastic()) + .doOnDiscard(HttpResponse.class, HttpResponse::close); } @Override public HttpResponse sendSync(HttpRequest request, Context context) { + HttpURLConnection connection = null; + HttpResponse response = null; try { - HttpURLConnection connection = createConnection(request); - return new CustomTokenProxyHttpResponse(request, connection); + HttpRequest proxyRequest = request.copy().setUrl(rewriteTokenRequestForProxy(request.getUrl())); + connection = createConnection(proxyRequest); + response = new CustomTokenProxyHttpResponse(proxyRequest, connection); + return response; } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("Failed to create connection to token proxy", e)); + } finally { + if (response == null && connection != null) { + connection.disconnect(); + } } } private HttpURLConnection createConnection(HttpRequest request) throws IOException { - URL updatedUrl = rewriteTokenRequestForProxy(request.getUrl()); - HttpsURLConnection connection = (HttpsURLConnection) updatedUrl.openConnection(); + HttpsURLConnection connection = (HttpsURLConnection) request.getUrl().openConnection(); + boolean requestSent = false; try { - SSLSocketFactory sslSocketFactory = getSSLSocketFactory(); - connection.setSSLSocketFactory(sslSocketFactory); + connection.setSSLSocketFactory(getSSLSocketFactory()); if (!CoreUtils.isNullOrEmpty(sniName)) { connection.setHostnameVerifier(sniAwareVerifier(sniName, proxyUrl)); } - } catch (Exception e) { - throw LOGGER.logExceptionAsError(new RuntimeException("Failed to set up SSL context for token proxy", e)); - } - - String method = request.getHttpMethod().toString(); - connection.setRequestMethod(method); - connection.setInstanceFollowRedirects(false); - connection.setConnectTimeout(10_000); - connection.setReadTimeout(20_000); - connection.setDoOutput(true); - - BinaryData bodyData = request.getBodyAsBinaryData(); - - request.getHeaders().forEach(header -> { - connection.addRequestProperty(header.getName(), header.getValue()); - }); - - if (bodyData != null) { - byte[] bytes = bodyData.toBytes(); - if (bytes != null && bytes.length > 0) { - try (OutputStream os = connection.getOutputStream()) { - os.write(bytes); - os.flush(); - } - } - } - return connection; - } - private URL rewriteTokenRequestForProxy(URL originalUrl) throws MalformedURLException { - try { - String originalPath = originalUrl.getPath(); - String originalQuery = originalUrl.getQuery(); + connection.setRequestMethod(request.getHttpMethod().toString()); + connection.setInstanceFollowRedirects(false); + connection.setConnectTimeout(10_000); + connection.setReadTimeout(20_000); - String tokenProxyBase = proxyUrl.toString(); - if (!tokenProxyBase.endsWith("/")) { - tokenProxyBase += "/"; - } + BinaryData bodyData = request.getBodyAsBinaryData(); + connection.setDoOutput(bodyData != null); - URI combined = URI.create(tokenProxyBase) - .resolve(originalPath.startsWith("/") ? originalPath.substring(1) : originalPath); + request.getHeaders().forEach(header -> connection.addRequestProperty(header.getName(), header.getValue())); - String combinedStr = combined.toString(); - if (originalQuery != null && !originalQuery.isEmpty()) { - combinedStr += "?" + originalQuery; + connection.connect(); + // HttpsURLConnection can skip its verifier when the certificate matches the URL host. + if (!CoreUtils.isNullOrEmpty(sniName) + && !certificateMatchesServerName(connection.getServerCertificates(), sniName)) { + throw LOGGER.logThrowableAsError(new SSLPeerUnverifiedException( + "Token proxy certificate does not match AZURE_KUBERNETES_SNI_NAME.")); } - return URI.create(combinedStr).toURL(); + if (bodyData != null) { + byte[] bytes = bodyData.toBytes(); + if (bytes.length > 0) { + try (OutputStream os = connection.getOutputStream()) { + os.write(bytes); + } + } + } + requestSent = true; + return connection; + } finally { + if (!requestSent) { + connection.disconnect(); + } + } + } - } catch (Exception e) { - throw LOGGER.logExceptionAsError(new RuntimeException("Failed to rewrite token request for proxy", e)); + private URL rewriteTokenRequestForProxy(URL originalUrl) throws MalformedURLException { + String tokenProxyBase = proxyUrl.toString(); + if (!tokenProxyBase.endsWith("/")) { + tokenProxyBase += "/"; + } + String originalPath = originalUrl.getPath(); + String combined = tokenProxyBase + (originalPath.startsWith("/") ? originalPath.substring(1) : originalPath); + if (originalUrl.getQuery() != null) { + combined += "?" + originalUrl.getQuery(); } + return new URL(combined); } - private SSLSocketFactory getSSLSocketFactory() { + private synchronized SSLSocketFactory getSSLSocketFactory() { SSLContext sslContext = getSSLContext(); if (cachedSslSocketFactory == null) { - synchronized (this) { - if (cachedSslSocketFactory == null) { - SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); - if (!CoreUtils.isNullOrEmpty(sniName)) { - sslSocketFactory = new SniSslSocketFactory(sslSocketFactory, sniName); - } - cachedSslSocketFactory = sslSocketFactory; - } + SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); + if (!CoreUtils.isNullOrEmpty(sniName)) { + sslSocketFactory = new SniSslSocketFactory(sslSocketFactory, sniName); } + cachedSslSocketFactory = sslSocketFactory; } return cachedSslSocketFactory; } private SSLContext getSSLContext() { try { - // If no CA override provided, use default - if (CoreUtils.isNullOrEmpty(caFile) && (caData == null || caData.length == 0)) { + if (CoreUtils.isNullOrEmpty(caFile)) { if (cachedSSLContext == null) { - synchronized (this) { - if (cachedSSLContext == null) { - cachedSSLContext = SSLContext.getDefault(); - cachedSslSocketFactory = null; - } + if (caData != null && caData.length > 0) { + cachedSSLContext = createSslContextFromBytes(caData); + } else { + cachedSSLContext + = CoreUtils.isNullOrEmpty(sniName) ? SSLContext.getDefault() : initializeSslContext(null); } } return cachedSSLContext; } - // If CA data provided, use it - if (CoreUtils.isNullOrEmpty(caFile)) { + byte[] currentContent; + try { + currentContent = Files.readAllBytes(Paths.get(caFile)); + } catch (NoSuchFileException e) { if (cachedSSLContext == null) { - synchronized (this) { - if (cachedSSLContext == null) { - cachedSSLContext = createSslContextFromBytes(caData); - cachedSslSocketFactory = null; - } - } + throw LOGGER.logExceptionAsError( + new IllegalStateException("Token proxy CA file is missing before its first load.", e)); } + LOGGER.warning("Token proxy CA file is temporarily missing; retaining the previously loaded CA."); return cachedSSLContext; } - // If CA file provided, read it (and re-read if it changes) - Path path = Paths.get(caFile); - if (!Files.exists(path)) { - throw LOGGER.logExceptionAsError(new RuntimeException("CA file not found: " + caFile)); - } - - byte[] currentContent = Files.readAllBytes(path); - int currentLength = currentContent.length; - byte[] currentHash = generateSHA256Hash(currentContent); - - synchronized (this) { - if (currentLength == 0) { - if (cachedSSLContext == null) { - throw LOGGER.logExceptionAsError(new IllegalStateException("CA file " + caFile + " is empty")); - } - LOGGER.warning("CA file " + caFile + " is empty, using cached SSL context from previous load"); - return cachedSSLContext; + if (currentContent.length == 0) { + if (cachedSSLContext == null) { + throw LOGGER.logExceptionAsError(new IllegalStateException("Token proxy CA file is empty.")); } + LOGGER.warning("Token proxy CA file is temporarily empty; retaining the previously loaded CA."); + return cachedSSLContext; + } - if (cachedSSLContext == null - || currentLength != cachedFileContentLength - || !Arrays.equals(currentHash, cachedFileContentHash)) { - cachedSSLContext = createSslContextFromBytes(currentContent); - cachedFileContentLength = currentLength; - cachedFileContentHash = currentHash; - cachedSslSocketFactory = null; - } + if (!Arrays.equals(currentContent, cachedCaData)) { + cachedSSLContext = createSslContextFromBytes(currentContent); + cachedCaData = currentContent; + cachedSslSocketFactory = null; } + return cachedSSLContext; - } catch (Exception e) { - throw LOGGER.logExceptionAsError(new RuntimeException("Failed to initialize SSLContext for proxy", e)); + } catch (IOException | GeneralSecurityException e) { + throw LOGGER.logExceptionAsError( + new IllegalStateException("Failed to initialize TLS trust for the token proxy.", e)); } } - // Create SSLContext from byte array containing PEM certificate data - private SSLContext createSslContextFromBytes(byte[] certificateData) { + private SSLContext createSslContextFromBytes(byte[] certificateData) throws GeneralSecurityException, IOException { try (InputStream inputStream = new ByteArrayInputStream(certificateData)) { - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - List certificates = new ArrayList<>(); - while (true) { - try { - X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream); - certificates.add(cert); - } catch (CertificateException e) { - break; - } - } + Collection certificates + = CertificateFactory.getInstance("X.509").generateCertificates(inputStream); if (certificates.isEmpty()) { throw LOGGER.logExceptionAsError(new IllegalStateException("No valid certificates found")); } return createSslContext(certificates); - } catch (Exception e) { - throw LOGGER.logExceptionAsError(new RuntimeException("Failed to create SSLContext from bytes", e)); } } - private SSLContext createSslContext(List certificates) { - try { - KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); - keystore.load(null, null); - int index = 1; - for (X509Certificate caCert : certificates) { - keystore.setCertificateEntry("ca-cert-" + index, caCert); - index++; + private SSLContext createSslContext(Collection certificates) + throws GeneralSecurityException, IOException { + KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); + keystore.load(null, null); + int index = 1; + for (Certificate caCert : certificates) { + keystore.setCertificateEntry("ca-cert-" + index++, caCert); + } + return initializeSslContext(keystore); + } + + private SSLContext initializeSslContext(KeyStore keystore) throws GeneralSecurityException { + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(keystore); + TrustManager[] trustManagers = tmf.getTrustManagers(); + if (!CoreUtils.isNullOrEmpty(sniName)) { + for (int i = 0; i < trustManagers.length; i++) { + if (trustManagers[i] instanceof X509ExtendedTrustManager) { + trustManagers[i] + = new SniExtendedTrustManager((X509ExtendedTrustManager) trustManagers[i], sniName); + } else if (trustManagers[i] instanceof X509TrustManager) { + trustManagers[i] = new SniTrustManager((X509TrustManager) trustManagers[i], sniName); + } } - TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(keystore); - - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, tmf.getTrustManagers(), null); - return context; - } catch (Exception e) { - throw LOGGER.logExceptionAsError(new RuntimeException("Failed to create SSLContext", e)); } + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, trustManagers, null); + return context; } private static HostnameVerifier sniAwareVerifier(String sniName, URL customProxyUrl) { return (urlHost, session) -> { - String peerHost = session.getPeerHost(); - String proxyHost = customProxyUrl.getHost(); - - if (peerHost.equalsIgnoreCase(proxyHost)) { - if (!CoreUtils.isNullOrEmpty(sniName)) { - try { - Certificate[] certificates = session.getPeerCertificates(); - if (certificates.length > 0 && certificates[0] instanceof X509Certificate) { - X509Certificate cert = (X509Certificate) certificates[0]; - return certificateContainsDnsName(cert, sniName); - } - return false; - } catch (SSLPeerUnverifiedException e) { - return false; - } - } - return true; + if (!customProxyUrl.getHost().equalsIgnoreCase(session.getPeerHost())) { + return false; + } + try { + return certificateMatchesServerName(session.getPeerCertificates(), sniName); + } catch (SSLPeerUnverifiedException e) { + return false; } - - return false; }; } + private static boolean certificateMatchesServerName(Certificate[] certificates, String serverName) { + return certificates.length > 0 + && certificates[0] instanceof X509Certificate + && certificateContainsDnsName((X509Certificate) certificates[0], serverName); + } + private static boolean certificateContainsDnsName(X509Certificate cert, String dnsName) { try { Collection> sanList = cert.getSubjectAlternativeNames(); @@ -300,7 +284,7 @@ private static boolean certificateContainsDnsName(X509Certificate cert, String d for (List san : sanList) { if (san.size() >= 2 && san.get(0).equals(2)) { String certDnsName = (String) san.get(1); - if (certDnsName.equalsIgnoreCase(dnsName)) { + if (matchesDnsName(dnsName, certDnsName)) { return true; } } @@ -312,13 +296,111 @@ private static boolean certificateContainsDnsName(X509Certificate cert, String d return false; } - private static byte[] generateSHA256Hash(byte[] data) { + static boolean matchesDnsName(String dnsName, String certificateDnsName) { + if (certificateDnsName.indexOf('*') == -1) { + return certificateDnsName.equalsIgnoreCase(dnsName); + } + + // A certificate wildcard can replace only the complete left-most DNS label (RFC 9525, section 6.3). + if (!certificateDnsName.startsWith("*.") + || certificateDnsName.length() == 2 + || certificateDnsName.indexOf('*', 1) != -1) { + return false; + } + try { - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - byte[] encodedHash = digest.digest(data); - return encodedHash; - } catch (NoSuchAlgorithmException e) { - throw LOGGER.logExceptionAsError(new RuntimeException("SHA-256 algorithm not found", e)); + String asciiDnsName = IDN.toASCII(dnsName, IDN.USE_STD3_ASCII_RULES); + int firstDot = asciiDnsName.indexOf('.'); + return firstDot > 0 + && !asciiDnsName.matches("[0-9.]+") + && certificateDnsName.substring(1).equalsIgnoreCase(asciiDnsName.substring(firstDot)); + } catch (IllegalArgumentException e) { + return false; } } + + private static final class SniTrustManager implements X509TrustManager { + private final X509TrustManager delegate; + private final String serverName; + + private SniTrustManager(X509TrustManager delegate, String serverName) { + this.delegate = delegate; + this.serverName = serverName; + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + delegate.checkServerTrusted(chain, authType); + checkServerName(chain); + } + + private void checkServerName(X509Certificate[] chain) throws CertificateException { + // JDK-internal retries can open new connections without repeating the HTTP-level name check. + if (!certificateMatchesServerName(chain, serverName)) { + throw new CertificateException("Token proxy certificate does not match AZURE_KUBERNETES_SNI_NAME."); + } + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + delegate.checkClientTrusted(chain, authType); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return delegate.getAcceptedIssuers(); + } + } + + private static final class SniExtendedTrustManager extends X509ExtendedTrustManager { + private final X509ExtendedTrustManager delegate; + private final SniTrustManager sniTrustManager; + + private SniExtendedTrustManager(X509ExtendedTrustManager delegate, String serverName) { + this.delegate = delegate; + this.sniTrustManager = new SniTrustManager(delegate, serverName); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { + sniTrustManager.checkServerTrusted(chain, authType); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + delegate.checkServerTrusted(chain, authType, socket); + sniTrustManager.checkServerName(chain); + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + delegate.checkServerTrusted(chain, authType, engine); + sniTrustManager.checkServerName(chain); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { + delegate.checkClientTrusted(chain, authType); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) + throws CertificateException { + delegate.checkClientTrusted(chain, authType, socket); + } + + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine) + throws CertificateException { + delegate.checkClientTrusted(chain, authType, engine); + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return delegate.getAcceptedIssuers(); + } + } + } diff --git a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponse.java b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponse.java index f31b859985e1a..6d94918cca3c6 100644 --- a/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponse.java +++ b/sdk/identity/azure-identity/src/main/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponse.java @@ -3,29 +3,34 @@ package com.azure.identity.implementation.customtokenproxy; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.io.UncheckedIOException; import java.net.HttpURLConnection; import java.nio.ByteBuffer; +import java.nio.channels.WritableByteChannel; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; +import java.util.Objects; import com.azure.core.http.HttpHeaderName; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; +import com.azure.core.util.BinaryData; import com.azure.core.util.logging.ClientLogger; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; public final class CustomTokenProxyHttpResponse extends HttpResponse { private static final ClientLogger LOGGER = new ClientLogger(CustomTokenProxyHttpResponse.class); - // private final HttpRequest request; private final int statusCode; private final HttpHeaders headers; private final HttpURLConnection connection; @@ -77,28 +82,48 @@ public HttpHeaders getHeaders() { @Override public Mono getBodyAsByteArray() { - return Mono.fromCallable(() -> { - if (cachedResponseBodyBytes != null) { - return cachedResponseBodyBytes; - } + return Mono.fromCallable(this::readResponseBody).subscribeOn(Schedulers.boundedElastic()); + } - InputStream stream = getResponseStream(); - if (stream == null) { - cachedResponseBodyBytes = new byte[0]; - return cachedResponseBodyBytes; - } + @Override + public BinaryData getBodyAsBinaryData() { + try { + return BinaryData.fromBytes(readResponseBody()); + } catch (IOException e) { + throw LOGGER.logExceptionAsError(new UncheckedIOException("Failed to read token proxy response body.", e)); + } + } - try (InputStream notNullStream = stream) { - ByteArrayOutputStream buffer = new ByteArrayOutputStream(); - int n; - byte[] temp = new byte[4096]; - while ((n = notNullStream.read(temp)) != -1) { - buffer.write(temp, 0, n); - } - cachedResponseBodyBytes = buffer.toByteArray(); - return cachedResponseBodyBytes; + @Override + public InputStream getBodyAsInputStreamSync() { + return getBodyAsBinaryData().toStream(); + } + + @Override + public void writeBodyTo(WritableByteChannel channel) throws IOException { + Objects.requireNonNull(channel, "'channel' must not be null."); + try { + BinaryData.fromBytes(readResponseBody()).writeTo(channel); + } finally { + close(); + } + } + + private synchronized byte[] readResponseBody() throws IOException { + if (cachedResponseBodyBytes != null) { + return cachedResponseBodyBytes; + } + + try (InputStream stream = getResponseStream()) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int n; + byte[] temp = new byte[4096]; + while ((n = stream.read(temp)) != -1) { + buffer.write(temp, 0, n); } - }); + cachedResponseBodyBytes = buffer.toByteArray(); + return cachedResponseBodyBytes; + } } @Override @@ -122,11 +147,12 @@ public void close() { } private InputStream getResponseStream() throws IOException { - try { + if (statusCode < 400) { + // JDK getInputStream() throws for HTTP errors, so we only check for non-error status codes return connection.getInputStream(); - } catch (IOException e) { - return connection.getErrorStream(); } + InputStream errorStream = connection.getErrorStream(); + return errorStream == null ? new ByteArrayInputStream(new byte[0]) : errorStream; } } diff --git a/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java b/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java index 3685fd3bc5f47..437f0f99bad18 100644 --- a/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java +++ b/sdk/identity/azure-identity/src/samples/java/com/azure/identity/credential/JavaDocCodeSnippets.java @@ -277,6 +277,17 @@ public void workloadIdentityCredentialCodeSnippets() { // END: com.azure.identity.credential.workloadidentitycredential.construct } + /** + * Creates a workload identity credential using the AKS webhook's identity binding configuration. + */ + public void workloadIdentityBindingCodeSnippets() { + // BEGIN: readme-sample-workloadidentitybinding + WorkloadIdentityCredential credential = new WorkloadIdentityCredentialBuilder() + .enableAzureProxy() + .build(); + // END: readme-sample-workloadidentitybinding + } + /** * Method to insert code snippets for {@link AzureDeveloperCliCredential} */ diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialIdentityBindingTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialIdentityBindingTest.java index ba206acdf5d30..727704de1619c 100644 --- a/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialIdentityBindingTest.java +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialIdentityBindingTest.java @@ -5,8 +5,20 @@ import com.azure.core.credential.AccessToken; import com.azure.core.credential.TokenRequestContext; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.FixedDelayOptions; +import com.azure.core.http.policy.RetryOptions; +import com.azure.core.test.http.MockHttpResponse; import com.azure.core.test.utils.TestConfigurationSource; import com.azure.core.util.Configuration; +import com.azure.core.util.Context; +import com.azure.identity.implementation.customtokenproxy.CustomTokenProxyHttpClient; +import com.azure.identity.implementation.customtokenproxy.ProxyConfig; import com.azure.identity.util.TestUtils; import io.netty.bootstrap.ServerBootstrap; import io.netty.buffer.ByteBuf; @@ -15,9 +27,8 @@ import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; -import io.netty.channel.MultiThreadIoEventLoopGroup; import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.channel.nio.NioIoHandler; +import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.handler.codec.http.DefaultFullHttpResponse; @@ -37,11 +48,20 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; import reactor.test.StepVerifier; -import javax.net.ssl.SSLEngine; +import javax.net.ssl.ExtendedSSLSession; +import javax.net.ssl.SNIServerName; +import javax.net.ssl.SSLSession; import java.io.InputStream; import java.net.InetSocketAddress; +import java.net.URL; +import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -50,13 +70,23 @@ import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.time.OffsetDateTime; +import java.time.Duration; import java.util.Base64; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.CopyOnWriteArrayList; import java.util.ArrayList; import java.util.List; import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Arrays; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * E2E test for WorkloadIdentityCredential with AKS Custom Token Proxy using Netty mock server. @@ -77,8 +107,8 @@ public class WorkloadIdentityCredentialIdentityBindingTest { @TempDir Path tempDir; - private MultiThreadIoEventLoopGroup bossGroup; - private MultiThreadIoEventLoopGroup workerGroup; + private NioEventLoopGroup bossGroup; + private NioEventLoopGroup workerGroup; private Channel serverChannel; private String serverBaseUrl; private Path tokenFilePath; @@ -87,6 +117,19 @@ public class WorkloadIdentityCredentialIdentityBindingTest { private AtomicInteger tokenRequestCount; private AtomicInteger metadataRequestCount; private X509Certificate certificate; + private volatile String lastRequestUri; + private volatile String lastRequestBody; + private volatile String lastRequestMethod; + private volatile String lastCustomHeader; + private volatile String lastServerName; + private volatile HttpResponseStatus responseStatus = HttpResponseStatus.OK; + private volatile String responseBodyOverride; + private volatile String redirectLocation; + private volatile boolean throttleFirstRequest; + private volatile boolean closeFirstTokenRequest; + private volatile SslContext retrySslContext; + private final AtomicInteger connectionCount = new AtomicInteger(); + private final List tokenRequestUris = new CopyOnWriteArrayList<>(); @BeforeEach public void setUp() throws Exception { @@ -120,12 +163,15 @@ public void setUp() throws Exception { public void cleanup() { if (serverChannel != null) { serverChannel.close().syncUninterruptibly(); + serverChannel = null; } if (bossGroup != null) { - bossGroup.shutdownGracefully(); + bossGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS).syncUninterruptibly(); + bossGroup = null; } if (workerGroup != null) { - workerGroup.shutdownGracefully(); + workerGroup.shutdownGracefully(0, 5, TimeUnit.SECONDS).syncUninterruptibly(); + workerGroup = null; } } @@ -220,6 +266,409 @@ public void testAksProxyWithCaData() { assertEquals(1, tokenRequestCount.get(), "Server should have received exactly one token request"); } + @Test + public void testAksProxyRoutesPublicAuthorityRequests() throws Exception { + WorkloadIdentityCredential credential + = new WorkloadIdentityCredentialBuilder().configuration(proxyConfiguration()).enableAzureProxy().build(); + + AccessToken token = credential.getTokenSync(tokenRequest()); + + assertEquals(MOCK_ACCESS_TOKEN, token.getToken()); + assertEquals("/" + TEST_TENANT_ID + "/oauth2/v2.0/token", lastRequestUri); + assertEquals(AKS_SNI_NAME, lastServerName); + Map form = parseForm(lastRequestBody); + assertEquals("client_credentials", form.get("grant_type")); + assertEquals(TEST_CLIENT_ID, form.get("client_id")); + assertEquals(new String(Files.readAllBytes(tokenFilePath), StandardCharsets.UTF_8), + form.get("client_assertion")); + assertTrue(Arrays.asList(form.get("scope").split(" ")).contains("https://management.azure.com/.default")); + assertEquals(1, tokenRequestCount.get(), tokenRequestUris::toString); + } + + @Test + public void testAksProxyCachesAsyncTokens() { + WorkloadIdentityCredential credential + = new WorkloadIdentityCredentialBuilder().configuration(proxyConfiguration()).enableAzureProxy().build(); + AccessToken token = credential.getToken(tokenRequest()).block(Duration.ofSeconds(30)); + assertNotNull(token); + int tokenRequests = tokenRequestCount.get(); + int metadataRequests = metadataRequestCount.get(); + assertTrue(tokenRequests > 0); + + AccessToken cached = credential.getToken(tokenRequest()).block(Duration.ofSeconds(30)); + + assertNotNull(cached); + assertEquals(token.getToken(), cached.getToken()); + assertEquals(tokenRequests, tokenRequestCount.get()); + assertEquals(metadataRequests, metadataRequestCount.get()); + } + + @Test + public void testAksProxySupportsConcurrentTokenRequests() { + WorkloadIdentityCredential credential + = new WorkloadIdentityCredentialBuilder().configuration(proxyConfiguration()).enableAzureProxy().build(); + + StepVerifier.create(Flux.range(0, 4).flatMap(ignored -> credential.getToken(tokenRequest())).collectList()) + .assertNext(tokens -> { + assertEquals(4, tokens.size()); + tokens.forEach(token -> { + assertEquals(MOCK_ACCESS_TOKEN, token.getToken()); + assertTrue(token.getExpiresAt().isAfter(OffsetDateTime.now())); + }); + }) + .expectComplete() + .verify(Duration.ofSeconds(30)); + assertTrue(tokenRequestCount.get() > 0); + } + + @Test + public void testAksProxyReadsRotatedServiceAccountToken() throws Exception { + WorkloadIdentityCredential credential + = new WorkloadIdentityCredentialBuilder().configuration(proxyConfiguration()).enableAzureProxy().build(); + credential.getTokenSync(tokenRequest()); + String rotatedAssertion = createMockFederatedToken() + "-rotated"; + Files.write(tokenFilePath, rotatedAssertion.getBytes(StandardCharsets.UTF_8)); + + credential.getTokenSync(new TokenRequestContext().addScopes("https://vault.azure.net/.default")); + + assertEquals(rotatedAssertion, parseForm(lastRequestBody).get("client_assertion")); + assertEquals(2, tokenRequestCount.get(), tokenRequestUris::toString); + } + + @Test + public void testAksProxyDisabledUsesDirectAuthentication() { + AtomicInteger directRequests = new AtomicInteger(); + HttpClient directClient = request -> { + assertEquals("login.microsoftonline.com", request.getUrl().getHost()); + directRequests.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 400, new HttpHeaders(), + "{\"error\":\"invalid_client\",\"error_description\":\"AADSTS700211: No matching federated identity.\"}" + .getBytes(StandardCharsets.UTF_8))); + }; + WorkloadIdentityCredential credential + = new WorkloadIdentityCredentialBuilder().configuration(proxyConfiguration()) + .httpClient(directClient) + .build(); + + RuntimeException exception + = assertThrows(RuntimeException.class, () -> credential.getTokenSync(tokenRequest())); + + assertTrue(exception.getMessage().contains("AADSTS700211")); + assertTrue(directRequests.get() > 0); + assertEquals(0, tokenRequestCount.get()); + assertEquals(0, metadataRequestCount.get()); + } + + @Test + public void testAksProxyOptInWithoutProxyConfigurationUsesDirectAuthentication() { + AtomicInteger directRequests = new AtomicInteger(); + HttpClient directClient = request -> { + assertEquals("login.microsoftonline.com", request.getUrl().getHost()); + directRequests.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 200, new HttpHeaders(), + "{\"access_token\":\"direct-token\",\"expires_in\":3600,\"token_type\":\"Bearer\"}" + .getBytes(StandardCharsets.UTF_8))); + }; + WorkloadIdentityCredential credential = new WorkloadIdentityCredentialBuilder().tenantId(TEST_TENANT_ID) + .clientId(TEST_CLIENT_ID) + .tokenFilePath(tokenFilePath.toString()) + .configuration(TestUtils.createTestConfiguration(new TestConfigurationSource())) + .httpClient(directClient) + .enableAzureProxy() + .build(); + + assertEquals("direct-token", credential.getTokenSync(tokenRequest()).getToken()); + assertTrue(directRequests.get() > 0); + assertEquals(0, tokenRequestCount.get()); + assertEquals(0, metadataRequestCount.get()); + } + + @ParameterizedTest + @CsvSource( + value = { + "''|/tenant/oauth2/v2.0/token", + "/|/tenant/oauth2/v2.0/token", + "/proxy|/proxy/tenant/oauth2/v2.0/token", + "/proxy/|/proxy/tenant/oauth2/v2.0/token", + "/api%2Fv1/token|/api%2Fv1/token/tenant/oauth2/v2.0/token" }, + delimiter = '|') + public void testAksProxyPreservesRequestAndEncodedPathAndQuery(String proxyPath, String expectedPath) + throws Exception { + String query = "?api-version=2.0&scope=a%2Fb&value=two%20words"; + CustomTokenProxyHttpClient client + = new CustomTokenProxyHttpClient(new ProxyConfig(new URL(serverBaseUrl + proxyPath), AKS_SNI_NAME, null, + caCertPemData.getBytes(StandardCharsets.UTF_8))); + String originalUrl = AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + "tenant/oauth2/v2.0/token" + query; + HttpRequest request = new HttpRequest(HttpMethod.POST, originalUrl) + .setHeader(HttpHeaderName.fromString("x-proxy-test"), "preserved") + .setBody("request-body"); + + for (int i = 0; i < 2; i++) { + try (HttpResponse response = client.sendSync(request, Context.NONE)) { + assertEquals(200, response.getStatusCode()); + assertEquals(serverBaseUrl + expectedPath + query, response.getRequest().getUrl().toString()); + assertFalse(response.getBodyAsBinaryData().toString().isEmpty()); + } + assertEquals(expectedPath + query, lastRequestUri); + assertEquals("request-body", lastRequestBody); + assertEquals("POST", lastRequestMethod); + assertEquals("preserved", lastCustomHeader); + assertEquals(originalUrl, request.getUrl().toString(), "Retries must not prepend the proxy path twice"); + } + assertEquals(2, tokenRequestCount.get()); + } + + @Test + public void testAksProxyRoutesMetadataGetRequests() throws Exception { + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + String path = "/" + TEST_TENANT_ID + "/v2.0/.well-known/openid-configuration"; + HttpRequest request + = new HttpRequest(HttpMethod.GET, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + path.substring(1)); + + try (HttpResponse response = client.sendSync(request, Context.NONE)) { + assertEquals(200, response.getStatusCode()); + assertEquals("application/json", response.getHeaderValue("Content-Type")); + assertTrue(response.getBodyAsBinaryData().toString().contains("token_endpoint")); + } + + assertEquals("GET", lastRequestMethod); + assertEquals(path, lastRequestUri); + assertEquals(1, metadataRequestCount.get()); + assertEquals(0, tokenRequestCount.get()); + } + + @Test + public void testAksProxyRoutesInstanceDiscoveryRequests() throws Exception { + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + String path = "/common/discovery/instance?api-version=1.1"; + HttpRequest request + = new HttpRequest(HttpMethod.GET, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + path.substring(1)); + + try (HttpResponse response = client.sendSync(request, Context.NONE)) { + assertEquals(200, response.getStatusCode()); + String body = response.getBodyAsBinaryData().toString(); + assertTrue(body.contains("\"tenant_discovery_endpoint\"")); + assertTrue(body.contains("\"preferred_network\":\"login.microsoftonline.com\"")); + } + + assertEquals("GET", lastRequestMethod); + assertEquals(path, lastRequestUri); + assertEquals(1, metadataRequestCount.get()); + assertEquals(0, tokenRequestCount.get()); + } + + @ParameterizedTest + @ValueSource(ints = { 400, 401, 403, 500 }) + public void testAksProxyPreservesErrorResponses(int status) throws Exception { + responseStatus = HttpResponseStatus.valueOf(status); + responseBodyOverride = "{\"error\":\"invalid_grant\",\"error_description\":\"Proxy denied the request\"}"; + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + HttpRequest request = new HttpRequest(HttpMethod.POST, + AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + TEST_TENANT_ID + "/oauth2/v2.0/token").setBody("request"); + + try (HttpResponse response = client.sendSync(request, Context.NONE)) { + assertEquals(status, response.getStatusCode()); + assertEquals(responseBodyOverride, response.getBodyAsBinaryData().toString()); + } + assertEquals(1, tokenRequestCount.get()); + } + + @Test + public void testAksProxyDoesNotFollowRedirects() throws Exception { + responseStatus = HttpResponseStatus.FOUND; + redirectLocation = serverBaseUrl + "/redirected"; + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + HttpRequest request = new HttpRequest(HttpMethod.POST, + AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + TEST_TENANT_ID + "/oauth2/v2.0/token").setBody("request"); + + try (HttpResponse response = client.sendSync(request, Context.NONE)) { + assertEquals(302, response.getStatusCode()); + assertEquals(redirectLocation, response.getHeaderValue("Location")); + assertFalse(response.getBodyAsBinaryData().toString().isEmpty()); + } + assertEquals(1, tokenRequestCount.get(), "Redirects must not forward the service account assertion"); + } + + @Test + public void testAksProxyPreservesPipelineRetries() { + throttleFirstRequest = true; + WorkloadIdentityCredential credential + = new WorkloadIdentityCredentialBuilder().configuration(proxyConfiguration(serverBaseUrl + "/proxy")) + .retryOptions(new RetryOptions(new FixedDelayOptions(1, Duration.ofMillis(1)))) + .enableAzureProxy() + .build(); + + assertEquals(MOCK_ACCESS_TOKEN, credential.getTokenSync(tokenRequest()).getToken()); + String path = "/proxy/" + TEST_TENANT_ID + "/oauth2/v2.0/token"; + assertEquals(Arrays.asList(path, path), tokenRequestUris); + } + + @Test + public void testAksProxyRetainsCaDuringMissingFileRotationGap() throws Exception { + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + sendProxyRequest(client); + + Files.delete(caCertFilePath); + + sendProxyRequest(client); + assertEquals(2, tokenRequestCount.get(), "A rotation gap must retain the previously loaded CA"); + } + + @Test + public void testAksProxyRetainsCaDuringEmptyFileRotationGap() throws Exception { + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + sendProxyRequest(client); + Files.write(caCertFilePath, new byte[0]); + + sendProxyRequest(client); + + assertEquals(2, tokenRequestCount.get()); + } + + @Test + public void testAksProxyReloadsCaAndDoesNotTrustReplacedCa() throws Exception { + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + sendProxyRequest(client); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream stream = getClass().getResourceAsStream("/test-aks-cert-mismatch.p12")) { + assertNotNull(stream); + keyStore.load(stream, "password".toCharArray()); + } + X509Certificate replacement = (X509Certificate) keyStore.getCertificate("test-cert"); + Files.write(caCertFilePath, toPemFormat(replacement).getBytes(StandardCharsets.UTF_8)); + + assertThrows(RuntimeException.class, () -> sendProxyRequest(client)); + assertEquals(1, tokenRequestCount.get(), "The previous CA must no longer be trusted"); + Files.write(caCertFilePath, caCertPemData.getBytes(StandardCharsets.UTF_8)); + sendProxyRequest(client); + assertEquals(2, tokenRequestCount.get()); + } + + @Test + public void testAksProxyInvalidCaRotationFailsInsteadOfFallingBack() throws Exception { + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + sendProxyRequest(client); + Files.write(caCertFilePath, "not-a-certificate".getBytes(StandardCharsets.UTF_8)); + + assertThrows(IllegalStateException.class, () -> sendProxyRequest(client)); + assertEquals(1, tokenRequestCount.get()); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + public void testAksProxyMissingOrEmptyInitialCaDoesNotUseDefaultTrust(boolean missing) throws Exception { + if (missing) { + Files.delete(caCertFilePath); + } else { + Files.write(caCertFilePath, new byte[0]); + } + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient( + new ProxyConfig(new URL(serverBaseUrl), AKS_SNI_NAME, caCertFilePath.toString(), null)); + + assertThrows(IllegalStateException.class, () -> sendProxyRequest(client)); + assertEquals(0, tokenRequestCount.get()); + } + + @Test + public void testAksProxyRejectsPartiallyMalformedCaBundle() throws Exception { + String invalidBundle + = caCertPemData + "-----BEGIN CERTIFICATE-----\nINVALID_BASE64_DATA\n-----END CERTIFICATE-----\n"; + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient(new ProxyConfig(new URL(serverBaseUrl), + AKS_SNI_NAME, null, invalidBundle.getBytes(StandardCharsets.UTF_8))); + + assertThrows(RuntimeException.class, () -> sendProxyRequest(client)); + assertEquals(0, tokenRequestCount.get()); + } + + @Test + public void testAksProxyRejectsWrongSniEvenWhenCertificateMatchesProxyUrl() throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream stream = getClass().getResourceAsStream("/test-aks-cert-no-sni.p12")) { + assertNotNull(stream); + keyStore.load(stream, "password".toCharArray()); + } + X509Certificate localhostCertificate = (X509Certificate) keyStore.getCertificate("test-cert"); + startNettyHttpsServer((PrivateKey) keyStore.getKey("test-cert", "password".toCharArray()), + localhostCertificate); + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient(new ProxyConfig(new URL(serverBaseUrl), + MISMATCHED_CERT_SAN, null, toPemFormat(localhostCertificate).getBytes(StandardCharsets.UTF_8))); + + assertThrows(RuntimeException.class, () -> sendProxyRequest(client)); + assertEquals(0, tokenRequestCount.get(), "The assertion must not be sent to a host with the wrong TLS name"); + } + + @ParameterizedTest + @ValueSource(booleans = { false, true }) + public void testAksProxyValidatesSniOnAutomaticPostRetry(boolean matchingServerName) throws Exception { + String resource = matchingServerName ? "/test-aks-cert.p12" : "/test-aks-cert-no-sni.p12"; + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream stream = getClass().getResourceAsStream(resource)) { + assertNotNull(stream); + keyStore.load(stream, "password".toCharArray()); + } + X509Certificate retryCertificate = (X509Certificate) keyStore.getCertificate("test-cert"); + retrySslContext = SslContextBuilder + .forServer((PrivateKey) keyStore.getKey("test-cert", "password".toCharArray()), retryCertificate) + .sslProvider(SslProvider.JDK) + .build(); + closeFirstTokenRequest = true; + String trustedCertificates = caCertPemData + toPemFormat(retryCertificate); + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient(new ProxyConfig(new URL(serverBaseUrl), + AKS_SNI_NAME, null, trustedCertificates.getBytes(StandardCharsets.UTF_8))); + + if (matchingServerName) { + sendProxyRequest(client); + assertEquals(2, tokenRequestCount.get(), "A retry with a matching TLS name must still succeed"); + } else { + assertThrows(RuntimeException.class, () -> sendProxyRequest(client)); + assertEquals(1, tokenRequestCount.get(), + "The retried assertion must not reach a trusted server with the wrong TLS name"); + } + assertTrue(connectionCount.get() >= 2, "The JDK must establish a new TLS connection for the retry"); + } + + @ParameterizedTest + @CsvSource({ + "proxy.example.com, true", + "PROXY.EXAMPLE.COM, true", + "example.com, false", + "nested.proxy.example.com, false", + "proxy.example.net, false" }) + public void testAksProxyValidatesWildcardSniBeforeSendingRequest(String serverName, boolean matches) + throws Exception { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream stream = getClass().getResourceAsStream("/test-aks-cert-wildcard.p12")) { + assertNotNull(stream); + keyStore.load(stream, "password".toCharArray()); + } + X509Certificate wildcardCertificate = (X509Certificate) keyStore.getCertificate("test-cert"); + List dnsNames = fetchCertificateSAN(wildcardCertificate); + assertTrue(dnsNames.contains("localhost")); + assertTrue(dnsNames.contains("*.example.com")); + startNettyHttpsServer((PrivateKey) keyStore.getKey("test-cert", "password".toCharArray()), wildcardCertificate); + + // The localhost SAN allows URL-host verification to succeed independently of the configured SNI name. + CustomTokenProxyHttpClient client = new CustomTokenProxyHttpClient(new ProxyConfig(new URL(serverBaseUrl), + serverName, null, toPemFormat(wildcardCertificate).getBytes(StandardCharsets.UTF_8))); + + if (matches) { + sendProxyRequest(client); + assertEquals(serverName, lastServerName); + assertEquals(1, tokenRequestCount.get()); + } else { + assertThrows(RuntimeException.class, () -> sendProxyRequest(client)); + assertEquals(0, tokenRequestCount.get(), "The assertion must not be sent for an unrelated TLS name"); + } + } + @Test public void testAksProxyWithInvalidTokenFile() { Path nonExistentTokenFile = tempDir.resolve("non-existent-token.jwt"); @@ -541,11 +990,12 @@ private List fetchCertificateSAN(X509Certificate certificate) throws Cer } private void startNettyHttpsServer(PrivateKey privateKey, X509Certificate certificate) throws Exception { + cleanup(); SslContext sslContext - = SslContextBuilder.forServer(privateKey, certificate).sslProvider(SslProvider.OPENSSL).build(); + = SslContextBuilder.forServer(privateKey, certificate).sslProvider(SslProvider.JDK).build(); - bossGroup = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()); - workerGroup = new MultiThreadIoEventLoopGroup(NioIoHandler.newFactory()); + bossGroup = new NioEventLoopGroup(1); + workerGroup = new NioEventLoopGroup(2); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) @@ -555,13 +1005,10 @@ private void startNettyHttpsServer(PrivateKey privateKey, X509Certificate certif protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); - SslHandler sslHandler = sslContext.newHandler(ch.alloc()); - - sslHandler.handshakeFuture().addListener(future -> { - if (future.isSuccess()) { - SSLEngine engine = sslHandler.engine(); - } - }); + SslContext connectionContext = connectionCount.incrementAndGet() > 1 && retrySslContext != null + ? retrySslContext + : sslContext; + SslHandler sslHandler = connectionContext.newHandler(ch.alloc()); pipeline.addLast(sslHandler); pipeline.addLast(new HttpServerCodec()); @@ -580,9 +1027,29 @@ private class HttpRequestHandler extends SimpleChannelInboundHandler serverNames = ((ExtendedSSLSession) session).getRequestedServerNames(); + if (!serverNames.isEmpty()) { + lastServerName = new String(serverNames.get(0).getEncoded(), StandardCharsets.US_ASCII); + } + } String responseBody; - if (uri.contains("/.well-known/openid-configuration")) { + // MSAL can request instance metadata before the token endpoint when its shared cache is cold. + if (uri.contains("/common/discovery/instance")) { + metadataRequestCount.incrementAndGet(); + responseBody + = String.format("{\"tenant_discovery_endpoint\":\"https://login.microsoftonline.com/%s/v2.0/" + + ".well-known/openid-configuration\",\"api-version\":\"1.1\",\"metadata\":[" + + "{\"preferred_network\":\"login.microsoftonline.com\"," + + "\"preferred_cache\":\"login.windows.net\",\"aliases\":[\"login.microsoftonline.com\"," + + "\"login.windows.net\",\"login.microsoft.com\",\"sts.windows.net\"]}]}", TEST_TENANT_ID); + } else if (uri.contains("/.well-known/openid-configuration")) { metadataRequestCount.incrementAndGet(); String base = serverBaseUrl + "/" + TEST_TENANT_ID; responseBody = String @@ -590,16 +1057,32 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) + " \"authorization_endpoint\": \"%s/oauth2/v2.0/authorize\"%n" + "}", base, base, base); } else { tokenRequestCount.incrementAndGet(); + tokenRequestUris.add(uri); + if (closeFirstTokenRequest && tokenRequestCount.get() == 1) { + ctx.close(); + return; + } responseBody = String.format( "{\"token_type\":\"Bearer\",\"expires_in\":3600,\"ext_expires_in\":3600,\"access_token\":\"%s\"}", MOCK_ACCESS_TOKEN); } + if (responseBodyOverride != null) { + responseBody = responseBodyOverride; + } + HttpResponseStatus status = throttleFirstRequest && tokenRequestCount.get() == 1 + ? HttpResponseStatus.TOO_MANY_REQUESTS + : responseStatus; ByteBuf content = Unpooled.copiedBuffer(responseBody, CharsetUtil.UTF_8); - FullHttpResponse response - = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content); + FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content); response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json"); response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); + if (redirectLocation != null) { + response.headers().set(HttpHeaderNames.LOCATION, redirectLocation); + } + if (status.equals(HttpResponseStatus.TOO_MANY_REQUESTS)) { + response.headers().set(HttpHeaderNames.RETRY_AFTER, "0"); + } ctx.writeAndFlush(response); } @@ -618,6 +1101,42 @@ private String toPemFormat(X509Certificate certificate) throws Exception { + "\n-----END CERTIFICATE-----\n"; } + private void sendProxyRequest(CustomTokenProxyHttpClient client) { + HttpRequest request = new HttpRequest(HttpMethod.POST, + AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + TEST_TENANT_ID + "/oauth2/v2.0/token").setBody("request"); + try (HttpResponse response = client.sendSync(request, Context.NONE)) { + assertEquals(200, response.getStatusCode()); + assertFalse(response.getBodyAsBinaryData().toString().isEmpty()); + } + } + + private Configuration proxyConfiguration() { + return proxyConfiguration(serverBaseUrl); + } + + private Configuration proxyConfiguration(String proxyUrl) { + return TestUtils + .createTestConfiguration(new TestConfigurationSource().put("AZURE_KUBERNETES_TOKEN_PROXY", proxyUrl) + .put("AZURE_KUBERNETES_CA_FILE", caCertFilePath.toString()) + .put("AZURE_KUBERNETES_SNI_NAME", AKS_SNI_NAME) + .put(Configuration.PROPERTY_AZURE_CLIENT_ID, TEST_CLIENT_ID) + .put(Configuration.PROPERTY_AZURE_TENANT_ID, TEST_TENANT_ID) + .put("AZURE_FEDERATED_TOKEN_FILE", tokenFilePath.toString())); + } + + private TokenRequestContext tokenRequest() { + return new TokenRequestContext().addScopes("https://management.azure.com/.default"); + } + + private Map parseForm(String body) throws Exception { + Map fields = new HashMap<>(); + for (String field : body.split("&")) { + String[] pair = field.split("=", 2); + fields.put(URLDecoder.decode(pair[0], "UTF-8"), URLDecoder.decode(pair[1], "UTF-8")); + } + return fields; + } + private String createMockFederatedToken() { String header = Base64.getUrlEncoder() .withoutPadding() diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialTest.java index 1e5470ab0e402..242589cdd2eb5 100644 --- a/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialTest.java +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialTest.java @@ -5,6 +5,12 @@ import com.azure.core.credential.AccessToken; import com.azure.core.credential.TokenRequestContext; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.ProxyOptions; +import com.azure.core.test.http.MockHttpResponse; import com.azure.core.test.utils.TestConfigurationSource; import com.azure.core.util.Configuration; import com.azure.identity.implementation.IdentityClient; @@ -19,17 +25,20 @@ import reactor.test.StepVerifier; import java.io.IOException; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class WorkloadIdentityCredentialTest { @@ -545,4 +554,89 @@ public void testProxyEnabledWithSniNameGetsToken(@TempDir Path tempDir) throws I } } + @Test + public void testProxyDoesNotMutateBuilderHttpClient() { + HttpClient httpClient = mock(HttpClient.class); + Configuration proxyConfiguration = TestUtils + .createTestConfiguration(new TestConfigurationSource().put(ENV_PROXY_URL, "https://proxy.example.com")); + WorkloadIdentityCredentialBuilder builder = new WorkloadIdentityCredentialBuilder().tenantId("tenant") + .clientId(CLIENT_ID) + .tokenFilePath("token.jwt") + .configuration(proxyConfiguration) + .httpClient(httpClient) + .enableAzureProxy(); + + builder.build(); + + Assertions.assertSame(httpClient, builder.identityClientOptions.getHttpClient()); + builder.configuration(TestUtils.createTestConfiguration(new TestConfigurationSource())).build(); + Assertions.assertSame(httpClient, builder.identityClientOptions.getHttpClient()); + } + + @Test + public void testProxyEnabledWithCustomPipelineUsesPipelineTransport(@TempDir Path tempDir) throws IOException { + Path tokenFile = tempDir.resolve("token.jwt"); + Files.write(tokenFile, "dummy-token".getBytes(StandardCharsets.UTF_8)); + AtomicInteger requests = new AtomicInteger(); + HttpClient pipelineClient = request -> { + Assertions.assertEquals("login.microsoftonline.com", request.getUrl().getHost()); + requests.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 200, new HttpHeaders(), + "{\"access_token\":\"pipeline-token\",\"expires_in\":3600,\"token_type\":\"Bearer\"}" + .getBytes(StandardCharsets.UTF_8))); + }; + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(pipelineClient).build(); + WorkloadIdentityCredentialBuilder builder = new WorkloadIdentityCredentialBuilder().tenantId("tenant") + .clientId(CLIENT_ID) + .tokenFilePath(tokenFile.toString()) + .configuration(TestUtils + .createTestConfiguration(new TestConfigurationSource().put(ENV_PROXY_URL, "https://proxy.example.com") + .put(Configuration.PROPERTY_AZURE_AUTHORITY_HOST, AzureAuthorityHosts.AZURE_PUBLIC_CLOUD))) + .pipeline(pipeline) + .disableInstanceDiscovery() + .enableAzureProxy(); + + WorkloadIdentityCredential credential = Assertions.assertDoesNotThrow(builder::build); + TokenRequestContext request = new TokenRequestContext().addScopes("https://management.azure.com/.default"); + + Assertions.assertEquals("pipeline-token", credential.getTokenSync(request).getToken()); + StepVerifier.create(credential.getToken(request)) + .expectNextMatches(token -> "pipeline-token".equals(token.getToken())) + .verifyComplete(); + assertTrue(requests.get() > 0); + Assertions.assertSame(pipeline, builder.identityClientOptions.getHttpPipeline()); + } + + @Test + public void testProxyEnabledWithLegacyProxyOptionsDoesNotThrow() { + ProxyOptions proxyOptions = new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888)); + WorkloadIdentityCredentialBuilder builder = new WorkloadIdentityCredentialBuilder().tenantId("tenant") + .clientId(CLIENT_ID) + .tokenFilePath("token.jwt") + .configuration(TestUtils + .createTestConfiguration(new TestConfigurationSource().put(ENV_PROXY_URL, "https://proxy.example.com"))) + .proxyOptions(proxyOptions) + .enableAzureProxy(); + + assertNotNull(Assertions.assertDoesNotThrow(builder::build)); + Assertions.assertSame(proxyOptions, builder.identityClientOptions.getProxyOptions()); + } + + @Test + public void testProxySettingsAreIgnoredWithoutExplicitOptIn() { + Configuration configuration + = TestUtils.createTestConfiguration(new TestConfigurationSource().put(ENV_PROXY_URL, "http://invalid-proxy") + .put(ENV_CA_FILE, "missing.pem") + .put(ENV_CA_DATA, "invalid-data") + .put(Configuration.PROPERTY_AZURE_CLIENT_ID, CLIENT_ID) + .put(Configuration.PROPERTY_AZURE_TENANT_ID, "tenant") + .put("AZURE_FEDERATED_TOKEN_FILE", "token.jwt")); + + Assertions + .assertDoesNotThrow(() -> new WorkloadIdentityCredentialBuilder().configuration(configuration).build()); + Assertions.assertDoesNotThrow(() -> new DefaultAzureCredentialBuilder().configuration(configuration).build()); + Assertions + .assertDoesNotThrow(() -> new ManagedIdentityCredentialBuilder().configuration(configuration).build()); + } + } diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfigurationTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfigurationTest.java new file mode 100644 index 0000000000000..14196d74f30d3 --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfigurationTest.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.implementation.customtokenproxy; + +import com.azure.core.test.utils.TestConfigurationSource; +import com.azure.core.util.Configuration; +import com.azure.identity.util.TestUtils; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CustomTokenProxyConfigurationTest { + private static final String PROXY_URL = "AZURE_KUBERNETES_TOKEN_PROXY"; + private static final String CA_FILE = "AZURE_KUBERNETES_CA_FILE"; + private static final String CA_DATA = "AZURE_KUBERNETES_CA_DATA"; + private static final String SNI_NAME = "AZURE_KUBERNETES_SNI_NAME"; + + @Test + public void noConfigurationUsesDirectAuthentication() { + assertNull(CustomTokenProxyConfiguration + .parseAndValidate(TestUtils.createTestConfiguration(new TestConfigurationSource()))); + } + + @ParameterizedTest + @ValueSource(strings = { CA_FILE, CA_DATA, SNI_NAME }) + public void partialConfigurationFails(String setting) { + Configuration configuration + = TestUtils.createTestConfiguration(new TestConfigurationSource().put(setting, "configured-value")); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, + () -> CustomTokenProxyConfiguration.parseAndValidate(configuration)); + assertTrue(exception.getMessage().contains(PROXY_URL)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "http://proxy.example.com", + "not-a-url", + "https:/proxy/path", + "https:///proxy/path", + "https://proxy.example.com:65536/path", + "https://proxy.example.com:invalid/path", + "https://user:password@proxy.example.com/path", + "https://proxy.example.com/path?query=value", + "https://proxy.example.com/path#fragment" }) + public void invalidProxyUrlFails(String url) { + Configuration configuration + = TestUtils.createTestConfiguration(new TestConfigurationSource().put(PROXY_URL, url)); + + assertThrows(IllegalArgumentException.class, + () -> CustomTokenProxyConfiguration.parseAndValidate(configuration)); + } + + @ParameterizedTest + @ValueSource( + strings = { + "https://proxy.example.com", + "HTTPS://proxy.example.com", + "https://proxy.example.com:8443/api%2Ftoken", + "https://[::1]:8443/proxy" }) + public void validProxyUrlPreservesEndpoint(String url) { + Configuration configuration = TestUtils + .createTestConfiguration(new TestConfigurationSource().put(PROXY_URL, url).put(SNI_NAME, "proxy.ests.aks")); + + ProxyConfig proxyConfig = CustomTokenProxyConfiguration.parseAndValidate(configuration); + + assertEquals("proxy.ests.aks", proxyConfig.getSniName()); + assertEquals(url.substring(url.indexOf("://") + 3), + proxyConfig.getTokenProxyUrl().toString().substring("https://".length())); + } + + @Test + public void conflictingCaSourcesFail() { + Configuration configuration = TestUtils + .createTestConfiguration(new TestConfigurationSource().put(PROXY_URL, "https://proxy.example.com") + .put(CA_FILE, "ca.pem") + .put(CA_DATA, "certificate")); + + assertThrows(IllegalArgumentException.class, + () -> CustomTokenProxyConfiguration.parseAndValidate(configuration)); + } + + @Test + public void missingCaFileFails(@TempDir Path directory) { + Configuration configuration = TestUtils + .createTestConfiguration(new TestConfigurationSource().put(PROXY_URL, "https://proxy.example.com") + .put(CA_FILE, directory.resolve("missing.pem").toString())); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, + () -> CustomTokenProxyConfiguration.parseAndValidate(configuration)); + assertTrue(exception.getMessage().contains(CA_FILE)); + } + + @Test + public void existingCaFileIsPreserved(@TempDir Path directory) throws IOException { + Path caFile = directory.resolve("ca.pem"); + Files.write(caFile, "certificate".getBytes(StandardCharsets.UTF_8)); + Configuration configuration = TestUtils.createTestConfiguration( + new TestConfigurationSource().put(PROXY_URL, "https://proxy.example.com").put(CA_FILE, caFile.toString())); + + assertEquals(caFile.toString(), CustomTokenProxyConfiguration.parseAndValidate(configuration).getCaFile()); + } + + @ParameterizedTest + @ValueSource(strings = { " ", "\t", "\r\n" }) + public void whitespaceCaDataFails(String caData) { + Configuration configuration = TestUtils.createTestConfiguration( + new TestConfigurationSource().put(PROXY_URL, "https://proxy.example.com").put(CA_DATA, caData)); + + IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, + () -> CustomTokenProxyConfiguration.parseAndValidate(configuration)); + assertTrue(exception.getMessage().contains(CA_DATA)); + } +} diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClientTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClientTest.java new file mode 100644 index 0000000000000..843a0920ca18f --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClientTest.java @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.implementation.customtokenproxy; + +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import com.azure.core.http.HttpResponse; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.core.util.Context; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; + +import java.net.MalformedURLException; +import java.net.URL; +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class CustomTokenProxyHttpClientTest { + @ParameterizedTest + @CsvSource({ + "proxy.example.com, proxy.example.com, true", + "PROXY.EXAMPLE.COM, proxy.example.com, true", + "proxy.example.com, unrelated.example.com, false", + "proxy.example.com, *.example.com, true", + "PROXY.EXAMPLE.COM, *.example.com, true", + "proxy.example.com, *.EXAMPLE.COM, true", + "xn--bcher-kva.example.com, *.example.com, true", + "b\u00FCcher.example.com, *.example.com, true", + "example.com, *.example.com, false", + "nested.proxy.example.com, *.example.com, false", + "proxy.example.net, *.example.com, false", + "badexample.com, *.example.com, false", + ".example.com, *.example.com, false", + "-proxy.example.com, *.example.com, false", + "proxy-.example.com, *.example.com, false", + "proxy .example.com, *.example.com, false", + "127.0.0.1, *.0.0.1, false", + "proxy.example.com, p*.example.com, false", + "proxy.example.com, example.*.com, false", + "proxy.example.com, *.*.com, false", + "proxy.example.com, *, false", + "proxy.example.com, *., false", + "*.example.com, *.example.com, false" }) + public void matchesDnsName(String serverName, String certificateName, boolean matches) { + assertEquals(matches, CustomTokenProxyHttpClient.matchesDnsName(serverName, certificateName)); + } + + @Test + public void preservesLiteralServerNamesWithoutDnsNormalization() { + String label = String.join("", Collections.nCopies(63, "a")); + String serverName = "a" + label + ".example.com"; + + assertTrue(CustomTokenProxyHttpClient.matchesDnsName(label + ".example.com", "*.example.com")); + assertTrue(CustomTokenProxyHttpClient.matchesDnsName(serverName, serverName)); + assertFalse(CustomTokenProxyHttpClient.matchesDnsName(serverName, "*.example.com")); + } + + @Test + public void asyncSendOffloadsBlockingIoAndPreservesContext() throws MalformedURLException { + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://login.microsoftonline.com/tenant/token"); + Context context = new Context("test-context", "value"); + AtomicInteger requests = new AtomicInteger(); + CustomTokenProxyHttpClient client + = new CustomTokenProxyHttpClient(new ProxyConfig(new URL("https://proxy.example.com"), null, null, null)) { + @Override + public HttpResponse sendSync(HttpRequest actualRequest, Context actualContext) { + assertFalse(Schedulers.isInNonBlockingThread(), "Proxy I/O must not run on an event-loop thread"); + assertSame(request, actualRequest); + assertSame(context, actualContext); + requests.incrementAndGet(); + return new MockHttpResponse(actualRequest, 200); + } + }; + + Mono response = client.send(request, context); + assertEquals(0, requests.get(), "Requests must remain lazy until subscription"); + + StepVerifier.create(response.subscribeOn(Schedulers.parallel())) + .assertNext(result -> assertEquals(200, result.getStatusCode())) + .expectComplete() + .verify(Duration.ofSeconds(10)); + assertEquals(1, requests.get()); + } +} diff --git a/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponseTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponseTest.java new file mode 100644 index 0000000000000..7799e2b56e528 --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponseTest.java @@ -0,0 +1,155 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.identity.implementation.customtokenproxy; + +import com.azure.core.http.HttpMethod; +import com.azure.core.http.HttpRequest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.api.parallel.Isolated; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Scheduler; +import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; + +import javax.net.ssl.HttpsURLConnection; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.channels.Channels; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@Execution(ExecutionMode.SAME_THREAD) +@Isolated("Temporarily replaces the shared Reactor scheduler factory") +public class CustomTokenProxyHttpResponseTest { + @ParameterizedTest + @ValueSource(strings = { "binary", "stream", "channel" }) + public void synchronousBodyReadCompletesWithFullBoundedElasticPool(String accessor) throws IOException { + HttpsURLConnection connection = mockConnection(200); + AtomicReference callingThread = new AtomicReference<>(); + when(connection.getInputStream()).thenAnswer(invocation -> { + assertSame(callingThread.get(), Thread.currentThread(), "Synchronous I/O must stay on the calling thread"); + return new ByteArrayInputStream("response".getBytes(StandardCharsets.UTF_8)); + }); + CustomTokenProxyHttpResponse response = new CustomTokenProxyHttpResponse( + new HttpRequest(HttpMethod.GET, "https://proxy.example.com/token"), connection); + Schedulers.Snapshot snapshot = Schedulers.setFactoryWithSnapshot(new Schedulers.Factory() { + @Override + public Scheduler newBoundedElastic(int threadCap, int queuedTaskCap, ThreadFactory threadFactory, + int ttlSeconds) { + return Schedulers.Factory.super.newBoundedElastic(1, queuedTaskCap, threadFactory, ttlSeconds); + } + }); + try { + String body = Mono.fromCallable(() -> { + callingThread.set(Thread.currentThread()); + if ("binary".equals(accessor)) { + return response.getBodyAsBinaryData().toString(); + } + if ("stream".equals(accessor)) { + try (InputStream stream = response.getBodyAsInputStreamSync()) { + byte[] bytes = new byte[8]; + assertEquals(bytes.length, stream.read(bytes)); + return new String(bytes, StandardCharsets.UTF_8); + } + } + ByteArrayOutputStream output = new ByteArrayOutputStream(); + response.writeBodyTo(Channels.newChannel(output)); + return output.toString(StandardCharsets.UTF_8.name()); + }).subscribeOn(Schedulers.boundedElastic()).block(Duration.ofSeconds(5)); + + assertEquals("response", body); + assertEquals("response", response.getBodyAsBinaryData().toString()); + assertEquals("response", response.getBodyAsString().block(Duration.ofSeconds(5))); + verify(connection, times(1)).getInputStream(); + } finally { + Schedulers.resetFrom(snapshot); + response.close(); + } + } + + @Test + public void asyncBodyReadOffloadsBlockingIoAndCachesBody() throws IOException { + HttpsURLConnection connection = mockConnection(200); + when(connection.getInputStream()).thenAnswer(invocation -> { + assertFalse(Schedulers.isInNonBlockingThread(), "Response I/O must not run on an event-loop thread"); + return new ByteArrayInputStream("response".getBytes(StandardCharsets.UTF_8)); + }); + CustomTokenProxyHttpResponse response = new CustomTokenProxyHttpResponse( + new HttpRequest(HttpMethod.GET, "https://proxy.example.com/token"), connection); + + StepVerifier.create(response.getBodyAsString().subscribeOn(Schedulers.parallel())) + .expectNext("response") + .expectComplete() + .verify(Duration.ofSeconds(10)); + StepVerifier.create(response.getBodyAsString()).expectNext("response").verifyComplete(); + verify(connection, times(1)).getInputStream(); + response.close(); + verify(connection).disconnect(); + } + + @Test + public void ioFailureWithoutErrorBodyIsNotAnEmptySuccess() throws IOException { + HttpsURLConnection connection = mockConnection(200); + IOException failure = new IOException("Response read failed"); + when(connection.getInputStream()).thenThrow(failure); + CustomTokenProxyHttpResponse response = new CustomTokenProxyHttpResponse( + new HttpRequest(HttpMethod.GET, "https://proxy.example.com/token"), connection); + + StepVerifier.create(response.getBodyAsByteArray()).expectErrorMatches(error -> error == failure).verify(); + assertSame(failure, assertThrows(UncheckedIOException.class, response::getBodyAsBinaryData).getCause()); + assertSame(failure, assertThrows(UncheckedIOException.class, response::getBodyAsInputStreamSync).getCause()); + assertSame(failure, assertThrows(IOException.class, + () -> response.writeBodyTo(Channels.newChannel(new ByteArrayOutputStream())))); + } + + @Test + public void errorResponseBodyIsPreserved() throws IOException { + HttpsURLConnection connection = mockConnection(400); + when(connection.getErrorStream()) + .thenReturn(new ByteArrayInputStream("{\"error\":\"invalid_grant\"}".getBytes(StandardCharsets.UTF_8))); + CustomTokenProxyHttpResponse response = new CustomTokenProxyHttpResponse( + new HttpRequest(HttpMethod.POST, "https://proxy.example.com/token"), connection); + + StepVerifier.create(response.getBodyAsString()).expectNext("{\"error\":\"invalid_grant\"}").verifyComplete(); + assertEquals("{\"error\":\"invalid_grant\"}", response.getBodyAsBinaryData().toString()); + } + + @ParameterizedTest + @ValueSource(ints = { 400, 401, 403, 500 }) + public void errorStatusWithoutBodyIsPreserved(int status) throws IOException { + HttpsURLConnection connection = mockConnection(status); + CustomTokenProxyHttpResponse response = new CustomTokenProxyHttpResponse( + new HttpRequest(HttpMethod.POST, "https://proxy.example.com/token"), connection); + + assertEquals(status, response.getStatusCode()); + StepVerifier.create(response.getBodyAsString()).expectNext("").verifyComplete(); + assertEquals("", response.getBodyAsBinaryData().toString()); + } + + private HttpsURLConnection mockConnection(int status) throws IOException { + HttpsURLConnection connection = mock(HttpsURLConnection.class); + when(connection.getResponseCode()).thenReturn(status); + when(connection.getHeaderFields()).thenReturn(Collections.emptyMap()); + return connection; + } +} diff --git a/sdk/identity/azure-identity/src/test/resources/test-aks-cert-wildcard.p12 b/sdk/identity/azure-identity/src/test/resources/test-aks-cert-wildcard.p12 new file mode 100644 index 0000000000000..f84f73dc44d14 Binary files /dev/null and b/sdk/identity/azure-identity/src/test/resources/test-aks-cert-wildcard.p12 differ diff --git a/sdk/identity/live-test-apps/identity-test-container/pom.xml b/sdk/identity/live-test-apps/identity-test-container/pom.xml index 7d7f2643dfae2..83a0558e64f73 100644 --- a/sdk/identity/live-test-apps/identity-test-container/pom.xml +++ b/sdk/identity/live-test-apps/identity-test-container/pom.xml @@ -18,7 +18,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 diff --git a/sdk/identity/live-test-apps/identity-test-function/pom.xml b/sdk/identity/live-test-apps/identity-test-function/pom.xml index d209bb33999c8..330e073eda46d 100644 --- a/sdk/identity/live-test-apps/identity-test-function/pom.xml +++ b/sdk/identity/live-test-apps/identity-test-function/pom.xml @@ -24,7 +24,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 com.azure diff --git a/sdk/identity/live-test-apps/identity-test-vm/pom.xml b/sdk/identity/live-test-apps/identity-test-vm/pom.xml index 17baf12d0e49a..6ea0d71d10d51 100644 --- a/sdk/identity/live-test-apps/identity-test-vm/pom.xml +++ b/sdk/identity/live-test-apps/identity-test-vm/pom.xml @@ -18,7 +18,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 diff --git a/sdk/identity/live-test-apps/identity-test-webapp/pom.xml b/sdk/identity/live-test-apps/identity-test-webapp/pom.xml index b3f4d00501fc8..316e35a45549f 100644 --- a/sdk/identity/live-test-apps/identity-test-webapp/pom.xml +++ b/sdk/identity/live-test-apps/identity-test-webapp/pom.xml @@ -29,7 +29,7 @@ com.azure azure-identity - 1.19.0-beta.3 + 1.19.0 com.azure