From fc30373cfe83bf712d12d8acd5d20503ce76b80f Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Tue, 20 Oct 2026 16:11:10 -0700 Subject: [PATCH 01/14] Fix AKS identity binding proxy configuration --- .../WorkloadIdentityCredentialBuilder.java | 14 +- .../CustomTokenProxyConfiguration.java | 38 ++++-- .../WorkloadIdentityCredentialTest.java | 71 ++++++++++ .../CustomTokenProxyConfigurationTest.java | 127 ++++++++++++++++++ 4 files changed, 234 insertions(+), 16 deletions(-) create mode 100644 sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyConfigurationTest.java 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..c294efe99a004 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; @@ -87,6 +88,8 @@ 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. + * @throws IllegalStateException if identity bindings are combined with a custom pipeline or legacy proxy options. */ public WorkloadIdentityCredential build() { Configuration configuration = identityClientOptions.getConfiguration() == null @@ -105,14 +108,19 @@ 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)); + if (options.getHttpPipeline() != null || options.getProxyOptions() != null) { + throw LOGGER.logExceptionAsError(new IllegalStateException( + "AKS identity bindings cannot be combined with a custom HTTP pipeline or legacy proxyOptions. " + + "Use addPolicy to configure policies on the credential's HTTP pipeline.")); + } + 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/test/java/com/azure/identity/WorkloadIdentityCredentialTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialTest.java index 1e5470ab0e402..8c6fbc1419423 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,10 @@ import com.azure.core.credential.AccessToken; import com.azure.core.credential.TokenRequestContext; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpPipeline; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.ProxyOptions; import com.azure.core.test.utils.TestConfigurationSource; import com.azure.core.util.Configuration; import com.azure.identity.implementation.IdentityClient; @@ -19,6 +23,7 @@ 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; @@ -30,6 +35,7 @@ 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 +551,69 @@ 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 testProxyRejectsCustomPipelineInsteadOfBypassingProxy() { + HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(mock(HttpClient.class)).build(); + 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"))) + .pipeline(pipeline) + .enableAzureProxy(); + + Assertions.assertThrows(IllegalStateException.class, builder::build); + Assertions.assertDoesNotThrow( + () -> builder.configuration(TestUtils.createTestConfiguration(new TestConfigurationSource())).build()); + } + + @Test + public void testProxyRejectsLegacyProxyOptionsInsteadOfBypassingProxy() { + 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(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))) + .enableAzureProxy(); + + Assertions.assertThrows(IllegalStateException.class, builder::build); + } + + @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)); + } +} From c263ae947e466015342e56e157569b97de08cf96 Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Tue, 20 Oct 2026 16:11:32 -0700 Subject: [PATCH 02/14] Harden AKS identity binding proxy transport --- .../CustomTokenProxyHttpClient.java | 300 +++++------- .../CustomTokenProxyHttpResponse.java | 43 +- ...IdentityCredentialIdentityBindingTest.java | 444 +++++++++++++++++- .../CustomTokenProxyHttpClientTest.java | 52 ++ .../CustomTokenProxyHttpResponseTest.java | 88 ++++ 5 files changed, 715 insertions(+), 212 deletions(-) create mode 100644 sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClientTest.java create mode 100644 sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponseTest.java 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..74dbcd813bd22 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 @@ -9,18 +9,16 @@ import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; -import java.net.URI; 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.CertificateParsingException; import java.security.cert.X509Certificate; -import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; @@ -42,25 +40,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 +63,195 @@ 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; - } - } + cachedSSLContext = caData == null || caData.length == 0 + ? SSLContext.getDefault() + : createSslContextFromBytes(caData); } 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++; - } - 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)); + 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); } + TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(keystore); + + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, tmf.getTrustManagers(), 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(); @@ -312,13 +271,4 @@ private static boolean certificateContainsDnsName(X509Certificate cert, String d return false; } - private static byte[] generateSHA256Hash(byte[] data) { - 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)); - } - } } 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..0de3f4d6920a3 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,6 +3,7 @@ package com.azure.identity.implementation.customtokenproxy; +import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -20,12 +21,12 @@ 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 +78,24 @@ 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; - } + private synchronized byte[] readResponseBody() throws IOException { + if (cachedResponseBodyBytes != null) { + return cachedResponseBodyBytes; + } - 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; + 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 +119,11 @@ public void close() { } private InputStream getResponseStream() throws IOException { - try { + if (statusCode < 400) { 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/test/java/com/azure/identity/WorkloadIdentityCredentialIdentityBindingTest.java b/sdk/identity/azure-identity/src/test/java/com/azure/identity/WorkloadIdentityCredentialIdentityBindingTest.java index ba206acdf5d30..b97752ab4e62b 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; @@ -37,11 +49,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 +71,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. @@ -87,6 +118,16 @@ 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 final List tokenRequestUris = new CopyOnWriteArrayList<>(); @BeforeEach public void setUp() throws Exception { @@ -120,12 +161,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 +264,324 @@ 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()); + } + + @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()); + } + + @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()); + } + + @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"); + } + @Test public void testAksProxyWithInvalidTokenFile() { Path nonExistentTokenFile = tempDir.resolve("non-existent-token.jwt"); @@ -541,11 +903,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()); + workerGroup = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory()); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) @@ -557,12 +920,6 @@ protected void initChannel(SocketChannel ch) { SslHandler sslHandler = sslContext.newHandler(ch.alloc()); - sslHandler.handshakeFuture().addListener(future -> { - if (future.isSuccess()) { - SSLEngine engine = sslHandler.engine(); - } - }); - pipeline.addLast(sslHandler); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); @@ -580,6 +937,17 @@ 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")) { @@ -590,16 +958,28 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) + " \"authorization_endpoint\": \"%s/oauth2/v2.0/authorize\"%n" + "}", base, base, base); } else { tokenRequestCount.incrementAndGet(); + tokenRequestUris.add(uri); 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 +998,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/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..55c4bcc448077 --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpClientTest.java @@ -0,0 +1,52 @@ +// 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 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.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; + +public class CustomTokenProxyHttpClientTest { + @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..586e067ec199f --- /dev/null +++ b/sdk/identity/azure-identity/src/test/java/com/azure/identity/implementation/customtokenproxy/CustomTokenProxyHttpResponseTest.java @@ -0,0 +1,88 @@ +// 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.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; + +import javax.net.ssl.HttpsURLConnection; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Collections; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class CustomTokenProxyHttpResponseTest { + @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(); + } + + @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(); + } + + @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(); + } + + 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; + } +} From 21b0b56f1ea1e05835f973da6c9bc61ee3de6d6c Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Tue, 20 Oct 2026 16:12:16 -0700 Subject: [PATCH 03/14] Document AKS identity binding usage --- sdk/identity/azure-identity/CHANGELOG.md | 5 ++ sdk/identity/azure-identity/README.md | 46 ++++++++++++++++++ .../azure-identity/TROUBLESHOOTING.md | 5 +- .../identity/WorkloadIdentityCredential.java | 19 ++++---- .../WorkloadIdentityCredentialBuilder.java | 48 +++++++++++++------ .../credential/JavaDocCodeSnippets.java | 11 +++++ 6 files changed, 108 insertions(+), 26 deletions(-) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 9b662e4e4fece..1b9afa66705eb 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -10,6 +10,10 @@ ### Bugs Fixed +- Fixed AKS identity binding proxy TLS server-name verification and rejection of partially malformed CA bundles. +- Fixed AKS identity binding CA file reloads to retain the previously loaded CA during missing or empty rotation windows. +- Fixed workload identity proxy requests and response reads blocking Reactor event-loop threads, and response read failures being returned as empty bodies. +- Fixed identity binding transport configuration leaking into subsequent credentials built with the same builder. Unsupported custom pipelines and legacy proxy options now fail explicitly instead of bypassing the proxy. - 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)) @@ -17,6 +21,7 @@ ### Other Changes +- Added AKS identity binding usage guidance and an opt-in example for `WorkloadIdentityCredentialBuilder.enableAzureProxy()`. - Improved `AzureDeveloperCliCredential` error handling to extract meaningful messages from `azd auth token` JSON output, providing cleaner error messages to users. #### Dependency Updates diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index 40a5114a066a7..230708e73bb7d 100644 --- a/sdk/identity/azure-identity/README.md +++ b/sdk/identity/azure-identity/README.md @@ -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, +the credential uses a dedicated HTTP transport. A custom HTTP pipeline or legacy `proxyOptions` isn't supported; +use `addPolicy()` to add pipeline policies. + +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 f58d827abe549..104e2489a18d3 100644 --- a/sdk/identity/azure-identity/TROUBLESHOOTING.md +++ b/sdk/identity/azure-identity/TROUBLESHOOTING.md @@ -271,7 +271,10 @@ 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.| +|`IllegalStateException` when combining identity bindings with a custom pipeline or legacy proxy options.|Those options would bypass the identity binding transport.|Remove the custom pipeline or legacy `proxyOptions`; use `addPolicy()` for request policies.| ## Troubleshoot `IntelliJCredential` authentication issues 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 c294efe99a004..a1a1561d8676c 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 @@ -17,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

* @@ -72,10 +65,35 @@ 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 replaces any client set with {@link #httpClient(com.azure.core.http.HttpClient)}. A custom HTTP pipeline + * or legacy {@code proxyOptions} cannot be combined with this feature. Use {@link #addPolicy} for pipeline policies. + * 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. */ 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} */ From 0c251f935836500830147f37e7d9128fe9dccf83 Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Thu, 22 Oct 2026 02:28:54 -0700 Subject: [PATCH 04/14] Added small clarifying comments --- .../customtokenproxy/CustomTokenProxyHttpResponse.java | 1 + 1 file changed, 1 insertion(+) 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 0de3f4d6920a3..b29ee01d02879 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 @@ -120,6 +120,7 @@ public void close() { private InputStream getResponseStream() throws IOException { if (statusCode < 400) { + // JDK getInputStream() throws for HTTP errors, so we only check for non-error status codes return connection.getInputStream(); } InputStream errorStream = connection.getErrorStream(); From ce2c433982ab34eb3aaa826b70e488092836def1 Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Thu, 22 Oct 2026 03:30:32 -0700 Subject: [PATCH 05/14] Fix AKS proxy instance discovery mocks --- ...IdentityCredentialIdentityBindingTest.java | 36 +++++++++++++++++-- 1 file changed, 33 insertions(+), 3 deletions(-) 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 b97752ab4e62b..f0e4994137912 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 @@ -280,7 +280,7 @@ public void testAksProxyRoutesPublicAuthorityRequests() throws Exception { 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()); + assertEquals(1, tokenRequestCount.get(), tokenRequestUris::toString); } @Test @@ -330,7 +330,7 @@ public void testAksProxyReadsRotatedServiceAccountToken() throws Exception { credential.getTokenSync(new TokenRequestContext().addScopes("https://vault.azure.net/.default")); assertEquals(rotatedAssertion, parseForm(lastRequestBody).get("client_assertion")); - assertEquals(2, tokenRequestCount.get()); + assertEquals(2, tokenRequestCount.get(), tokenRequestUris::toString); } @Test @@ -436,6 +436,27 @@ public void testAksProxyRoutesMetadataGetRequests() throws Exception { 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 { @@ -950,7 +971,16 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) } 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 From e632a3fa66f729ea5c1a243e8f7e3de2c6546d91 Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Thu, 22 Oct 2026 03:31:27 -0700 Subject: [PATCH 06/14] Preserve AKS proxy configuration precedence --- sdk/identity/azure-identity/CHANGELOG.md | 2 +- sdk/identity/azure-identity/README.md | 4 +- .../azure-identity/TROUBLESHOOTING.md | 1 - .../WorkloadIdentityCredentialBuilder.java | 11 ++--- .../WorkloadIdentityCredentialTest.java | 43 ++++++++++++++----- 5 files changed, 39 insertions(+), 22 deletions(-) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 1b9afa66705eb..11fc600438e63 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -13,7 +13,7 @@ - Fixed AKS identity binding proxy TLS server-name verification and rejection of partially malformed CA bundles. - Fixed AKS identity binding CA file reloads to retain the previously loaded CA during missing or empty rotation windows. - Fixed workload identity proxy requests and response reads blocking Reactor event-loop threads, and response read failures being returned as empty bodies. -- Fixed identity binding transport configuration leaking into subsequent credentials built with the same builder. Unsupported custom pipelines and legacy proxy options now fail explicitly instead of bypassing the proxy. +- Fixed identity binding transport configuration leaking into subsequent credentials built with the same builder. - 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)) diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index 230708e73bb7d..0ae1c45d5aaff 100644 --- a/sdk/identity/azure-identity/README.md +++ b/sdk/identity/azure-identity/README.md @@ -186,8 +186,8 @@ 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, -the credential uses a dedicated HTTP transport. A custom HTTP pipeline or legacy `proxyOptions` isn't supported; -use `addPolicy()` to add pipeline policies. +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. diff --git a/sdk/identity/azure-identity/TROUBLESHOOTING.md b/sdk/identity/azure-identity/TROUBLESHOOTING.md index 104e2489a18d3..c005f832f22e9 100644 --- a/sdk/identity/azure-identity/TROUBLESHOOTING.md +++ b/sdk/identity/azure-identity/TROUBLESHOOTING.md @@ -274,7 +274,6 @@ Get-AzAccessToken -ResourceUrl "https://management.core.windows.net" |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.| -|`IllegalStateException` when combining identity bindings with a custom pipeline or legacy proxy options.|Those options would bypass the identity binding transport.|Remove the custom pipeline or legacy `proxyOptions`; use `addPolicy()` for request policies.| ## Troubleshoot `IntelliJCredential` authentication issues 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 a1a1561d8676c..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 @@ -81,8 +81,9 @@ public WorkloadIdentityCredentialBuilder tokenFilePath(String tokenFilePath) { * *

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 replaces any client set with {@link #httpClient(com.azure.core.http.HttpClient)}. A custom HTTP pipeline - * or legacy {@code proxyOptions} cannot be combined with this feature. Use {@link #addPolicy} for pipeline policies. + * 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

@@ -107,7 +108,6 @@ public WorkloadIdentityCredentialBuilder enableAzureProxy() { * * @return a {@link WorkloadIdentityCredential} with the current configurations. * @throws IllegalArgumentException if required workload identity settings are missing or proxy configuration is invalid. - * @throws IllegalStateException if identity bindings are combined with a custom pipeline or legacy proxy options. */ public WorkloadIdentityCredential build() { Configuration configuration = identityClientOptions.getConfiguration() == null @@ -130,11 +130,6 @@ public WorkloadIdentityCredential build() { if (enableAzureProxy) { ProxyConfig proxyConfig = CustomTokenProxyConfiguration.parseAndValidate(configuration); if (proxyConfig != null) { - if (options.getHttpPipeline() != null || options.getProxyOptions() != null) { - throw LOGGER.logExceptionAsError(new IllegalStateException( - "AKS identity bindings cannot be combined with a custom HTTP pipeline or legacy proxyOptions. " - + "Use addPolicy to configure policies on the credential's HTTP pipeline.")); - } options.setHttpClient(new CustomTokenProxyHttpClient(proxyConfig)); } } 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 8c6fbc1419423..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 @@ -6,9 +6,11 @@ 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; @@ -30,6 +32,7 @@ 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; @@ -571,32 +574,52 @@ public void testProxyDoesNotMutateBuilderHttpClient() { } @Test - public void testProxyRejectsCustomPipelineInsteadOfBypassingProxy() { - HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(mock(HttpClient.class)).build(); + 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("token.jwt") + .tokenFilePath(tokenFile.toString()) .configuration(TestUtils - .createTestConfiguration(new TestConfigurationSource().put(ENV_PROXY_URL, "https://proxy.example.com"))) + .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(); - Assertions.assertThrows(IllegalStateException.class, builder::build); - Assertions.assertDoesNotThrow( - () -> builder.configuration(TestUtils.createTestConfiguration(new TestConfigurationSource())).build()); + 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 testProxyRejectsLegacyProxyOptionsInsteadOfBypassingProxy() { + 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(new ProxyOptions(ProxyOptions.Type.HTTP, new InetSocketAddress("localhost", 8888))) + .proxyOptions(proxyOptions) .enableAzureProxy(); - Assertions.assertThrows(IllegalStateException.class, builder::build); + assertNotNull(Assertions.assertDoesNotThrow(builder::build)); + Assertions.assertSame(proxyOptions, builder.identityClientOptions.getProxyOptions()); } @Test From 3d68bc276adb6cb20d15484fe0267e843fd08107 Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Thu, 22 Oct 2026 03:31:47 -0700 Subject: [PATCH 07/14] Clarify AKS identity binding changelog --- sdk/identity/azure-identity/CHANGELOG.md | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 11fc600438e63..d358bdb1a190e 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -2,6 +2,8 @@ ## 1.19.0-beta.3 (Unreleased) +The AKS identity binding updates below affect only the opt-in proxy implementation in 1.19.0 beta releases, not the 1.18.x stable implementation or ordinary workload identity authentication. + ### Features Added - Added support for user-assigned managed identities on Azure Arc in `ManagedIdentityCredential` and `DefaultAzureCredential`. @@ -10,10 +12,13 @@ ### Bugs Fixed -- Fixed AKS identity binding proxy TLS server-name verification and rejection of partially malformed CA bundles. -- Fixed AKS identity binding CA file reloads to retain the previously loaded CA during missing or empty rotation windows. -- Fixed workload identity proxy requests and response reads blocking Reactor event-loop threads, and response read failures being returned as empty bodies. -- Fixed identity binding transport configuration leaking into subsequent credentials built with the same builder. +- 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 before sending the service-account assertion. +- Fixed the AKS token proxy accepting CA bundles containing a valid certificate followed by a malformed certificate entry. +- Fixed authentication failures when a previously loaded proxy CA file temporarily disappears during rotation. The existing fallback for an empty CA file is unchanged. +- Fixed a race between proxy CA reloads and socket factory creation that could leave requests using the previous CA configuration. +- 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; the MSAL bridge's synchronous send path is unchanged. +- 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. +- 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. - 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)) From f8dca06fa9f670d6421cfd78dd19b415c653efec Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Thu, 22 Oct 2026 04:00:05 -0700 Subject: [PATCH 08/14] Update changelog and versions --- eng/versioning/version_client.txt | 2 +- .../azure-identity-broker-samples/pom.xml | 2 +- sdk/identity/azure-identity-broker/pom.xml | 2 +- sdk/identity/azure-identity-perf/pom.xml | 2 +- sdk/identity/azure-identity/CHANGELOG.md | 37 ++++++++----------- sdk/identity/azure-identity/README.md | 2 +- sdk/identity/azure-identity/pom.xml | 2 +- .../identity-test-container/pom.xml | 2 +- .../identity-test-function/pom.xml | 2 +- .../live-test-apps/identity-test-vm/pom.xml | 2 +- .../identity-test-webapp/pom.xml | 2 +- 11 files changed, 26 insertions(+), 31 deletions(-) diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index 1ad97b6ca4864..6c2aaad2baec1 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 d6ccb760b9afa..cfd580dd5a3d5 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 d358bdb1a190e..0645fbf454cd4 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -1,37 +1,32 @@ # Release History -## 1.19.0-beta.3 (Unreleased) - -The AKS identity binding updates below affect only the opt-in proxy implementation in 1.19.0 beta releases, not the 1.18.x stable implementation or ordinary workload identity authentication. +## 1.19.0 (2026-10-22) ### 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 -- 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 before sending the service-account assertion. -- Fixed the AKS token proxy accepting CA bundles containing a valid certificate followed by a malformed certificate entry. -- Fixed authentication failures when a previously loaded proxy CA file temporarily disappears during rotation. The existing fallback for an empty CA file is unchanged. -- Fixed a race between proxy CA reloads and socket factory creation that could leave requests using the previous CA configuration. -- 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; the MSAL bridge's synchronous send path is unchanged. -- 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. -- 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. -- 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 +--- -- Added AKS identity binding usage guidance and an opt-in example for `WorkloadIdentityCredentialBuilder.enableAzureProxy()`. -- Improved `AzureDeveloperCliCredential` error handling to extract meaningful messages from `azd auth token` JSON output, providing cleaner error messages to users. +The updates below only denote differences between this release and previous 1.19.0 beta releases, not the 1.18.x stable implementation. -#### Dependency Updates +### Bugs Fixed -- Upgraded `msal4j` from `1.23.1` to `1.26.0`. +- 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 before sending the service-account assertion. ([#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; the MSAL bridge's synchronous send path is unchanged. ([#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 0ae1c45d5aaff..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}) diff --git a/sdk/identity/azure-identity/pom.xml b/sdk/identity/azure-identity/pom.xml index 4b7c7e2a5b716..86447041df297 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/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 From 3aeda84db3de8e52d3d3708e9ec5d0c5af6c5d8d Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Thu, 22 Oct 2026 21:36:13 -0700 Subject: [PATCH 09/14] Fix AKS proxy wildcard certificate matching --- sdk/identity/azure-identity/CHANGELOG.md | 2 +- .../CustomTokenProxyHttpClient.java | 26 ++++++++++- ...IdentityCredentialIdentityBindingTest.java | 34 ++++++++++++++ .../CustomTokenProxyHttpClientTest.java | 43 ++++++++++++++++++ .../test/resources/test-aks-cert-wildcard.p12 | Bin 0 -> 2469 bytes 5 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 sdk/identity/azure-identity/src/test/resources/test-aks-cert-wildcard.p12 diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 0645fbf454cd4..f066abd6b8de7 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -16,7 +16,7 @@ The updates below only denote differences between this release and previous 1.19 ### 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 before sending the service-account assertion. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- 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 before sending the service-account assertion, while accepting certificate DNS wildcards that match exactly one label. ([#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)) 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 74dbcd813bd22..09704afee133f 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,6 +8,7 @@ import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; +import java.net.IDN; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; @@ -259,7 +260,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; } } @@ -271,4 +272,27 @@ private static boolean certificateContainsDnsName(X509Certificate cert, String d return false; } + 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 { + 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; + } + } + } 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 f0e4994137912..6735ea9a67f42 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 @@ -603,6 +603,40 @@ public void testAksProxyRejectsWrongSniEvenWhenCertificateMatchesProxyUrl() thro assertEquals(0, tokenRequestCount.get(), "The assertion must not be sent to a host with the wrong TLS name"); } + @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"); 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 index 55c4bcc448077..843a0920ca18f 100644 --- 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 @@ -9,6 +9,8 @@ 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; @@ -16,13 +18,54 @@ 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"); 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 0000000000000000000000000000000000000000..f84f73dc44d145246ed5bf3b46613f5521925bf4 GIT binary patch literal 2469 zcmY+EX*?8)8pdbW*kg*Zg;X?_8QYLynrxAxOgIW7`xa3YM$V8uAw!fs`*I{pc7u*( zN|p@Cma=3W`;y_f_jm8P_k4Jl-}Aih^YM?Sz_UO=Fq#6lgu%~;T@Ksk0wb ze#XzQ3rV4vGWog4P)ZKJs7bJ`M=Jhs(XW~(cbAkD6$StN^6hoU9M_iTTTL8W^zXk* zBo8P#vm-kshA!>T9{w~G5C+WV47b+&_+jN2Nv|wQlO3l&0HsKvS_+#M))xaC7Q_C8T>M49a#b4IMN-p~=qk9U7rBigR6dyo)?5Q!oc<^tvomeb)PPu5*)N zTo!kUZCeaH?CuK;Iiskvk!DwYt9q1?Ue8E~QQ|vpkGsYrtci0vH+|8^qBWXH5ze86 zOPlbVI$Lm+%3WHdfTZRGmCir2n{$oBa_$<+{_5(A68_Tn*<>9G7+n{H-buKrre$1^ zcvS+<@;O~3&)dc8BXQWT+ofq(_(xM6VJ|`RQ=wtAe)X=kmowA0YfH6IQn8;1$WB{} zU)MQZ>@sujhcDEL>2Bb`V4`%*hq0y2xG57B>%yEv1<#KB%$=L&q|quzy-=ol5!T!I zqw5vZ+uUTU^5b6-q65{^f>}1UDWuCFQh~ue@1Z^a<%0c{<9(b&o9+7)|nr+K5EOpDM8S5@&-(>T5DyLRcJ27X3~Q;n2w`1X#Z zqG6ubVClXFQ3IUNr}wY9BD$99QfylWlU5{?jq`EE0FRPA7~As>#7d!*{H@{HWequ&cVJ|Am4zSR7!5B_djssx6%*4 zT377n8gC|CEL~&JG!g^hXLB0NekVR|tlFSO>b15%Q!Oy)^OMU6oWxxz$T0}LCH+3H#muQJ!(&b$w?mG>_2-Ze^1B);sLH*XItpA@WjHz& zR`*YNZ^vgT1LJNaTE{ZQp3`0v01jtP!$O*oXM~Y55nfZxmZnvXO1j~zS~JW?0yukx z5w->b*E@Mh&7BBF8u^dSeSV&1t7%GsV=o>6OegE57Ief-F0yKbI8TgM&^-|W)~P|g#Hm+OuXq%+6&d4iY z6{C9NLGo?~L`|hL#@%d0P4-2#))ZAtmsYRT&e%jq=jTTKy7pQ%BRNg!pXWS2nlB#a zN8ISCClfHZvx{*{+KysE*~3$sqsm_TqN0u;V1AYl+;THSXIZ>I$Ynb5&MMuB$H>tJ zI<_mD#+C=zN)5(q{k)n92dZK40K0%0O0mt+{nOVN@86VFgXgH?U0zEahNN|H`r_;) z)O5{dr@g{Q!42-K(T}g+5L;vNN#2ND$JgH+6GRXzMn};cwvPR5E0606}rPsFJI*Mhyg}kOW&>a4rX__I~u?Y(tazQUn1yUQ5ND@=IG1Xym(fq zOSm6@vY&i>LK+NJ5(KKrCUm;*Pr+kShld{EF}a&G}& zg@2`|W3sMNsuk$cQ(63IskwOWa1CP36#^3f$>#O$tWNk?gvI1ou{~!8bnoJmCZNZ~ zHSVX~8(tfm54Qsv2S!mhnV79aJ;j;?y|PBaT!sjDpPP}efG;C>q%zFdjdkz7z<+kz$@mSDAI&$qHH`ZrwT)Dy%;v zZU0~|b-SlsY&m+4T>d3As3DAR2Ox6!vDx&9Wz`7RE0Tn}62&*`>(r(414Ebb@(GQF z_LX=6w+F3r>AGVj4d;Em8Yd59H$K4kTJ0nz;4qB^)=5}KV2@B>7vqI;ZtvO6h(PG? zSgpd7gZ$Ip3vY-By$f5)+z(J?7!j6AA!svy{vCKToNnQcmDBREe&Mz+)mhhjJ;3U> zBs&qvd+q(QfIa@#xw)$>XUFBYhLu-%GQSj5KV*<`2c}yQFH;82Fd7uB4+5jMk$ESU z#;!fgqC^db(!nyFm3J<=>-F6F=u&fiyM_KnJg;BsZp?Sy+_;D*mfAJd2UxFfUBu=2 z+TH#-Y5(Nx4@xQyG>+QtUr9c*7k~XZ6ItO&GBCz}w`z!9D=4(stjV-Tj1&aSd`j4t zL}y4M)Yd5!8#}3?)bJ*OCS3jr)!4T=UX#UZhv}1SLc7T)Jq>7(49j8R9Rbg1vWx%c z&(Tj>UeI_#QeHvJ1B(w*;C!fWhM+);h`0?%yWA%A8|V;uOhCS*gI@dN#)npql|XI5 ziAOTyT*p|eA&_pXp`QB#=fpG4C*Nu{dS{!u8uz0m@>#g!o0Zne<)>T3%x{qAW<$Ii zYMiSweVK2|NLAXsz8&`Rf|1aMrNDY!&RSVLKK)(>Gr-lzXo{0#{N^btq3q?o{xzb1 zA#Mg~aE{%dnbRN3f~zmvzqxiTRe|5eAIBDmL!3&Ifv7jf_={k_n3uwc`;b~Ica0O9 za6hybS^^D+K~dabkPs9AL6p5+SSD*UD(w>(e!nW>Vz@81@j(!wp~OGJdGW=^d86(! Q%;;2e_Ba3t3=GTs3lO%GJ^%m! literal 0 HcmV?d00001 From 0071fd7259aa318176e9f831a23b21666a791419 Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Thu, 22 Oct 2026 22:41:36 -0700 Subject: [PATCH 10/14] Restore released Core dependencies for Identity --- sdk/identity/azure-identity/pom.xml | 6 +++--- ...WorkloadIdentityCredentialIdentityBindingTest.java | 11 +++++------ 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/sdk/identity/azure-identity/pom.xml b/sdk/identity/azure-identity/pom.xml index 86447041df297..db35d4b9c6f40 100644 --- a/sdk/identity/azure-identity/pom.xml +++ b/sdk/identity/azure-identity/pom.xml @@ -36,13 +36,13 @@ com.azure azure-core - 1.61.0-beta.1 + 1.60.0 com.azure azure-core-http-netty - 1.17.0-beta.1 + 1.16.8 @@ -63,7 +63,7 @@ com.azure azure-core-test - 1.27.0-beta.20 + 1.27.0-beta.19 test 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 6735ea9a67f42..0bc1c2f4fbde5 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 @@ -27,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; @@ -108,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; @@ -962,8 +961,8 @@ private void startNettyHttpsServer(PrivateKey privateKey, X509Certificate certif SslContext sslContext = SslContextBuilder.forServer(privateKey, certificate).sslProvider(SslProvider.JDK).build(); - bossGroup = new MultiThreadIoEventLoopGroup(1, NioIoHandler.newFactory()); - workerGroup = new MultiThreadIoEventLoopGroup(2, NioIoHandler.newFactory()); + bossGroup = new NioEventLoopGroup(1); + workerGroup = new NioEventLoopGroup(2); ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) From 8d84beccee7067ad98102073fc829b338fa9affe Mon Sep 17 00:00:00 2001 From: Victor Colin Amador Date: Wed, 28 Oct 2026 14:07:06 -0700 Subject: [PATCH 11/14] Fix AKS proxy body reads and TLS retry validation --- sdk/identity/azure-identity/CHANGELOG.md | 4 +- .../CustomTokenProxyHttpClient.java | 116 +++++++++++++++++- .../CustomTokenProxyHttpResponse.java | 28 +++++ ...IdentityCredentialIdentityBindingTest.java | 42 ++++++- .../CustomTokenProxyHttpResponseTest.java | 67 ++++++++++ 5 files changed, 250 insertions(+), 7 deletions(-) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index f066abd6b8de7..8399e8f6e09d8 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -16,11 +16,11 @@ The updates below only denote differences between this release and previous 1.19 ### 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 before sending the service-account assertion, while accepting certificate DNS wildcards that match exactly one label. ([#50917](https://github.com/Azure/azure-sdk-for-java/pull/50917)) +- 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; the MSAL bridge's synchronous send path is unchanged. ([#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)) 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 09704afee133f..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 @@ -10,6 +10,7 @@ import java.net.HttpURLConnection; import java.net.IDN; import java.net.MalformedURLException; +import java.net.Socket; import java.net.URL; import java.nio.file.Files; import java.nio.file.NoSuchFileException; @@ -18,6 +19,7 @@ import java.security.GeneralSecurityException; import java.security.cert.Certificate; import java.security.cert.CertificateFactory; +import java.security.cert.CertificateException; import java.security.cert.CertificateParsingException; import java.security.cert.X509Certificate; import java.util.Arrays; @@ -27,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; @@ -165,9 +171,12 @@ private SSLContext getSSLContext() { try { if (CoreUtils.isNullOrEmpty(caFile)) { if (cachedSSLContext == null) { - cachedSSLContext = caData == null || caData.length == 0 - ? SSLContext.getDefault() - : createSslContextFromBytes(caData); + if (caData != null && caData.length > 0) { + cachedSSLContext = createSslContextFromBytes(caData); + } else { + cachedSSLContext + = CoreUtils.isNullOrEmpty(sniName) ? SSLContext.getDefault() : initializeSslContext(null); + } } return cachedSSLContext; } @@ -226,11 +235,26 @@ private SSLContext createSslContext(Collection certificat 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); + } + } + } SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, tmf.getTrustManagers(), null); + context.init(null, trustManagers, null); return context; } @@ -295,4 +319,88 @@ static boolean matchesDnsName(String dnsName, String certificateDnsName) { } } + 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 b29ee01d02879..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 @@ -7,17 +7,21 @@ 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; @@ -81,6 +85,30 @@ public Mono getBodyAsByteArray() { return Mono.fromCallable(this::readResponseBody).subscribeOn(Schedulers.boundedElastic()); } + @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)); + } + } + + @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; 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 0bc1c2f4fbde5..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 @@ -126,6 +126,9 @@ public class WorkloadIdentityCredentialIdentityBindingTest { 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 @@ -602,6 +605,36 @@ public void testAksProxyRejectsWrongSniEvenWhenCertificateMatchesProxyUrl() thro 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", @@ -972,7 +1005,10 @@ private void startNettyHttpsServer(PrivateKey privateKey, X509Certificate certif protected void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); - SslHandler sslHandler = sslContext.newHandler(ch.alloc()); + SslContext connectionContext = connectionCount.incrementAndGet() > 1 && retrySslContext != null + ? retrySslContext + : sslContext; + SslHandler sslHandler = connectionContext.newHandler(ch.alloc()); pipeline.addLast(sslHandler); pipeline.addLast(new HttpServerCodec()); @@ -1022,6 +1058,10 @@ protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest request) } 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); 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 index 586e067ec199f..7799e2b56e528 100644 --- 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 @@ -6,26 +6,87 @@ 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); @@ -55,6 +116,10 @@ public void ioFailureWithoutErrorBodyIsNotAnEmptySuccess() throws IOException { 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 @@ -66,6 +131,7 @@ public void errorResponseBodyIsPreserved() throws IOException { 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 @@ -77,6 +143,7 @@ public void errorStatusWithoutBodyIsPreserved(int status) throws IOException { assertEquals(status, response.getStatusCode()); StepVerifier.create(response.getBodyAsString()).expectNext("").verifyComplete(); + assertEquals("", response.getBodyAsBinaryData().toString()); } private HttpsURLConnection mockConnection(int status) throws IOException { From 8e4229fc34eb51a4d87c8a84f81781b071878bbc Mon Sep 17 00:00:00 2001 From: vcolin7 Date: Wed, 28 Oct 2026 18:05:59 -0700 Subject: [PATCH 12/14] Update CHANGELOG release date --- sdk/identity/azure-identity/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 8399e8f6e09d8..8b393060309ad 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.19.0 (2026-10-22) +## 1.19.0 (2026-10-28) ### Features Added From ff13c0683db871f7a9aebe105962144cd245b2e6 Mon Sep 17 00:00:00 2001 From: vcolin7 Date: Wed, 28 Oct 2026 21:50:05 -0700 Subject: [PATCH 13/14] Update CHANGELOG with bug fixes and dependency upgrades Upgraded dependencies for azure-core and azure-core-http-netty. --- sdk/identity/azure-identity/CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 8b393060309ad..4c76a4ccdf444 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -10,6 +10,11 @@ - 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 + +- 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`. + --- The updates below only denote differences between this release and previous 1.19.0 beta releases, not the 1.18.x stable implementation. From b4b03828b159032bd795a8f35506024c3bff0f0c Mon Sep 17 00:00:00 2001 From: vcolin7 Date: Wed, 28 Oct 2026 22:00:26 -0700 Subject: [PATCH 14/14] Update CHANGELOG for version 1.19.0 Updated release date for version 1.19.0 and added details about the new enableAzureProxy method. --- sdk/identity/azure-identity/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 4c76a4ccdf444..f55bbae34228b 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 1.19.0 (2026-10-28) +## 1.19.0 (2026-10-29) ### Features Added