From 58257706a570bf5c6f60eabcc8c43d18e7ffbc46 Mon Sep 17 00:00:00 2001 From: Rohit Singhal Date: Sat, 21 Nov 2026 02:13:45 +0000 Subject: [PATCH 1/2] Harden Key Vault pagination and authentication state Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../CHANGELOG.md | 3 + .../java/AdministrationCustomizations.java | 13 + .../KeyVaultCredentialPolicy.java | 175 ++++++-- .../KeyVaultEndpointValidation.java | 46 ++ .../implementation/RoleAssignmentsImpl.java | 10 +- .../implementation/RoleDefinitionsImpl.java | 8 +- .../KeyVaultCredentialPolicyTest.java | 297 +++++++++++++ .../KeyVaultPaginationTest.java | 156 +++++++ .../CHANGELOG.md | 3 + .../main/java/CertificatesCustomizations.java | 11 + .../implementation/CertificateClientImpl.java | 41 +- .../KeyVaultCredentialPolicy.java | 175 ++++++-- .../KeyVaultEndpointValidation.java | 46 ++ .../KeyVaultCredentialPolicyTest.java | 298 +++++++++++++ .../certificates/KeyVaultPaginationTest.java | 157 +++++++ .../azure-security-keyvault-keys/CHANGELOG.md | 3 + .../src/main/java/KeysCustomizations.java | 11 + .../keys/implementation/KeyClientImpl.java | 30 +- .../KeyVaultCredentialPolicy.java | 175 ++++++-- .../KeyVaultEndpointValidation.java | 46 ++ .../keys/KeyVaultCredentialPolicyTest.java | 297 +++++++++++++ .../keyvault/keys/KeyVaultPaginationTest.java | 153 +++++++ .../CHANGELOG.md | 3 + .../src/main/java/SecretsCustomizations.java | 11 + .../KeyVaultCredentialPolicy.java | 175 ++++++-- .../KeyVaultEndpointValidation.java | 46 ++ .../implementation/SecretClientImpl.java | 30 +- .../secrets/KeyVaultCredentialPolicyTest.java | 416 ++++++++++++++++++ .../secrets/KeyVaultPaginationTest.java | 186 ++++++++ 29 files changed, 2784 insertions(+), 237 deletions(-) create mode 100644 sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultEndpointValidation.java create mode 100644 sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java create mode 100644 sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultEndpointValidation.java create mode 100644 sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java create mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultEndpointValidation.java create mode 100644 sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java create mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidation.java create mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java diff --git a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md index 0a1fa103aaffb..75d3abcb61386 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md @@ -8,6 +8,9 @@ ### Bugs Fixed +- Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. +- Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. + ### Other Changes ## 4.10.0 (2026-11-13) diff --git a/sdk/keyvault/azure-security-keyvault-administration/customizations/src/main/java/AdministrationCustomizations.java b/sdk/keyvault/azure-security-keyvault-administration/customizations/src/main/java/AdministrationCustomizations.java index 957c90c2a3e87..d95164cb5b2a1 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/customizations/src/main/java/AdministrationCustomizations.java +++ b/sdk/keyvault/azure-security-keyvault-administration/customizations/src/main/java/AdministrationCustomizations.java @@ -11,6 +11,7 @@ import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.EnumDeclaration; import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.javadoc.Javadoc; import org.slf4j.Logger; @@ -31,6 +32,7 @@ public void customize(LibraryCustomization libraryCustomization, Logger logger) customizeKeyVaultRoleScope(libraryCustomization); customizeServiceVersion(libraryCustomization); customizeImplClients(libraryCustomization); + customizePaging(libraryCustomization); customizeModuleInfo(libraryCustomization.getRawEditor()); customizePackageInfos(libraryCustomization.getRawEditor()); } @@ -77,6 +79,17 @@ private static void makeAllMethodsPublic(ClassOrInterfaceDeclaration clazz, Stri } } + private static void customizePaging(LibraryCustomization customization) { + for (String className : Arrays.asList("RoleAssignmentsImpl", "RoleDefinitionsImpl")) { + customization.getClass("com.azure.security.keyvault.administration.implementation", className) + .customizeAst(ast -> ast.findAll(MethodCallExpr.class).stream() + .filter(call -> call.getScope().map(Object::toString).orElse("").equals("service") + && !call.getArguments().isEmpty() && call.getArgument(0).toString().equals("nextLink")) + .forEach(call -> call.setArgument(0, StaticJavaParser.parseExpression( + "KeyVaultEndpointValidation.validateNextLink(nextLink, this.client.getVaultBaseUrl())")))); + } + } + private static void customizeKeyVaultRoleScope(LibraryCustomization customization) { customization.getClass("com.azure.security.keyvault.administration.models", "KeyVaultRoleScope") .customizeAst(ast -> diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java index f95ea3c6398e4..59ac079af3544 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.security.keyvault.administration.implementation; +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.AccessTokenCache; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; import com.azure.core.http.HttpPipelineCallContext; @@ -20,15 +22,18 @@ import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static com.azure.core.http.HttpHeaderName.AUTHORIZATION; import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH; import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE; @@ -42,9 +47,12 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class); private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; + private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); - private ChallengeParameters challenge; + private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; + private final TokenCredential credential; + private final ConcurrentMap accessTokenCaches = new ConcurrentHashMap<>(); /** * Creates a {@link KeyVaultCredentialPolicy}. @@ -55,6 +63,7 @@ public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChall super(credential); this.disableChallengeResourceVerification = disableChallengeResourceVerification; + this.credential = credential; } /** @@ -82,17 +91,13 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext - = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) + .setCaeEnabled(true); return setAuthorizationHeader(context, tokenRequestContext); } @@ -130,7 +135,7 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -141,10 +146,11 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return Mono.just(false); } } else { @@ -173,13 +179,14 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -205,15 +212,12 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context public void authorizeRequestSync(HttpPipelineCallContext context) { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); setAuthorizationHeaderSync(context, tokenRequestContext); @@ -248,7 +252,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -258,10 +262,11 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return false; } } else { @@ -291,13 +296,14 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -319,6 +325,28 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, return true; } + @Override + public Mono setAuthorizationHeader(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + return Mono.defer(() -> { + String authority = getRequestAuthority(context); + return getAccessTokenCache(authority, tokenRequestContext).getToken(tokenRequestContext, true) + .flatMap(token -> { + // The request is mutable while asynchronous credential acquisition is in progress. + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + return Mono.empty(); + }); + }); + } + + @Override + public void setAuthorizationHeaderSync(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + String authority = getRequestAuthority(context); + AccessToken token = getAccessTokenCache(authority, tokenRequestContext).getTokenSync(tokenRequestContext, true); + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + } + @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { @@ -426,12 +454,48 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { + if (context == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); + } + // Keep one current context per origin. A failed refresh must never expose a token from an older context. + return accessTokenCaches.compute(authority, + (ignored, existing) -> existing != null && existing.matches(context) + ? existing + : new TokenCache(credential, context)).cache; + } + + private static final class TokenCache { + private final AccessTokenCache cache; + private final List scopes; + private final String tenantId; + private final String claims; + private final boolean caeEnabled; + + private TokenCache(TokenCredential credential, TokenRequestContext context) { + cache = new AccessTokenCache(credential); + scopes = new ArrayList<>(context.getScopes()); + tenantId = context.getTenantId(); + claims = context.getClaims(); + caeEnabled = context.isCaeEnabled(); + } + + private boolean matches(TokenRequestContext context) { + return scopes.equals(context.getScopes()) + && Objects.equals(tenantId, context.getTenantId()) + && Objects.equals(claims, context.getClaims()) + && caeEnabled == context.isCaeEnabled(); + } + } + private static class ChallengeParameters { + private final String authority; private final URI authorizationUri; private final String tenantId; private final String[] scopes; - ChallengeParameters(URI authorizationUri, String[] scopes) { + ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; this.scopes = scopes; @@ -464,26 +528,41 @@ public static void clearCache() { CHALLENGE_CACHE.clear(); } - /** - * Gets the host name and port of the Key Vault or Managed HSM endpoint. - * - * @param request The {@link HttpRequest} to extract the host name and port from. - * - * @return The host name and port of the Key Vault or Managed HSM endpoint. - */ - private static String getRequestAuthority(HttpRequest request) { - URL url = request.getUrl(); - String authority = url.getAuthority(); - int port = url.getPort(); - - // Append port for complete authority. - if (!authority.contains(":") && port > 0) { - authority = authority + ":" + port; + private ChallengeParameters getChallenge(HttpPipelineCallContext context) { + String authority = getRequestAuthority(context); + // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. + ChallengeParameters cachedChallenge = this.challenge; + if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { + cachedChallenge = CHALLENGE_CACHE.get(authority); + this.challenge = cachedChallenge; } + return cachedChallenge; + } + private static String getRequestAuthority(HttpPipelineCallContext context) { + String authority = (String) context.getData(KEY_VAULT_REQUEST_ORIGIN_KEY).orElse(null); + if (authority == null) { + authority = KeyVaultEndpointValidation.getOrigin(context.getHttpRequest().getUrl().toString()); + context.setData(KEY_VAULT_REQUEST_ORIGIN_KEY, authority); + } + validateRequestAuthority(context, authority); return authority; } + private static void validateRequestAuthority(HttpPipelineCallContext context, String authority) { + HttpRequest request = context.getHttpRequest(); + try { + if (!authority.equals(KeyVaultEndpointValidation.getOrigin(request.getUrl().toString()))) { + throw new IllegalArgumentException( + "The request URL must have the same origin as the original request."); + } + } catch (RuntimeException e) { + // A previous attempt may already have authorized this request before its destination changed. + request.getHeaders().remove(AUTHORIZATION); + throw LOGGER.logExceptionAsError(e); + } + } + private static boolean isChallengeResourceValid(HttpRequest request, String scope) { final URI scopeUri; diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultEndpointValidation.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultEndpointValidation.java new file mode 100644 index 0000000000000..148ce44e42241 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultEndpointValidation.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration.implementation; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; + +/** + * Validates Key Vault continuation destinations independently of the HTTP pipeline. + */ +final class KeyVaultEndpointValidation { + private KeyVaultEndpointValidation() { + } + + static String validateNextLink(String nextLink, String endpoint) { + if (!getOrigin(endpoint).equals(getOrigin(nextLink))) { + throw new IllegalArgumentException( + "The continuation URL must have the same origin as the configured endpoint."); + } + return nextLink; + } + + static String getOrigin(String url) { + final URI uri; + try { + uri = new URI(url).parseServerAuthority(); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid Key Vault URL.", e); + } + + String scheme = uri.getScheme(); + if ((!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawFragment() != null + || uri.getPort() < -1 + || uri.getPort() > 65535) { + throw new IllegalArgumentException("Invalid Key Vault URL."); + } + + int port = uri.getPort() == -1 ? ("https".equalsIgnoreCase(scheme) ? 443 : 80) : uri.getPort(); + return scheme.toLowerCase(Locale.ROOT) + "://" + uri.getHost().toLowerCase(Locale.ROOT) + ":" + port; + } +} diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java index b36c91d4e019e..b4c3a2d453464 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleAssignmentsImpl.java @@ -649,8 +649,9 @@ public Mono> listForScopeNextSinglePageAsync(String ne RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.listForScopeNext(nextLink, this.client.getVaultBaseUrl(), accept, - requestOptions, context)) + .withContext(context -> service.listForScopeNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.client.getVaultBaseUrl()), + this.client.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -685,8 +686,9 @@ public Mono> listForScopeNextSinglePageAsync(String ne @ServiceMethod(returns = ReturnType.SINGLE) private PagedResponse listForScopeNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.listForScopeNextSync(nextLink, this.client.getVaultBaseUrl(), accept, - requestOptions, Context.NONE); + Response res = service.listForScopeNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.client.getVaultBaseUrl()), + this.client.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java index bd4f5fbc503a6..b5bf1021447ce 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/RoleDefinitionsImpl.java @@ -896,8 +896,9 @@ public PagedIterable list(String scope, RequestOptions requestOption public Mono> listNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext( - context -> service.listNext(nextLink, this.client.getVaultBaseUrl(), accept, requestOptions, context)) + .withContext(context -> service.listNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.client.getVaultBaseUrl()), + this.client.getVaultBaseUrl(), accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -952,7 +953,8 @@ public Mono> listNextSinglePageAsync(String nextLink, private PagedResponse listNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; Response res - = service.listNextSync(nextLink, this.client.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + = service.listNextSync(KeyVaultEndpointValidation.validateNextLink(nextLink, this.client.getVaultBaseUrl()), + this.client.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java index 3b4a377a06132..9babdbda02c3c 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java @@ -14,6 +14,8 @@ import com.azure.core.http.HttpPipelineCallContext; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.FixedDelay; +import com.azure.core.http.policy.RetryPolicy; import com.azure.core.test.SyncAsyncExtension; import com.azure.core.test.annotation.SyncAsyncTest; import com.azure.core.test.http.MockHttpResponse; @@ -28,15 +30,18 @@ import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; import reactor.test.StepVerifier; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -147,6 +152,229 @@ public void cleanup() { KeyVaultCredentialPolicy.clearCache(); } + @SyncAsyncTest + public void failedAcquisitionCannotReuseAnotherOriginsToken() { + for (boolean sameTenant : new boolean[] { false, true }) { + for (boolean sameScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean failAcquisition = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger foreignAuthorizedSends = new AtomicInteger(); + String secondTenant = sameTenant ? "first" : "second"; + String secondScope = sameScope ? "https://vault.azure.net/.default" : "https://azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (failAcquisition.get()) { + assertEquals(secondTenant, context.getTenantId()); + assertEquals(Arrays.asList(secondScope), context.getScopes()); + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + boolean second = request.getUrl().getHost().equals("second.vault.azure.net"); + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono.just(tokenCacheChallenge(request, second ? secondTenant : "first", + second ? secondScope : "https://vault.azure.net/.default", null)); + } + if (second) { + foreignAuthorizedSends.incrementAndGet(); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertEquals(1, tokenRequests.get()); + failAcquisition.set(true); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://second.vault.azure.net")); + assertEquals(0, foreignAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + + failAcquisition.set(false); + sendTokenCacheRequest(pipeline, "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets"); + assertEquals(4, tokenRequests.get(), + "A failed acquisition for another origin must not evict this token."); + } + } + } + + @SyncAsyncTest + public void failedContextChangeCannotReusePreviousToken() { + for (String change : Arrays.asList("tenant", "scope", "claims")) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean changedChallenge = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger staleAuthorizedSends = new AtomicInteger(); + String tenant = "tenant".equals(change) ? "second" : "first"; + String scope = "scope".equals(change) ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + String claims = "claims".equals(change) ? DECODED_CLAIMS : null; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (changedChallenge.get()) { + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (changedChallenge.get() && authorization != null) { + staleAuthorizedSends.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 200)); + } + if ("/changed".equals(request.getUrl().getPath())) { + changedChallenge.set(true); + return Mono.just(tokenCacheChallenge(request, tenant, scope, claims)); + } + return Mono.just(authorization == null + ? tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null) + : new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed")); + assertEquals(0, staleAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + } + } + + @SyncAsyncTest + public void originScopedTokensSupportRetriesAndNormalization() { + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + } + if (secondTokenRequests.incrementAndGet() == 1) { + throw new IllegalStateException("Transient token acquisition failure."); + } + return new AccessToken("second-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String tenant + = request.getUrl().getHost().equalsIgnoreCase("first.vault.azure.net") ? "first" : "second"; + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, tenant, "https://vault.azure.net/.default", null)); + } + assertEquals("Bearer " + tenant + "-origin-token", authorization); + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + for (String url : Arrays.asList("https://first.vault.azure.net", "https://second.vault.azure.net", + "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets", "HTTPS://SECOND.VAULT.AZURE.NET:443/secrets")) { + assertEquals(200, sendTokenCacheRequest(pipeline, url).getStatusCode()); + } + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + } + + @Test + public void concurrentTokenAcquisitionsKeepIndependentCacheState() { + for (boolean sameOrigin : new boolean[] { false, true }) { + Sinks.One firstToken = Sinks.one(); + Sinks.One secondToken = Sinks.one(); + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return firstToken.asMono(); + } + if (secondTokenRequests.incrementAndGet() == 1) { + return Mono.error(new IllegalStateException("Transient token acquisition failure.")); + } + return secondToken.asMono(); + }, false); + HttpPipelineCallContext firstContext + = createCallContext(new HttpRequest(HttpMethod.GET, "https://first.vault.azure.net"), Context.NONE); + HttpPipelineCallContext secondContext = createCallContext(new HttpRequest(HttpMethod.GET, + sameOrigin ? "https://first.vault.azure.net" : "https://second.vault.azure.net"), Context.NONE); + TokenRequestContext firstRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("first") + .setCaeEnabled(true); + TokenRequestContext secondRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("second") + .setCaeEnabled(true); + + StepVerifier.create(Mono.when(policy.setAuthorizationHeader(firstContext, firstRequest), + policy.setAuthorizationHeader(secondContext, secondRequest).retry(1))).then(() -> { + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + secondToken.tryEmitValue(new AccessToken("second-token", OffsetDateTime.now().plusHours(1))); + firstToken.tryEmitValue(new AccessToken("first-token", OffsetDateTime.now().plusHours(1))); + }).expectComplete().verify(Duration.ofSeconds(5)); + assertEquals("Bearer first-token", firstContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals("Bearer second-token", secondContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + StepVerifier.create(policy.setAuthorizationHeader(secondContext, secondRequest)).verifyComplete(); + assertEquals(2, secondTokenRequests.get()); + } + } + + private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String url) { + HttpRequest request = new HttpRequest(HttpMethod.GET, url); + return SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE)); + } + + private static HttpResponse tokenCacheChallenge(HttpRequest request, String tenant, String scope, String claims) { + String challenge = "Bearer authorization=\"https://login.example/" + tenant + "\", scope=\"" + scope + "\""; + if (claims != null) { + challenge += ", error=\"insufficient_claims\", claims=\"" + + Base64Util.encodeToString(claims.getBytes(StandardCharsets.UTF_8)) + "\""; + } + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, challenge)); + } + + @SyncAsyncTest + public void cachedChallengeIsBoundToRequestOrigin() { + AtomicInteger tokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false); + SyncAsyncExtension.execute( + () -> policy.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> policy.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + assertEquals(1, tokenRequests.get()); + + for (KeyVaultCredentialPolicy cachedPolicy : Arrays.asList(policy, new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false))) { + for (String endpoint : Arrays.asList("https://other.vault.azure.net", "https://kvtest.vault.azure.net:8443", + "http://kvtest.vault.azure.net")) { + HttpPipelineCallContext foreignContext + = createCallContext(new HttpRequest(HttpMethod.GET, endpoint), Context.NONE); + int previousTokenRequests = tokenRequests.get(); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(foreignContext), + () -> cachedPolicy.authorizeRequest(foreignContext)); + assertNull(foreignContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals(previousTokenRequests, tokenRequests.get()); + } + + HttpPipelineCallContext normalizedContext = createCallContext( + new HttpRequest(HttpMethod.GET, "HTTPS://KVTEST.VAULT.AZURE.NET:443/roleDefinitions"), Context.NONE); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(normalizedContext), + () -> cachedPolicy.authorizeRequest(normalizedContext)); + assertNotNull(normalizedContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + } + } + @SyncAsyncTest public void onNon401ErrorResponse() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); @@ -164,6 +392,75 @@ public void onNon401ErrorResponse() { KeyVaultCredentialPolicy.clearCache(); } + @SyncAsyncTest + public void requestOriginIsRevalidatedDuringTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean cachedChallenge : new boolean[] { false, true }) { + for (String destination : Arrays.asList("https://other.example/roles", + "https://other.vault.azure.net/roles", "https://kvtest.vault.azure.net:8443/roles", + "http://kvtest.vault.azure.net/roles", "https://user@kvtest.vault.azure.net/roles")) { + KeyVaultCredentialPolicy.clearCache(); + if (cachedChallenge) { + KeyVaultCredentialPolicy seed = new KeyVaultCredentialPolicy(credential, false); + SyncAsyncExtension.execute( + () -> seed.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> seed.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + } + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/roles"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + TokenCredential mutatingCredential = context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + request.setUrl(destination); + return new AccessToken("fake-token", OffsetDateTime.now().plusHours(1)); + }); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new KeyVaultCredentialPolicy(mutatingCredential, disableVerification)) + .httpClient(ignored -> { + sends.incrementAndGet(); + return Mono.just(request.getHeaders().getValue(AUTHORIZATION) == null + ? unauthorizedHttpResponseWithHeader + : simpleResponse); + }) + .build(); + + assertThrows(IllegalArgumentException.class, + () -> SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(cachedChallenge ? 0 : 1, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + } + } + + @SyncAsyncTest + public void requestOriginIsRevalidatedBeforeCaeTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/roles"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + HttpPipeline pipeline = new HttpPipelineBuilder().policies(new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, disableVerification)).httpClient(ignored -> { + if (sends.incrementAndGet() == 1) { + return Mono.just(unauthorizedHttpResponseWithHeader); + } + request.setUrl("https://other.vault.azure.net/roles"); + return Mono.just(unauthorizedHttpResponseWithHeaderAndClaims); + }).build(); + + assertThrows(IllegalArgumentException.class, () -> SyncAsyncExtension + .execute(() -> pipeline.sendSync(request, Context.NONE), () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(2, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + @SyncAsyncTest public void on401UnauthorizedResponseWithHeader() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java new file mode 100644 index 0000000000000..2359e41ed8761 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java @@ -0,0 +1,156 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.administration; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.test.SyncAsyncExtension; +import com.azure.core.test.annotation.SyncAsyncTest; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.security.keyvault.administration.implementation.KeyVaultCredentialPolicy; +import com.azure.security.keyvault.administration.models.KeyVaultRoleScope; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import reactor.core.publisher.Mono; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Execution(ExecutionMode.SAME_THREAD) +public class KeyVaultPaginationTest { + private static final String ENDPOINT = "https://paging.managedhsm.azure.net"; + private final AtomicInteger tokenRequests = new AtomicInteger(); + private final AtomicInteger sends = new AtomicInteger(); + private final AtomicInteger authorizedSends = new AtomicInteger(); + private final AtomicInteger customPolicyCalls = new AtomicInteger(); + private final AtomicReference responseNextLink = new AtomicReference<>(); + + @AfterEach + public void cleanup() { + KeyVaultCredentialPolicy.clearCache(); + } + + @SyncAsyncTest + public void allContinuationOperationsValidateBeforePipeline() { + for (boolean customPipeline : new boolean[] { false, true }) { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + KeyVaultAccessControlClientBuilder builder = builder(customPipeline, disableVerification); + KeyVaultAccessControlClient client = builder.buildClient(); + KeyVaultAccessControlAsyncClient asyncClient = builder.buildAsyncClient(); + List> syncPages = Arrays.asList(client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + client.listRoleAssignments(KeyVaultRoleScope.GLOBAL)); + List> asyncPages = Arrays.asList(asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + asyncClient.listRoleAssignments(KeyVaultRoleScope.GLOBAL)); + + for (int i = 0; i < syncPages.size(); i++) { + PagedIterable sync = syncPages.get(i); + PagedFlux async = asyncPages.get(i); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, null)); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, "HTTPS://PAGING.MANAGEDHSM.AZURE.NET:443/roles?skip=1")); + } + + assertRejectedContinuations(builder.buildClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + builder.buildAsyncClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL)); + } + } + assertTrue(tokenRequests.get() > 0); + assertTrue(authorizedSends.get() > 0); + } + + @SyncAsyncTest + public void serviceProvidedContinuationIsValidated() { + KeyVaultAccessControlClientBuilder builder = builder(false, false); + KeyVaultAccessControlClient client = builder.buildClient(); + KeyVaultAccessControlAsyncClient asyncClient = builder.buildAsyncClient(); + responseNextLink.set(ENDPOINT + "/roles?skip=1"); + assertEquals(2, readPages(client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), null)); + + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + responseNextLink.set("https://other.example/roles"); + assertThrows(IllegalArgumentException.class, + () -> readPages(client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), null)); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends + 1, sends.get()); + } + + private void assertRejectedContinuations(PagedIterable sync, PagedFlux async) { + for (String nextLink : Arrays.asList("https://other.example/roles", "https://other.managedhsm.azure.net/roles", + "http://paging.managedhsm.azure.net/roles", ENDPOINT + ":8443/roles", + "https://user@paging.managedhsm.azure.net/roles", ENDPOINT + ":invalid/roles", "/roles")) { + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + int previousAuthorizedSends = authorizedSends.get(); + int previousPolicyCalls = customPolicyCalls.get(); + assertThrows(IllegalArgumentException.class, () -> readPages(sync, async, nextLink), nextLink); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + assertEquals(previousAuthorizedSends, authorizedSends.get()); + assertEquals(previousPolicyCalls, customPolicyCalls.get()); + } + } + + private static int readPages(PagedIterable sync, PagedFlux async, String nextLink) { + AtomicInteger pages = new AtomicInteger(); + SyncAsyncExtension.execute(() -> sync.iterableByPage(nextLink).forEach(page -> pages.incrementAndGet()), + () -> (nextLink == null ? async.byPage() : async.byPage(nextLink)).doOnNext(page -> pages.incrementAndGet()) + .then()); + return pages.get(); + } + + private KeyVaultAccessControlClientBuilder builder(boolean customPipeline, boolean disableVerification) { + TokenCredential credential = context -> { + tokenRequests.incrementAndGet(); + return Mono.just(new AccessToken("fake-key-vault-token", OffsetDateTime.now().plusHours(1))); + }; + HttpClient httpClient = request -> Mono.fromSupplier(() -> { + sends.incrementAndGet(); + String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); + if (authorization == null) { + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, + "Bearer authorization=\"https://login.example/tenant\", resource=\"https://managedhsm.azure.net\"")); + } + assertEquals("Bearer fake-key-vault-token", authorization); + authorizedSends.incrementAndGet(); + String nextLink = responseNextLink.getAndSet(null); + String body = nextLink == null ? "{\"value\":[]}" : "{\"value\":[],\"nextLink\":\"" + nextLink + "\"}"; + return new MockHttpResponse(request, 200, + new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), + body.getBytes(StandardCharsets.UTF_8)); + }); + KeyVaultAccessControlClientBuilder builder + = new KeyVaultAccessControlClientBuilder().vaultUrl(ENDPOINT).credential(credential).httpClient(httpClient); + if (disableVerification) { + builder.disableChallengeResourceVerification(); + } + if (customPipeline) { + builder.pipeline(new HttpPipelineBuilder().httpClient(httpClient).policies((context, next) -> { + customPolicyCalls.incrementAndGet(); + return next.process(); + }, new BearerTokenAuthenticationPolicy(credential, "https://managedhsm.azure.net/.default")).build()); + } + return builder; + } +} diff --git a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md index 23c770ab893c8..09c9608dbd473 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md @@ -8,6 +8,9 @@ ### Bugs Fixed +- Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. +- Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. + ### Other Changes ## 4.11.1 (2026-11-02) diff --git a/sdk/keyvault/azure-security-keyvault-certificates/customizations/src/main/java/CertificatesCustomizations.java b/sdk/keyvault/azure-security-keyvault-certificates/customizations/src/main/java/CertificatesCustomizations.java index 33c6998c1e122..79cc0b5e87463 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/customizations/src/main/java/CertificatesCustomizations.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/customizations/src/main/java/CertificatesCustomizations.java @@ -9,6 +9,7 @@ import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.EnumDeclaration; import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.javadoc.Javadoc; import org.slf4j.Logger; @@ -29,6 +30,7 @@ public void customize(LibraryCustomization libraryCustomization, Logger logger) customizeCertificateKeyType(libraryCustomization); customizeCertificateKeyUsage(libraryCustomization); customizeServiceVersion(libraryCustomization); + customizePaging(libraryCustomization); customizeModuleInfo(libraryCustomization.getRawEditor()); customizePackageInfos(libraryCustomization.getRawEditor()); } @@ -40,6 +42,15 @@ private static void removeFiles(Editor editor) { editor.removeFile("src/main/java/com/azure/security/keyvault/certificates/KeyVaultServiceVersion.java"); } + private static void customizePaging(LibraryCustomization customization) { + customization.getClass("com.azure.security.keyvault.certificates.implementation", "CertificateClientImpl") + .customizeAst(ast -> ast.findAll(MethodCallExpr.class).stream() + .filter(call -> call.getScope().map(Object::toString).orElse("").equals("service") + && !call.getArguments().isEmpty() && call.getArgument(0).toString().equals("nextLink")) + .forEach(call -> call.setArgument(0, StaticJavaParser.parseExpression( + "KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl())")))); + } + private static void customizeError(LibraryCustomization customization) { String implModelsDirectory = "src/main/java/com/azure/security/keyvault/certificates/implementation/models/"; String oldClassName = "KeyVaultErrorError"; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java index f998c04ccefbc..82ca5d816f05e 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java @@ -6004,8 +6004,10 @@ public Response recoverDeletedCertificateWithResponse(String certifi private Mono> getCertificatesNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getCertificatesNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + return FluxUtil + .withContext(context -> service.getCertificatesNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -6048,8 +6050,9 @@ private Mono> getCertificatesNextSinglePageAsync(Strin @ServiceMethod(returns = ReturnType.SINGLE) private PagedResponse getCertificatesNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getCertificatesNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + Response res = service.getCertificatesNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } @@ -6083,8 +6086,9 @@ private Mono> getCertificateIssuersNextSinglePageAsync RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getCertificateIssuersNext(nextLink, this.getVaultBaseUrl(), accept, - requestOptions, context)) + .withContext(context -> service.getCertificateIssuersNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -6116,8 +6120,9 @@ private Mono> getCertificateIssuersNextSinglePageAsync private PagedResponse getCertificateIssuersNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getCertificateIssuersNextSync(nextLink, this.getVaultBaseUrl(), accept, - requestOptions, Context.NONE); + Response res = service.getCertificateIssuersNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } @@ -6162,8 +6167,9 @@ private Mono> getCertificateVersionsNextSinglePageAsyn RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getCertificateVersionsNext(nextLink, this.getVaultBaseUrl(), accept, - requestOptions, context)) + .withContext(context -> service.getCertificateVersionsNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -6207,8 +6213,9 @@ private Mono> getCertificateVersionsNextSinglePageAsyn private PagedResponse getCertificateVersionsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getCertificateVersionsNextSync(nextLink, this.getVaultBaseUrl(), accept, - requestOptions, Context.NONE); + Response res = service.getCertificateVersionsNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } @@ -6257,8 +6264,9 @@ private Mono> getDeletedCertificatesNextSinglePageAsyn RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext(context -> service.getDeletedCertificatesNext(nextLink, this.getVaultBaseUrl(), accept, - requestOptions, context)) + .withContext(context -> service.getDeletedCertificatesNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -6305,8 +6313,9 @@ private Mono> getDeletedCertificatesNextSinglePageAsyn private PagedResponse getDeletedCertificatesNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res = service.getDeletedCertificatesNextSync(nextLink, this.getVaultBaseUrl(), accept, - requestOptions, Context.NONE); + Response res = service.getDeletedCertificatesNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java index fa2e5607f7505..ca7725b3ab39a 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.security.keyvault.certificates.implementation; +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.AccessTokenCache; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; import com.azure.core.http.HttpPipelineCallContext; @@ -20,15 +22,18 @@ import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static com.azure.core.http.HttpHeaderName.AUTHORIZATION; import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH; import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE; @@ -42,9 +47,12 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class); private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; + private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); - private ChallengeParameters challenge; + private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; + private final TokenCredential credential; + private final ConcurrentMap accessTokenCaches = new ConcurrentHashMap<>(); /** * Creates a {@link KeyVaultCredentialPolicy}. @@ -55,6 +63,7 @@ public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChall super(credential); this.disableChallengeResourceVerification = disableChallengeResourceVerification; + this.credential = credential; } /** @@ -82,17 +91,13 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext - = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) + .setCaeEnabled(true); return setAuthorizationHeader(context, tokenRequestContext); } @@ -130,7 +135,7 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -141,10 +146,11 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return Mono.just(false); } } else { @@ -173,13 +179,14 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -205,15 +212,12 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context public void authorizeRequestSync(HttpPipelineCallContext context) { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); setAuthorizationHeaderSync(context, tokenRequestContext); @@ -248,7 +252,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -258,10 +262,11 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return false; } } else { @@ -291,13 +296,14 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -319,6 +325,28 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, return true; } + @Override + public Mono setAuthorizationHeader(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + return Mono.defer(() -> { + String authority = getRequestAuthority(context); + return getAccessTokenCache(authority, tokenRequestContext).getToken(tokenRequestContext, true) + .flatMap(token -> { + // The request is mutable while asynchronous credential acquisition is in progress. + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + return Mono.empty(); + }); + }); + } + + @Override + public void setAuthorizationHeaderSync(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + String authority = getRequestAuthority(context); + AccessToken token = getAccessTokenCache(authority, tokenRequestContext).getTokenSync(tokenRequestContext, true); + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + } + @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { @@ -426,12 +454,48 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { + if (context == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); + } + // Keep one current context per origin. A failed refresh must never expose a token from an older context. + return accessTokenCaches.compute(authority, + (ignored, existing) -> existing != null && existing.matches(context) + ? existing + : new TokenCache(credential, context)).cache; + } + + private static final class TokenCache { + private final AccessTokenCache cache; + private final List scopes; + private final String tenantId; + private final String claims; + private final boolean caeEnabled; + + private TokenCache(TokenCredential credential, TokenRequestContext context) { + cache = new AccessTokenCache(credential); + scopes = new ArrayList<>(context.getScopes()); + tenantId = context.getTenantId(); + claims = context.getClaims(); + caeEnabled = context.isCaeEnabled(); + } + + private boolean matches(TokenRequestContext context) { + return scopes.equals(context.getScopes()) + && Objects.equals(tenantId, context.getTenantId()) + && Objects.equals(claims, context.getClaims()) + && caeEnabled == context.isCaeEnabled(); + } + } + private static class ChallengeParameters { + private final String authority; private final URI authorizationUri; private final String tenantId; private final String[] scopes; - ChallengeParameters(URI authorizationUri, String[] scopes) { + ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; this.scopes = scopes; @@ -464,26 +528,41 @@ public static void clearCache() { CHALLENGE_CACHE.clear(); } - /** - * Gets the host name and port of the Key Vault or Managed HSM endpoint. - * - * @param request The {@link HttpRequest} to extract the host name and port from. - * - * @return The host name and port of the Key Vault or Managed HSM endpoint. - */ - private static String getRequestAuthority(HttpRequest request) { - URL url = request.getUrl(); - String authority = url.getAuthority(); - int port = url.getPort(); - - // Append port for complete authority. - if (!authority.contains(":") && port > 0) { - authority = authority + ":" + port; + private ChallengeParameters getChallenge(HttpPipelineCallContext context) { + String authority = getRequestAuthority(context); + // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. + ChallengeParameters cachedChallenge = this.challenge; + if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { + cachedChallenge = CHALLENGE_CACHE.get(authority); + this.challenge = cachedChallenge; } + return cachedChallenge; + } + private static String getRequestAuthority(HttpPipelineCallContext context) { + String authority = (String) context.getData(KEY_VAULT_REQUEST_ORIGIN_KEY).orElse(null); + if (authority == null) { + authority = KeyVaultEndpointValidation.getOrigin(context.getHttpRequest().getUrl().toString()); + context.setData(KEY_VAULT_REQUEST_ORIGIN_KEY, authority); + } + validateRequestAuthority(context, authority); return authority; } + private static void validateRequestAuthority(HttpPipelineCallContext context, String authority) { + HttpRequest request = context.getHttpRequest(); + try { + if (!authority.equals(KeyVaultEndpointValidation.getOrigin(request.getUrl().toString()))) { + throw new IllegalArgumentException( + "The request URL must have the same origin as the original request."); + } + } catch (RuntimeException e) { + // A previous attempt may already have authorized this request before its destination changed. + request.getHeaders().remove(AUTHORIZATION); + throw LOGGER.logExceptionAsError(e); + } + } + private static boolean isChallengeResourceValid(HttpRequest request, String scope) { final URI scopeUri; diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultEndpointValidation.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultEndpointValidation.java new file mode 100644 index 0000000000000..6c8aa1e7839fe --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultEndpointValidation.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates.implementation; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; + +/** + * Validates Key Vault continuation destinations independently of the HTTP pipeline. + */ +final class KeyVaultEndpointValidation { + private KeyVaultEndpointValidation() { + } + + static String validateNextLink(String nextLink, String endpoint) { + if (!getOrigin(endpoint).equals(getOrigin(nextLink))) { + throw new IllegalArgumentException( + "The continuation URL must have the same origin as the configured endpoint."); + } + return nextLink; + } + + static String getOrigin(String url) { + final URI uri; + try { + uri = new URI(url).parseServerAuthority(); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid Key Vault URL.", e); + } + + String scheme = uri.getScheme(); + if ((!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawFragment() != null + || uri.getPort() < -1 + || uri.getPort() > 65535) { + throw new IllegalArgumentException("Invalid Key Vault URL."); + } + + int port = uri.getPort() == -1 ? ("https".equalsIgnoreCase(scheme) ? 443 : 80) : uri.getPort(); + return scheme.toLowerCase(Locale.ROOT) + "://" + uri.getHost().toLowerCase(Locale.ROOT) + ":" + port; + } +} diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java index f9b26586cf606..ab2b560140762 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java @@ -14,6 +14,8 @@ import com.azure.core.http.HttpPipelineCallContext; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.FixedDelay; +import com.azure.core.http.policy.RetryPolicy; import com.azure.core.test.SyncAsyncExtension; import com.azure.core.test.annotation.SyncAsyncTest; import com.azure.core.test.http.MockHttpResponse; @@ -28,15 +30,18 @@ import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; import reactor.test.StepVerifier; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -147,6 +152,229 @@ public void cleanup() { KeyVaultCredentialPolicy.clearCache(); } + @SyncAsyncTest + public void failedAcquisitionCannotReuseAnotherOriginsToken() { + for (boolean sameTenant : new boolean[] { false, true }) { + for (boolean sameScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean failAcquisition = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger foreignAuthorizedSends = new AtomicInteger(); + String secondTenant = sameTenant ? "first" : "second"; + String secondScope = sameScope ? "https://vault.azure.net/.default" : "https://azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (failAcquisition.get()) { + assertEquals(secondTenant, context.getTenantId()); + assertEquals(Arrays.asList(secondScope), context.getScopes()); + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + boolean second = request.getUrl().getHost().equals("second.vault.azure.net"); + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono.just(tokenCacheChallenge(request, second ? secondTenant : "first", + second ? secondScope : "https://vault.azure.net/.default", null)); + } + if (second) { + foreignAuthorizedSends.incrementAndGet(); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertEquals(1, tokenRequests.get()); + failAcquisition.set(true); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://second.vault.azure.net")); + assertEquals(0, foreignAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + + failAcquisition.set(false); + sendTokenCacheRequest(pipeline, "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets"); + assertEquals(4, tokenRequests.get(), + "A failed acquisition for another origin must not evict this token."); + } + } + } + + @SyncAsyncTest + public void failedContextChangeCannotReusePreviousToken() { + for (String change : Arrays.asList("tenant", "scope", "claims")) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean changedChallenge = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger staleAuthorizedSends = new AtomicInteger(); + String tenant = "tenant".equals(change) ? "second" : "first"; + String scope = "scope".equals(change) ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + String claims = "claims".equals(change) ? DECODED_CLAIMS : null; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (changedChallenge.get()) { + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (changedChallenge.get() && authorization != null) { + staleAuthorizedSends.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 200)); + } + if ("/changed".equals(request.getUrl().getPath())) { + changedChallenge.set(true); + return Mono.just(tokenCacheChallenge(request, tenant, scope, claims)); + } + return Mono.just(authorization == null + ? tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null) + : new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed")); + assertEquals(0, staleAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + } + } + + @SyncAsyncTest + public void originScopedTokensSupportRetriesAndNormalization() { + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + } + if (secondTokenRequests.incrementAndGet() == 1) { + throw new IllegalStateException("Transient token acquisition failure."); + } + return new AccessToken("second-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String tenant + = request.getUrl().getHost().equalsIgnoreCase("first.vault.azure.net") ? "first" : "second"; + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, tenant, "https://vault.azure.net/.default", null)); + } + assertEquals("Bearer " + tenant + "-origin-token", authorization); + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + for (String url : Arrays.asList("https://first.vault.azure.net", "https://second.vault.azure.net", + "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets", "HTTPS://SECOND.VAULT.AZURE.NET:443/secrets")) { + assertEquals(200, sendTokenCacheRequest(pipeline, url).getStatusCode()); + } + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + } + + @Test + public void concurrentTokenAcquisitionsKeepIndependentCacheState() { + for (boolean sameOrigin : new boolean[] { false, true }) { + Sinks.One firstToken = Sinks.one(); + Sinks.One secondToken = Sinks.one(); + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return firstToken.asMono(); + } + if (secondTokenRequests.incrementAndGet() == 1) { + return Mono.error(new IllegalStateException("Transient token acquisition failure.")); + } + return secondToken.asMono(); + }, false); + HttpPipelineCallContext firstContext + = createCallContext(new HttpRequest(HttpMethod.GET, "https://first.vault.azure.net"), Context.NONE); + HttpPipelineCallContext secondContext = createCallContext(new HttpRequest(HttpMethod.GET, + sameOrigin ? "https://first.vault.azure.net" : "https://second.vault.azure.net"), Context.NONE); + TokenRequestContext firstRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("first") + .setCaeEnabled(true); + TokenRequestContext secondRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("second") + .setCaeEnabled(true); + + StepVerifier.create(Mono.when(policy.setAuthorizationHeader(firstContext, firstRequest), + policy.setAuthorizationHeader(secondContext, secondRequest).retry(1))).then(() -> { + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + secondToken.tryEmitValue(new AccessToken("second-token", OffsetDateTime.now().plusHours(1))); + firstToken.tryEmitValue(new AccessToken("first-token", OffsetDateTime.now().plusHours(1))); + }).expectComplete().verify(Duration.ofSeconds(5)); + assertEquals("Bearer first-token", firstContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals("Bearer second-token", secondContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + StepVerifier.create(policy.setAuthorizationHeader(secondContext, secondRequest)).verifyComplete(); + assertEquals(2, secondTokenRequests.get()); + } + } + + private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String url) { + HttpRequest request = new HttpRequest(HttpMethod.GET, url); + return SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE)); + } + + private static HttpResponse tokenCacheChallenge(HttpRequest request, String tenant, String scope, String claims) { + String challenge = "Bearer authorization=\"https://login.example/" + tenant + "\", scope=\"" + scope + "\""; + if (claims != null) { + challenge += ", error=\"insufficient_claims\", claims=\"" + + Base64Util.encodeToString(claims.getBytes(StandardCharsets.UTF_8)) + "\""; + } + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, challenge)); + } + + @SyncAsyncTest + public void cachedChallengeIsBoundToRequestOrigin() { + AtomicInteger tokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false); + SyncAsyncExtension.execute( + () -> policy.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> policy.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + assertEquals(1, tokenRequests.get()); + + for (KeyVaultCredentialPolicy cachedPolicy : Arrays.asList(policy, new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false))) { + for (String endpoint : Arrays.asList("https://other.vault.azure.net", "https://kvtest.vault.azure.net:8443", + "http://kvtest.vault.azure.net")) { + HttpPipelineCallContext foreignContext + = createCallContext(new HttpRequest(HttpMethod.GET, endpoint), Context.NONE); + int previousTokenRequests = tokenRequests.get(); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(foreignContext), + () -> cachedPolicy.authorizeRequest(foreignContext)); + assertNull(foreignContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals(previousTokenRequests, tokenRequests.get()); + } + + HttpPipelineCallContext normalizedContext = createCallContext( + new HttpRequest(HttpMethod.GET, "HTTPS://KVTEST.VAULT.AZURE.NET:443/certificates"), Context.NONE); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(normalizedContext), + () -> cachedPolicy.authorizeRequest(normalizedContext)); + assertNotNull(normalizedContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + } + } + @SyncAsyncTest public void onNon401ErrorResponse() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); @@ -164,6 +392,76 @@ public void onNon401ErrorResponse() { KeyVaultCredentialPolicy.clearCache(); } + @SyncAsyncTest + public void requestOriginIsRevalidatedDuringTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean cachedChallenge : new boolean[] { false, true }) { + for (String destination : Arrays.asList("https://other.example/certificates", + "https://other.vault.azure.net/certificates", "https://kvtest.vault.azure.net:8443/certificates", + "http://kvtest.vault.azure.net/certificates", "https://user@kvtest.vault.azure.net/certificates")) { + KeyVaultCredentialPolicy.clearCache(); + if (cachedChallenge) { + KeyVaultCredentialPolicy seed = new KeyVaultCredentialPolicy(credential, false); + SyncAsyncExtension.execute( + () -> seed.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> seed.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + } + HttpRequest request + = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/certificates"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + TokenCredential mutatingCredential = context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + request.setUrl(destination); + return new AccessToken("fake-token", OffsetDateTime.now().plusHours(1)); + }); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new KeyVaultCredentialPolicy(mutatingCredential, disableVerification)) + .httpClient(ignored -> { + sends.incrementAndGet(); + return Mono.just(request.getHeaders().getValue(AUTHORIZATION) == null + ? unauthorizedHttpResponseWithHeader + : simpleResponse); + }) + .build(); + + assertThrows(IllegalArgumentException.class, + () -> SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(cachedChallenge ? 0 : 1, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + } + } + + @SyncAsyncTest + public void requestOriginIsRevalidatedBeforeCaeTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/certificates"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + HttpPipeline pipeline = new HttpPipelineBuilder().policies(new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, disableVerification)).httpClient(ignored -> { + if (sends.incrementAndGet() == 1) { + return Mono.just(unauthorizedHttpResponseWithHeader); + } + request.setUrl("https://other.vault.azure.net/certificates"); + return Mono.just(unauthorizedHttpResponseWithHeaderAndClaims); + }).build(); + + assertThrows(IllegalArgumentException.class, () -> SyncAsyncExtension + .execute(() -> pipeline.sendSync(request, Context.NONE), () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(2, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + @SyncAsyncTest public void on401UnauthorizedResponseWithHeader() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java new file mode 100644 index 0000000000000..73755ba4c0dd6 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java @@ -0,0 +1,157 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.certificates; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.test.SyncAsyncExtension; +import com.azure.core.test.annotation.SyncAsyncTest; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.security.keyvault.certificates.implementation.KeyVaultCredentialPolicy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import reactor.core.publisher.Mono; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Execution(ExecutionMode.SAME_THREAD) +public class KeyVaultPaginationTest { + private static final String ENDPOINT = "https://paging.vault.azure.net"; + private final AtomicInteger tokenRequests = new AtomicInteger(); + private final AtomicInteger sends = new AtomicInteger(); + private final AtomicInteger authorizedSends = new AtomicInteger(); + private final AtomicInteger customPolicyCalls = new AtomicInteger(); + private final AtomicReference responseNextLink = new AtomicReference<>(); + + @AfterEach + public void cleanup() { + KeyVaultCredentialPolicy.clearCache(); + } + + @SyncAsyncTest + public void allContinuationOperationsValidateBeforePipeline() { + for (boolean customPipeline : new boolean[] { false, true }) { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + CertificateClientBuilder builder = builder(customPipeline, disableVerification); + CertificateClient client = builder.buildClient(); + CertificateAsyncClient asyncClient = builder.buildAsyncClient(); + List> syncPages = Arrays.asList(client.listPropertiesOfCertificates(), + client.listPropertiesOfCertificateVersions("certificate"), client.listDeletedCertificates(), + client.listPropertiesOfIssuers()); + List> asyncPages = Arrays.asList(asyncClient.listPropertiesOfCertificates(), + asyncClient.listPropertiesOfCertificateVersions("certificate"), + asyncClient.listDeletedCertificates(), asyncClient.listPropertiesOfIssuers()); + + for (int i = 0; i < syncPages.size(); i++) { + PagedIterable sync = syncPages.get(i); + PagedFlux async = asyncPages.get(i); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, null)); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, "HTTPS://PAGING.VAULT.AZURE.NET:443/certificates?skip=1")); + } + + assertRejectedContinuations(builder.buildClient().listPropertiesOfCertificates(), + builder.buildAsyncClient().listPropertiesOfCertificates()); + } + } + assertTrue(tokenRequests.get() > 0); + assertTrue(authorizedSends.get() > 0); + } + + @SyncAsyncTest + public void serviceProvidedContinuationIsValidated() { + CertificateClientBuilder builder = builder(false, false); + CertificateClient client = builder.buildClient(); + CertificateAsyncClient asyncClient = builder.buildAsyncClient(); + responseNextLink.set(ENDPOINT + "/certificates?skip=1"); + assertEquals(2, + readPages(client.listPropertiesOfCertificates(), asyncClient.listPropertiesOfCertificates(), null)); + + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + responseNextLink.set("https://other.example/certificates"); + assertThrows(IllegalArgumentException.class, + () -> readPages(client.listPropertiesOfCertificates(), asyncClient.listPropertiesOfCertificates(), null)); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends + 1, sends.get()); + } + + private void assertRejectedContinuations(PagedIterable sync, PagedFlux async) { + for (String nextLink : Arrays.asList("https://other.example/certificates", + "https://other.vault.azure.net/certificates", "http://paging.vault.azure.net/certificates", + ENDPOINT + ":8443/certificates", "https://user@paging.vault.azure.net/certificates", + ENDPOINT + ":invalid/certificates", "/certificates")) { + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + int previousAuthorizedSends = authorizedSends.get(); + int previousPolicyCalls = customPolicyCalls.get(); + assertThrows(IllegalArgumentException.class, () -> readPages(sync, async, nextLink), nextLink); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + assertEquals(previousAuthorizedSends, authorizedSends.get()); + assertEquals(previousPolicyCalls, customPolicyCalls.get()); + } + } + + private static int readPages(PagedIterable sync, PagedFlux async, String nextLink) { + AtomicInteger pages = new AtomicInteger(); + SyncAsyncExtension.execute(() -> sync.iterableByPage(nextLink).forEach(page -> pages.incrementAndGet()), + () -> (nextLink == null ? async.byPage() : async.byPage(nextLink)).doOnNext(page -> pages.incrementAndGet()) + .then()); + return pages.get(); + } + + private CertificateClientBuilder builder(boolean customPipeline, boolean disableVerification) { + TokenCredential credential = context -> { + tokenRequests.incrementAndGet(); + return Mono.just(new AccessToken("fake-key-vault-token", OffsetDateTime.now().plusHours(1))); + }; + HttpClient httpClient = request -> Mono.fromSupplier(() -> { + sends.incrementAndGet(); + String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); + if (authorization == null) { + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, + "Bearer authorization=\"https://login.example/tenant\", resource=\"https://vault.azure.net\"")); + } + assertEquals("Bearer fake-key-vault-token", authorization); + authorizedSends.incrementAndGet(); + String nextLink = responseNextLink.getAndSet(null); + String body = nextLink == null ? "{\"value\":[]}" : "{\"value\":[],\"nextLink\":\"" + nextLink + "\"}"; + return new MockHttpResponse(request, 200, + new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), + body.getBytes(StandardCharsets.UTF_8)); + }); + CertificateClientBuilder builder + = new CertificateClientBuilder().vaultUrl(ENDPOINT).credential(credential).httpClient(httpClient); + if (disableVerification) { + builder.disableChallengeResourceVerification(); + } + if (customPipeline) { + builder.pipeline(new HttpPipelineBuilder().httpClient(httpClient).policies((context, next) -> { + customPolicyCalls.incrementAndGet(); + return next.process(); + }, new BearerTokenAuthenticationPolicy(credential, "https://vault.azure.net/.default")).build()); + } + return builder; + } +} diff --git a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md index 1e688986022c2..21783704538bf 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md @@ -8,6 +8,9 @@ ### Bugs Fixed +- Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. +- Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. + ### Other Changes ## 4.13.0 (2026-11-13) diff --git a/sdk/keyvault/azure-security-keyvault-keys/customizations/src/main/java/KeysCustomizations.java b/sdk/keyvault/azure-security-keyvault-keys/customizations/src/main/java/KeysCustomizations.java index 5b31f1b164974..4f37c11961ea6 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/customizations/src/main/java/KeysCustomizations.java +++ b/sdk/keyvault/azure-security-keyvault-keys/customizations/src/main/java/KeysCustomizations.java @@ -9,6 +9,7 @@ import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.EnumDeclaration; import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.javadoc.Javadoc; import org.slf4j.Logger; @@ -25,6 +26,7 @@ public class KeysCustomizations extends Customization { public void customize(LibraryCustomization libraryCustomization, Logger logger) { removeFiles(libraryCustomization.getRawEditor()); customizeServiceVersion(libraryCustomization); + customizePaging(libraryCustomization); customizeKeyAttestation(libraryCustomization); customizeKeyCurveName(libraryCustomization); customizeKeyOperation(libraryCustomization); @@ -41,6 +43,15 @@ private static void removeFiles(Editor editor) { editor.removeFile("src/main/java/com/azure/security/keyvault/keys/KeyVaultServiceVersion.java"); } + private static void customizePaging(LibraryCustomization customization) { + customization.getClass("com.azure.security.keyvault.keys.implementation", "KeyClientImpl") + .customizeAst(ast -> ast.findAll(MethodCallExpr.class).stream() + .filter(call -> call.getScope().map(Object::toString).orElse("").equals("service") + && !call.getArguments().isEmpty() && call.getArgument(0).toString().equals("nextLink")) + .forEach(call -> call.setArgument(0, StaticJavaParser.parseExpression( + "KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl())")))); + } + private static void customizeServiceVersion(LibraryCustomization customization) { CompilationUnit compilationUnit = new CompilationUnit(); diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java index 8d643f92a436e..7f331ace0925b 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java @@ -5054,8 +5054,10 @@ public Response getKeyAttestationWithResponse(String keyName, String private Mono> getKeyVersionsNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getKeyVersionsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + return FluxUtil + .withContext(context -> service.getKeyVersionsNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -5110,8 +5112,9 @@ private Mono> getKeyVersionsNextSinglePageAsync(String @ServiceMethod(returns = ReturnType.SINGLE) private PagedResponse getKeyVersionsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getKeyVersionsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + Response res = service.getKeyVersionsNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } @@ -5167,8 +5170,9 @@ private PagedResponse getKeyVersionsNextSinglePage(String nextLink, private Mono> getKeysNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext( - context -> service.getKeysNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + .withContext(context -> service.getKeysNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -5224,7 +5228,8 @@ private Mono> getKeysNextSinglePageAsync(String nextLi private PagedResponse getKeysNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; Response res - = service.getKeysNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + = service.getKeysNextSync(KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), + this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } @@ -5284,8 +5289,10 @@ private PagedResponse getKeysNextSinglePage(String nextLink, Request private Mono> getDeletedKeysNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getDeletedKeysNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + return FluxUtil + .withContext(context -> service.getDeletedKeysNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -5343,8 +5350,9 @@ private Mono> getDeletedKeysNextSinglePageAsync(String @ServiceMethod(returns = ReturnType.SINGLE) private PagedResponse getDeletedKeysNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getDeletedKeysNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + Response res = service.getDeletedKeysNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java index eb7bc9ca2be90..4eb339ab7a6a8 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.security.keyvault.keys.implementation; +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.AccessTokenCache; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; import com.azure.core.http.HttpPipelineCallContext; @@ -20,15 +22,18 @@ import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static com.azure.core.http.HttpHeaderName.AUTHORIZATION; import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH; import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE; @@ -42,9 +47,12 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class); private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; + private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); - private ChallengeParameters challenge; + private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; + private final TokenCredential credential; + private final ConcurrentMap accessTokenCaches = new ConcurrentHashMap<>(); /** * Creates a {@link KeyVaultCredentialPolicy}. @@ -55,6 +63,7 @@ public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChall super(credential); this.disableChallengeResourceVerification = disableChallengeResourceVerification; + this.credential = credential; } /** @@ -82,17 +91,13 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext - = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) + .setCaeEnabled(true); return setAuthorizationHeader(context, tokenRequestContext); } @@ -130,7 +135,7 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -141,10 +146,11 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return Mono.just(false); } } else { @@ -173,13 +179,14 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -205,15 +212,12 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context public void authorizeRequestSync(HttpPipelineCallContext context) { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); setAuthorizationHeaderSync(context, tokenRequestContext); @@ -248,7 +252,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -258,10 +262,11 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return false; } } else { @@ -291,13 +296,14 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -319,6 +325,28 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, return true; } + @Override + public Mono setAuthorizationHeader(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + return Mono.defer(() -> { + String authority = getRequestAuthority(context); + return getAccessTokenCache(authority, tokenRequestContext).getToken(tokenRequestContext, true) + .flatMap(token -> { + // The request is mutable while asynchronous credential acquisition is in progress. + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + return Mono.empty(); + }); + }); + } + + @Override + public void setAuthorizationHeaderSync(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + String authority = getRequestAuthority(context); + AccessToken token = getAccessTokenCache(authority, tokenRequestContext).getTokenSync(tokenRequestContext, true); + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + } + @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { @@ -426,12 +454,48 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { + if (context == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); + } + // Keep one current context per origin. A failed refresh must never expose a token from an older context. + return accessTokenCaches.compute(authority, + (ignored, existing) -> existing != null && existing.matches(context) + ? existing + : new TokenCache(credential, context)).cache; + } + + private static final class TokenCache { + private final AccessTokenCache cache; + private final List scopes; + private final String tenantId; + private final String claims; + private final boolean caeEnabled; + + private TokenCache(TokenCredential credential, TokenRequestContext context) { + cache = new AccessTokenCache(credential); + scopes = new ArrayList<>(context.getScopes()); + tenantId = context.getTenantId(); + claims = context.getClaims(); + caeEnabled = context.isCaeEnabled(); + } + + private boolean matches(TokenRequestContext context) { + return scopes.equals(context.getScopes()) + && Objects.equals(tenantId, context.getTenantId()) + && Objects.equals(claims, context.getClaims()) + && caeEnabled == context.isCaeEnabled(); + } + } + private static class ChallengeParameters { + private final String authority; private final URI authorizationUri; private final String tenantId; private final String[] scopes; - ChallengeParameters(URI authorizationUri, String[] scopes) { + ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; this.scopes = scopes; @@ -464,26 +528,41 @@ public static void clearCache() { CHALLENGE_CACHE.clear(); } - /** - * Gets the host name and port of the Key Vault or Managed HSM endpoint. - * - * @param request The {@link HttpRequest} to extract the host name and port from. - * - * @return The host name and port of the Key Vault or Managed HSM endpoint. - */ - private static String getRequestAuthority(HttpRequest request) { - URL url = request.getUrl(); - String authority = url.getAuthority(); - int port = url.getPort(); - - // Append port for complete authority. - if (!authority.contains(":") && port > 0) { - authority = authority + ":" + port; + private ChallengeParameters getChallenge(HttpPipelineCallContext context) { + String authority = getRequestAuthority(context); + // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. + ChallengeParameters cachedChallenge = this.challenge; + if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { + cachedChallenge = CHALLENGE_CACHE.get(authority); + this.challenge = cachedChallenge; } + return cachedChallenge; + } + private static String getRequestAuthority(HttpPipelineCallContext context) { + String authority = (String) context.getData(KEY_VAULT_REQUEST_ORIGIN_KEY).orElse(null); + if (authority == null) { + authority = KeyVaultEndpointValidation.getOrigin(context.getHttpRequest().getUrl().toString()); + context.setData(KEY_VAULT_REQUEST_ORIGIN_KEY, authority); + } + validateRequestAuthority(context, authority); return authority; } + private static void validateRequestAuthority(HttpPipelineCallContext context, String authority) { + HttpRequest request = context.getHttpRequest(); + try { + if (!authority.equals(KeyVaultEndpointValidation.getOrigin(request.getUrl().toString()))) { + throw new IllegalArgumentException( + "The request URL must have the same origin as the original request."); + } + } catch (RuntimeException e) { + // A previous attempt may already have authorized this request before its destination changed. + request.getHeaders().remove(AUTHORIZATION); + throw LOGGER.logExceptionAsError(e); + } + } + private static boolean isChallengeResourceValid(HttpRequest request, String scope) { final URI scopeUri; diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultEndpointValidation.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultEndpointValidation.java new file mode 100644 index 0000000000000..41f523efa4fcd --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultEndpointValidation.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys.implementation; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; + +/** + * Validates Key Vault continuation destinations independently of the HTTP pipeline. + */ +final class KeyVaultEndpointValidation { + private KeyVaultEndpointValidation() { + } + + static String validateNextLink(String nextLink, String endpoint) { + if (!getOrigin(endpoint).equals(getOrigin(nextLink))) { + throw new IllegalArgumentException( + "The continuation URL must have the same origin as the configured endpoint."); + } + return nextLink; + } + + static String getOrigin(String url) { + final URI uri; + try { + uri = new URI(url).parseServerAuthority(); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid Key Vault URL.", e); + } + + String scheme = uri.getScheme(); + if ((!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawFragment() != null + || uri.getPort() < -1 + || uri.getPort() > 65535) { + throw new IllegalArgumentException("Invalid Key Vault URL."); + } + + int port = uri.getPort() == -1 ? ("https".equalsIgnoreCase(scheme) ? 443 : 80) : uri.getPort(); + return scheme.toLowerCase(Locale.ROOT) + "://" + uri.getHost().toLowerCase(Locale.ROOT) + ":" + port; + } +} diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java index 9ff7d06b868d7..d1f47227f4bc5 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java @@ -14,6 +14,8 @@ import com.azure.core.http.HttpPipelineCallContext; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.FixedDelay; +import com.azure.core.http.policy.RetryPolicy; import com.azure.core.test.SyncAsyncExtension; import com.azure.core.test.annotation.SyncAsyncTest; import com.azure.core.test.http.MockHttpResponse; @@ -28,15 +30,18 @@ import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; import reactor.test.StepVerifier; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -147,6 +152,229 @@ public void cleanup() { KeyVaultCredentialPolicy.clearCache(); } + @SyncAsyncTest + public void failedAcquisitionCannotReuseAnotherOriginsToken() { + for (boolean sameTenant : new boolean[] { false, true }) { + for (boolean sameScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean failAcquisition = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger foreignAuthorizedSends = new AtomicInteger(); + String secondTenant = sameTenant ? "first" : "second"; + String secondScope = sameScope ? "https://vault.azure.net/.default" : "https://azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (failAcquisition.get()) { + assertEquals(secondTenant, context.getTenantId()); + assertEquals(Arrays.asList(secondScope), context.getScopes()); + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + boolean second = request.getUrl().getHost().equals("second.vault.azure.net"); + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono.just(tokenCacheChallenge(request, second ? secondTenant : "first", + second ? secondScope : "https://vault.azure.net/.default", null)); + } + if (second) { + foreignAuthorizedSends.incrementAndGet(); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertEquals(1, tokenRequests.get()); + failAcquisition.set(true); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://second.vault.azure.net")); + assertEquals(0, foreignAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + + failAcquisition.set(false); + sendTokenCacheRequest(pipeline, "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets"); + assertEquals(4, tokenRequests.get(), + "A failed acquisition for another origin must not evict this token."); + } + } + } + + @SyncAsyncTest + public void failedContextChangeCannotReusePreviousToken() { + for (String change : Arrays.asList("tenant", "scope", "claims")) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean changedChallenge = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger staleAuthorizedSends = new AtomicInteger(); + String tenant = "tenant".equals(change) ? "second" : "first"; + String scope = "scope".equals(change) ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + String claims = "claims".equals(change) ? DECODED_CLAIMS : null; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (changedChallenge.get()) { + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (changedChallenge.get() && authorization != null) { + staleAuthorizedSends.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 200)); + } + if ("/changed".equals(request.getUrl().getPath())) { + changedChallenge.set(true); + return Mono.just(tokenCacheChallenge(request, tenant, scope, claims)); + } + return Mono.just(authorization == null + ? tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null) + : new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed")); + assertEquals(0, staleAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + } + } + + @SyncAsyncTest + public void originScopedTokensSupportRetriesAndNormalization() { + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + } + if (secondTokenRequests.incrementAndGet() == 1) { + throw new IllegalStateException("Transient token acquisition failure."); + } + return new AccessToken("second-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String tenant + = request.getUrl().getHost().equalsIgnoreCase("first.vault.azure.net") ? "first" : "second"; + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, tenant, "https://vault.azure.net/.default", null)); + } + assertEquals("Bearer " + tenant + "-origin-token", authorization); + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + for (String url : Arrays.asList("https://first.vault.azure.net", "https://second.vault.azure.net", + "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets", "HTTPS://SECOND.VAULT.AZURE.NET:443/secrets")) { + assertEquals(200, sendTokenCacheRequest(pipeline, url).getStatusCode()); + } + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + } + + @Test + public void concurrentTokenAcquisitionsKeepIndependentCacheState() { + for (boolean sameOrigin : new boolean[] { false, true }) { + Sinks.One firstToken = Sinks.one(); + Sinks.One secondToken = Sinks.one(); + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return firstToken.asMono(); + } + if (secondTokenRequests.incrementAndGet() == 1) { + return Mono.error(new IllegalStateException("Transient token acquisition failure.")); + } + return secondToken.asMono(); + }, false); + HttpPipelineCallContext firstContext + = createCallContext(new HttpRequest(HttpMethod.GET, "https://first.vault.azure.net"), Context.NONE); + HttpPipelineCallContext secondContext = createCallContext(new HttpRequest(HttpMethod.GET, + sameOrigin ? "https://first.vault.azure.net" : "https://second.vault.azure.net"), Context.NONE); + TokenRequestContext firstRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("first") + .setCaeEnabled(true); + TokenRequestContext secondRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("second") + .setCaeEnabled(true); + + StepVerifier.create(Mono.when(policy.setAuthorizationHeader(firstContext, firstRequest), + policy.setAuthorizationHeader(secondContext, secondRequest).retry(1))).then(() -> { + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + secondToken.tryEmitValue(new AccessToken("second-token", OffsetDateTime.now().plusHours(1))); + firstToken.tryEmitValue(new AccessToken("first-token", OffsetDateTime.now().plusHours(1))); + }).expectComplete().verify(Duration.ofSeconds(5)); + assertEquals("Bearer first-token", firstContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals("Bearer second-token", secondContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + StepVerifier.create(policy.setAuthorizationHeader(secondContext, secondRequest)).verifyComplete(); + assertEquals(2, secondTokenRequests.get()); + } + } + + private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String url) { + HttpRequest request = new HttpRequest(HttpMethod.GET, url); + return SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE)); + } + + private static HttpResponse tokenCacheChallenge(HttpRequest request, String tenant, String scope, String claims) { + String challenge = "Bearer authorization=\"https://login.example/" + tenant + "\", scope=\"" + scope + "\""; + if (claims != null) { + challenge += ", error=\"insufficient_claims\", claims=\"" + + Base64Util.encodeToString(claims.getBytes(StandardCharsets.UTF_8)) + "\""; + } + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, challenge)); + } + + @SyncAsyncTest + public void cachedChallengeIsBoundToRequestOrigin() { + AtomicInteger tokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false); + SyncAsyncExtension.execute( + () -> policy.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> policy.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + assertEquals(1, tokenRequests.get()); + + for (KeyVaultCredentialPolicy cachedPolicy : Arrays.asList(policy, new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false))) { + for (String endpoint : Arrays.asList("https://other.vault.azure.net", "https://kvtest.vault.azure.net:8443", + "http://kvtest.vault.azure.net")) { + HttpPipelineCallContext foreignContext + = createCallContext(new HttpRequest(HttpMethod.GET, endpoint), Context.NONE); + int previousTokenRequests = tokenRequests.get(); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(foreignContext), + () -> cachedPolicy.authorizeRequest(foreignContext)); + assertNull(foreignContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals(previousTokenRequests, tokenRequests.get()); + } + + HttpPipelineCallContext normalizedContext = createCallContext( + new HttpRequest(HttpMethod.GET, "HTTPS://KVTEST.VAULT.AZURE.NET:443/keys"), Context.NONE); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(normalizedContext), + () -> cachedPolicy.authorizeRequest(normalizedContext)); + assertNotNull(normalizedContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + } + } + @SyncAsyncTest public void onNon401ErrorResponse() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); @@ -164,6 +392,75 @@ public void onNon401ErrorResponse() { KeyVaultCredentialPolicy.clearCache(); } + @SyncAsyncTest + public void requestOriginIsRevalidatedDuringTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean cachedChallenge : new boolean[] { false, true }) { + for (String destination : Arrays.asList("https://other.example/keys", + "https://other.vault.azure.net/keys", "https://kvtest.vault.azure.net:8443/keys", + "http://kvtest.vault.azure.net/keys", "https://user@kvtest.vault.azure.net/keys")) { + KeyVaultCredentialPolicy.clearCache(); + if (cachedChallenge) { + KeyVaultCredentialPolicy seed = new KeyVaultCredentialPolicy(credential, false); + SyncAsyncExtension.execute( + () -> seed.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> seed.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + } + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/keys"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + TokenCredential mutatingCredential = context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + request.setUrl(destination); + return new AccessToken("fake-token", OffsetDateTime.now().plusHours(1)); + }); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new KeyVaultCredentialPolicy(mutatingCredential, disableVerification)) + .httpClient(ignored -> { + sends.incrementAndGet(); + return Mono.just(request.getHeaders().getValue(AUTHORIZATION) == null + ? unauthorizedHttpResponseWithHeader + : simpleResponse); + }) + .build(); + + assertThrows(IllegalArgumentException.class, + () -> SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(cachedChallenge ? 0 : 1, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + } + } + + @SyncAsyncTest + public void requestOriginIsRevalidatedBeforeCaeTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/keys"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + HttpPipeline pipeline = new HttpPipelineBuilder().policies(new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, disableVerification)).httpClient(ignored -> { + if (sends.incrementAndGet() == 1) { + return Mono.just(unauthorizedHttpResponseWithHeader); + } + request.setUrl("https://other.vault.azure.net/keys"); + return Mono.just(unauthorizedHttpResponseWithHeaderAndClaims); + }).build(); + + assertThrows(IllegalArgumentException.class, () -> SyncAsyncExtension + .execute(() -> pipeline.sendSync(request, Context.NONE), () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(2, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + @SyncAsyncTest public void on401UnauthorizedResponseWithHeader() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java new file mode 100644 index 0000000000000..235fd9b22bd4a --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java @@ -0,0 +1,153 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.keys; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.test.SyncAsyncExtension; +import com.azure.core.test.annotation.SyncAsyncTest; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import reactor.core.publisher.Mono; + +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Execution(ExecutionMode.SAME_THREAD) +public class KeyVaultPaginationTest { + private static final String ENDPOINT = "https://paging.vault.azure.net"; + private final AtomicInteger tokenRequests = new AtomicInteger(); + private final AtomicInteger sends = new AtomicInteger(); + private final AtomicInteger authorizedSends = new AtomicInteger(); + private final AtomicInteger customPolicyCalls = new AtomicInteger(); + private final AtomicReference responseNextLink = new AtomicReference<>(); + + @AfterEach + public void cleanup() { + KeyVaultCredentialPolicy.clearCache(); + } + + @SyncAsyncTest + public void allContinuationOperationsValidateBeforePipeline() { + for (boolean customPipeline : new boolean[] { false, true }) { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + KeyClientBuilder builder = builder(customPipeline, disableVerification); + KeyClient client = builder.buildClient(); + KeyAsyncClient asyncClient = builder.buildAsyncClient(); + List> syncPages = Arrays.asList(client.listPropertiesOfKeys(), + client.listPropertiesOfKeyVersions("key"), client.listDeletedKeys()); + List> asyncPages = Arrays.asList(asyncClient.listPropertiesOfKeys(), + asyncClient.listPropertiesOfKeyVersions("key"), asyncClient.listDeletedKeys()); + + for (int i = 0; i < syncPages.size(); i++) { + PagedIterable sync = syncPages.get(i); + PagedFlux async = asyncPages.get(i); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, null)); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, "HTTPS://PAGING.VAULT.AZURE.NET:443/keys?skip=1")); + } + + assertRejectedContinuations(builder.buildClient().listPropertiesOfKeys(), + builder.buildAsyncClient().listPropertiesOfKeys()); + } + } + assertTrue(tokenRequests.get() > 0); + assertTrue(authorizedSends.get() > 0); + } + + @SyncAsyncTest + public void serviceProvidedContinuationIsValidated() { + KeyClientBuilder builder = builder(false, false); + KeyClient client = builder.buildClient(); + KeyAsyncClient asyncClient = builder.buildAsyncClient(); + responseNextLink.set(ENDPOINT + "/keys?skip=1"); + assertEquals(2, readPages(client.listPropertiesOfKeys(), asyncClient.listPropertiesOfKeys(), null)); + + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + responseNextLink.set("https://other.example/keys"); + assertThrows(IllegalArgumentException.class, + () -> readPages(client.listPropertiesOfKeys(), asyncClient.listPropertiesOfKeys(), null)); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends + 1, sends.get()); + } + + private void assertRejectedContinuations(PagedIterable sync, PagedFlux async) { + for (String nextLink : Arrays.asList("https://other.example/keys", "https://other.vault.azure.net/keys", + "http://paging.vault.azure.net/keys", ENDPOINT + ":8443/keys", "https://user@paging.vault.azure.net/keys", + ENDPOINT + ":invalid/keys", "/keys")) { + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + int previousAuthorizedSends = authorizedSends.get(); + int previousPolicyCalls = customPolicyCalls.get(); + assertThrows(IllegalArgumentException.class, () -> readPages(sync, async, nextLink), nextLink); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + assertEquals(previousAuthorizedSends, authorizedSends.get()); + assertEquals(previousPolicyCalls, customPolicyCalls.get()); + } + } + + private static int readPages(PagedIterable sync, PagedFlux async, String nextLink) { + AtomicInteger pages = new AtomicInteger(); + SyncAsyncExtension.execute(() -> sync.iterableByPage(nextLink).forEach(page -> pages.incrementAndGet()), + () -> (nextLink == null ? async.byPage() : async.byPage(nextLink)).doOnNext(page -> pages.incrementAndGet()) + .then()); + return pages.get(); + } + + private KeyClientBuilder builder(boolean customPipeline, boolean disableVerification) { + TokenCredential credential = context -> { + tokenRequests.incrementAndGet(); + return Mono.just(new AccessToken("fake-key-vault-token", OffsetDateTime.now().plusHours(1))); + }; + HttpClient httpClient = request -> Mono.fromSupplier(() -> { + sends.incrementAndGet(); + String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); + if (authorization == null) { + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, + "Bearer authorization=\"https://login.example/tenant\", resource=\"https://vault.azure.net\"")); + } + assertEquals("Bearer fake-key-vault-token", authorization); + authorizedSends.incrementAndGet(); + String nextLink = responseNextLink.getAndSet(null); + String body = nextLink == null ? "{\"value\":[]}" : "{\"value\":[],\"nextLink\":\"" + nextLink + "\"}"; + return new MockHttpResponse(request, 200, + new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), + body.getBytes(StandardCharsets.UTF_8)); + }); + KeyClientBuilder builder + = new KeyClientBuilder().vaultUrl(ENDPOINT).credential(credential).httpClient(httpClient); + if (disableVerification) { + builder.disableChallengeResourceVerification(); + } + if (customPipeline) { + builder.pipeline(new HttpPipelineBuilder().httpClient(httpClient).policies((context, next) -> { + customPolicyCalls.incrementAndGet(); + return next.process(); + }, new BearerTokenAuthenticationPolicy(credential, "https://vault.azure.net/.default")).build()); + } + return builder; + } +} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md index 8985d89fc6653..271fbf3032e86 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md @@ -8,6 +8,9 @@ ### Bugs Fixed +- Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. +- Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. + ### Other Changes ## 4.13.1 (2026-11-02) diff --git a/sdk/keyvault/azure-security-keyvault-secrets/customizations/src/main/java/SecretsCustomizations.java b/sdk/keyvault/azure-security-keyvault-secrets/customizations/src/main/java/SecretsCustomizations.java index 5ed0231f4f679..4669571d3fd9f 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/customizations/src/main/java/SecretsCustomizations.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/customizations/src/main/java/SecretsCustomizations.java @@ -9,6 +9,7 @@ import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.EnumDeclaration; import com.github.javaparser.ast.comments.LineComment; +import com.github.javaparser.ast.expr.MethodCallExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.javadoc.Javadoc; import org.slf4j.Logger; @@ -25,6 +26,7 @@ public class SecretsCustomizations extends Customization { public void customize(LibraryCustomization libraryCustomization, Logger logger) { removeFiles(libraryCustomization.getRawEditor()); customizeServiceVersion(libraryCustomization); + customizePaging(libraryCustomization); customizeModuleInfo(libraryCustomization.getRawEditor()); customizePackageInfos(libraryCustomization.getRawEditor()); } @@ -36,6 +38,15 @@ private static void removeFiles(Editor editor) { editor.removeFile("src/main/java/com/azure/security/keyvault/secrets/SecretClientBuilder.java"); } + private static void customizePaging(LibraryCustomization customization) { + customization.getClass("com.azure.security.keyvault.secrets.implementation", "SecretClientImpl") + .customizeAst(ast -> ast.findAll(MethodCallExpr.class).stream() + .filter(call -> call.getScope().map(Object::toString).orElse("").equals("service") + && !call.getArguments().isEmpty() && call.getArgument(0).toString().equals("nextLink")) + .forEach(call -> call.setArgument(0, StaticJavaParser.parseExpression( + "KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl())")))); + } + private static void customizeServiceVersion(LibraryCustomization customization) { CompilationUnit compilationUnit = new CompilationUnit(); compilationUnit.addOrphanComment(new LineComment(" Copyright (c) Microsoft Corporation. All rights reserved.")); diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java index b865e8482922b..b7725fb91f93f 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java @@ -2,6 +2,8 @@ // Licensed under the MIT License. package com.azure.security.keyvault.secrets.implementation; +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.AccessTokenCache; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; import com.azure.core.http.HttpPipelineCallContext; @@ -20,15 +22,18 @@ import java.net.URI; import java.net.URISyntaxException; -import java.net.URL; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import static com.azure.core.http.HttpHeaderName.AUTHORIZATION; import static com.azure.core.http.HttpHeaderName.CONTENT_LENGTH; import static com.azure.core.http.HttpHeaderName.WWW_AUTHENTICATE; @@ -42,9 +47,12 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final ClientLogger LOGGER = new ClientLogger(KeyVaultCredentialPolicy.class); private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; + private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); - private ChallengeParameters challenge; + private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; + private final TokenCredential credential; + private final ConcurrentMap accessTokenCaches = new ConcurrentHashMap<>(); /** * Creates a {@link KeyVaultCredentialPolicy}. @@ -55,6 +63,7 @@ public KeyVaultCredentialPolicy(TokenCredential credential, boolean disableChall super(credential); this.disableChallengeResourceVerification = disableChallengeResourceVerification; + this.credential = credential; } /** @@ -82,17 +91,13 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { return Mono.defer(() -> { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext - = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) - .setCaeEnabled(true); + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) + .setCaeEnabled(true); return setAuthorizationHeader(context, tokenRequestContext); } @@ -130,7 +135,7 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -141,10 +146,11 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return Mono.just(false); } } else { @@ -173,13 +179,14 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -205,15 +212,12 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context public void authorizeRequestSync(HttpPipelineCallContext context) { HttpRequest request = context.getHttpRequest(); - // If this policy doesn't have challenge parameters cached try to get it from the static challenge cache. - if (this.challenge == null) { - this.challenge = CHALLENGE_CACHE.get(getRequestAuthority(request)); - } + ChallengeParameters challenge = getChallenge(context); - if (this.challenge != null) { + if (challenge != null) { // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); setAuthorizationHeaderSync(context, tokenRequestContext); @@ -248,7 +252,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, request.setHeader(CONTENT_LENGTH, (String) contentLengthOptional.get()); } - String authority = getRequestAuthority(request); + String authority = getRequestAuthority(context); Map challengeAttributes = extractChallengeAttributes(response.getHeaderValue(WWW_AUTHENTICATE)); String scope = challengeAttributes.get("resource"); @@ -258,10 +262,11 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, scope = challengeAttributes.get("scope"); } + ChallengeParameters challenge; if (scope == null) { - this.challenge = CHALLENGE_CACHE.get(authority); + challenge = CHALLENGE_CACHE.get(authority); - if (this.challenge == null) { + if (challenge == null) { return false; } } else { @@ -291,13 +296,14 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, String.format("The challenge authorization URI '%s' is invalid.", authorization), e)); } - this.challenge = new ChallengeParameters(authorizationUri, new String[] { scope }); + challenge = new ChallengeParameters(authority, authorizationUri, new String[] { scope }); - CHALLENGE_CACHE.put(authority, this.challenge); + CHALLENGE_CACHE.put(authority, challenge); } + this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(this.challenge.getScopes()) - .setTenantId(this.challenge.getTenantId()) + TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) + .setTenantId(challenge.getTenantId()) .setCaeEnabled(true); String error = challengeAttributes.get("error"); @@ -319,6 +325,28 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, return true; } + @Override + public Mono setAuthorizationHeader(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + return Mono.defer(() -> { + String authority = getRequestAuthority(context); + return getAccessTokenCache(authority, tokenRequestContext).getToken(tokenRequestContext, true) + .flatMap(token -> { + // The request is mutable while asynchronous credential acquisition is in progress. + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + return Mono.empty(); + }); + }); + } + + @Override + public void setAuthorizationHeaderSync(HttpPipelineCallContext context, TokenRequestContext tokenRequestContext) { + String authority = getRequestAuthority(context); + AccessToken token = getAccessTokenCache(authority, tokenRequestContext).getTokenSync(tokenRequestContext, true); + validateRequestAuthority(context, authority); + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + token.getToken()); + } + @Override public Mono process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if (!"https".equals(context.getHttpRequest().getUrl().getProtocol())) { @@ -426,12 +454,48 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { + if (context == null) { + throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); + } + // Keep one current context per origin. A failed refresh must never expose a token from an older context. + return accessTokenCaches.compute(authority, + (ignored, existing) -> existing != null && existing.matches(context) + ? existing + : new TokenCache(credential, context)).cache; + } + + private static final class TokenCache { + private final AccessTokenCache cache; + private final List scopes; + private final String tenantId; + private final String claims; + private final boolean caeEnabled; + + private TokenCache(TokenCredential credential, TokenRequestContext context) { + cache = new AccessTokenCache(credential); + scopes = new ArrayList<>(context.getScopes()); + tenantId = context.getTenantId(); + claims = context.getClaims(); + caeEnabled = context.isCaeEnabled(); + } + + private boolean matches(TokenRequestContext context) { + return scopes.equals(context.getScopes()) + && Objects.equals(tenantId, context.getTenantId()) + && Objects.equals(claims, context.getClaims()) + && caeEnabled == context.isCaeEnabled(); + } + } + private static class ChallengeParameters { + private final String authority; private final URI authorizationUri; private final String tenantId; private final String[] scopes; - ChallengeParameters(URI authorizationUri, String[] scopes) { + ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; this.scopes = scopes; @@ -464,26 +528,41 @@ public static void clearCache() { CHALLENGE_CACHE.clear(); } - /** - * Gets the host name and port of the Key Vault or Managed HSM endpoint. - * - * @param request The {@link HttpRequest} to extract the host name and port from. - * - * @return The host name and port of the Key Vault or Managed HSM endpoint. - */ - private static String getRequestAuthority(HttpRequest request) { - URL url = request.getUrl(); - String authority = url.getAuthority(); - int port = url.getPort(); - - // Append port for complete authority. - if (!authority.contains(":") && port > 0) { - authority = authority + ":" + port; + private ChallengeParameters getChallenge(HttpPipelineCallContext context) { + String authority = getRequestAuthority(context); + // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. + ChallengeParameters cachedChallenge = this.challenge; + if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { + cachedChallenge = CHALLENGE_CACHE.get(authority); + this.challenge = cachedChallenge; } + return cachedChallenge; + } + private static String getRequestAuthority(HttpPipelineCallContext context) { + String authority = (String) context.getData(KEY_VAULT_REQUEST_ORIGIN_KEY).orElse(null); + if (authority == null) { + authority = KeyVaultEndpointValidation.getOrigin(context.getHttpRequest().getUrl().toString()); + context.setData(KEY_VAULT_REQUEST_ORIGIN_KEY, authority); + } + validateRequestAuthority(context, authority); return authority; } + private static void validateRequestAuthority(HttpPipelineCallContext context, String authority) { + HttpRequest request = context.getHttpRequest(); + try { + if (!authority.equals(KeyVaultEndpointValidation.getOrigin(request.getUrl().toString()))) { + throw new IllegalArgumentException( + "The request URL must have the same origin as the original request."); + } + } catch (RuntimeException e) { + // A previous attempt may already have authorized this request before its destination changed. + request.getHeaders().remove(AUTHORIZATION); + throw LOGGER.logExceptionAsError(e); + } + } + private static boolean isChallengeResourceValid(HttpRequest request, String scope) { final URI scopeUri; diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidation.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidation.java new file mode 100644 index 0000000000000..75345d10af2f3 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidation.java @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets.implementation; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Locale; + +/** + * Validates Key Vault continuation destinations independently of the HTTP pipeline. + */ +final class KeyVaultEndpointValidation { + private KeyVaultEndpointValidation() { + } + + static String validateNextLink(String nextLink, String endpoint) { + if (!getOrigin(endpoint).equals(getOrigin(nextLink))) { + throw new IllegalArgumentException( + "The continuation URL must have the same origin as the configured endpoint."); + } + return nextLink; + } + + static String getOrigin(String url) { + final URI uri; + try { + uri = new URI(url).parseServerAuthority(); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid Key Vault URL.", e); + } + + String scheme = uri.getScheme(); + if ((!"https".equalsIgnoreCase(scheme) && !"http".equalsIgnoreCase(scheme)) + || uri.getHost() == null + || uri.getRawUserInfo() != null + || uri.getRawFragment() != null + || uri.getPort() < -1 + || uri.getPort() > 65535) { + throw new IllegalArgumentException("Invalid Key Vault URL."); + } + + int port = uri.getPort() == -1 ? ("https".equalsIgnoreCase(scheme) ? 443 : 80) : uri.getPort(); + return scheme.toLowerCase(Locale.ROOT) + "://" + uri.getHost().toLowerCase(Locale.ROOT) + ":" + port; + } +} diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java index 11c6ddae3a8d1..d71fbc2621c7b 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java @@ -2120,8 +2120,9 @@ private Mono> getSecretsNextSinglePageAsync(String nex RequestOptions requestOptions) { final String accept = "application/json"; return FluxUtil - .withContext( - context -> service.getSecretsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + .withContext(context -> service.getSecretsNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -2166,7 +2167,8 @@ private Mono> getSecretsNextSinglePageAsync(String nex private PagedResponse getSecretsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; Response res - = service.getSecretsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + = service.getSecretsNextSync(KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), + this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } @@ -2211,8 +2213,10 @@ private PagedResponse getSecretsNextSinglePage(String nextLink, Requ private Mono> getSecretVersionsNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getSecretVersionsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + return FluxUtil + .withContext(context -> service.getSecretVersionsNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -2256,8 +2260,9 @@ private Mono> getSecretVersionsNextSinglePageAsync(Str @ServiceMethod(returns = ReturnType.SINGLE) private PagedResponse getSecretVersionsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getSecretVersionsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + Response res = service.getSecretVersionsNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } @@ -2305,8 +2310,10 @@ private PagedResponse getSecretVersionsNextSinglePage(String nextLin private Mono> getDeletedSecretsNextSinglePageAsync(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - return FluxUtil.withContext( - context -> service.getDeletedSecretsNext(nextLink, this.getVaultBaseUrl(), accept, requestOptions, context)) + return FluxUtil + .withContext(context -> service.getDeletedSecretsNext( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, context)) .map(res -> new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null)); } @@ -2353,8 +2360,9 @@ private Mono> getDeletedSecretsNextSinglePageAsync(Str @ServiceMethod(returns = ReturnType.SINGLE) private PagedResponse getDeletedSecretsNextSinglePage(String nextLink, RequestOptions requestOptions) { final String accept = "application/json"; - Response res - = service.getDeletedSecretsNextSync(nextLink, this.getVaultBaseUrl(), accept, requestOptions, Context.NONE); + Response res = service.getDeletedSecretsNextSync( + KeyVaultEndpointValidation.validateNextLink(nextLink, this.getVaultBaseUrl()), this.getVaultBaseUrl(), + accept, requestOptions, Context.NONE); return new PagedResponseBase<>(res.getRequest(), res.getStatusCode(), res.getHeaders(), getValues(res.getValue(), "value"), getNextLink(res.getValue(), "nextLink"), null); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java index bdcba1517425f..f45828b5187fb 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java @@ -14,6 +14,8 @@ import com.azure.core.http.HttpPipelineCallContext; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; +import com.azure.core.http.policy.FixedDelay; +import com.azure.core.http.policy.RetryPolicy; import com.azure.core.test.SyncAsyncExtension; import com.azure.core.test.annotation.SyncAsyncTest; import com.azure.core.test.http.MockHttpResponse; @@ -28,15 +30,19 @@ import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import reactor.core.publisher.Sinks; +import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; @@ -147,6 +153,416 @@ public void cleanup() { KeyVaultCredentialPolicy.clearCache(); } + @SyncAsyncTest + public void failedAcquisitionCannotReuseAnotherOriginsToken() { + for (boolean sameTenant : new boolean[] { false, true }) { + for (boolean sameScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean failAcquisition = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger foreignAuthorizedSends = new AtomicInteger(); + String secondTenant = sameTenant ? "first" : "second"; + String secondScope = sameScope ? "https://vault.azure.net/.default" : "https://azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (failAcquisition.get()) { + assertEquals(secondTenant, context.getTenantId()); + assertEquals(Arrays.asList(secondScope), context.getScopes()); + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + boolean second = request.getUrl().getHost().equals("second.vault.azure.net"); + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono.just(tokenCacheChallenge(request, second ? secondTenant : "first", + second ? secondScope : "https://vault.azure.net/.default", null)); + } + if (second) { + foreignAuthorizedSends.incrementAndGet(); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertEquals(1, tokenRequests.get()); + failAcquisition.set(true); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://second.vault.azure.net")); + assertEquals(0, foreignAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + + failAcquisition.set(false); + sendTokenCacheRequest(pipeline, "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets"); + assertEquals(4, tokenRequests.get(), + "A failed acquisition for another origin must not evict this token."); + } + } + } + + @SyncAsyncTest + public void failedContextChangeCannotReusePreviousToken() { + for (String change : Arrays.asList("tenant", "scope", "claims")) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean changedChallenge = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger staleAuthorizedSends = new AtomicInteger(); + String tenant = "tenant".equals(change) ? "second" : "first"; + String scope = "scope".equals(change) ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + String claims = "claims".equals(change) ? DECODED_CLAIMS : null; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + if (changedChallenge.get()) { + throw new IllegalStateException("Token acquisition failed."); + } + return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (changedChallenge.get() && authorization != null) { + staleAuthorizedSends.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 200)); + } + if ("/changed".equals(request.getUrl().getPath())) { + changedChallenge.set(true); + return Mono.just(tokenCacheChallenge(request, tenant, scope, claims)); + } + return Mono.just(authorization == null + ? tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null) + : new MockHttpResponse(request, 200)); + }) + .build(); + + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net"); + assertThrows(IllegalStateException.class, + () -> sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed")); + assertEquals(0, staleAuthorizedSends.get()); + assertEquals(4, tokenRequests.get()); + } + } + + private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String url) { + HttpRequest request = new HttpRequest(HttpMethod.GET, url); + return SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE)); + } + + @SyncAsyncTest + public void originScopedTokensSupportRetriesAndNormalization() { + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return new AccessToken("first-origin-token", OffsetDateTime.now().plusHours(1)); + } + if (secondTokenRequests.incrementAndGet() == 1) { + throw new IllegalStateException("Transient token acquisition failure."); + } + return new AccessToken("second-origin-token", OffsetDateTime.now().plusHours(1)); + }), false); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String tenant + = request.getUrl().getHost().equalsIgnoreCase("first.vault.azure.net") ? "first" : "second"; + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, tenant, "https://vault.azure.net/.default", null)); + } + assertEquals("Bearer " + tenant + "-origin-token", authorization); + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + for (String url : Arrays.asList("https://first.vault.azure.net", "https://second.vault.azure.net", + "HTTPS://FIRST.VAULT.AZURE.NET:443/secrets", "HTTPS://SECOND.VAULT.AZURE.NET:443/secrets")) { + assertEquals(200, sendTokenCacheRequest(pipeline, url).getStatusCode()); + } + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + } + + @Test + public void concurrentTokenAcquisitionsKeepIndependentCacheState() { + for (boolean sameOrigin : new boolean[] { false, true }) { + Sinks.One firstToken = Sinks.one(); + Sinks.One secondToken = Sinks.one(); + AtomicInteger firstTokenRequests = new AtomicInteger(); + AtomicInteger secondTokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + if ("first".equals(context.getTenantId())) { + firstTokenRequests.incrementAndGet(); + return firstToken.asMono(); + } + if (secondTokenRequests.incrementAndGet() == 1) { + return Mono.error(new IllegalStateException("Transient token acquisition failure.")); + } + return secondToken.asMono(); + }, false); + HttpPipelineCallContext firstContext + = createCallContext(new HttpRequest(HttpMethod.GET, "https://first.vault.azure.net"), Context.NONE); + HttpPipelineCallContext secondContext = createCallContext(new HttpRequest(HttpMethod.GET, + sameOrigin ? "https://first.vault.azure.net" : "https://second.vault.azure.net"), Context.NONE); + TokenRequestContext firstRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("first") + .setCaeEnabled(true); + TokenRequestContext secondRequest = new TokenRequestContext().addScopes("https://vault.azure.net/.default") + .setTenantId("second") + .setCaeEnabled(true); + + StepVerifier.create(Mono.when(policy.setAuthorizationHeader(firstContext, firstRequest), + policy.setAuthorizationHeader(secondContext, secondRequest).retry(1))).then(() -> { + assertEquals(1, firstTokenRequests.get()); + assertEquals(2, secondTokenRequests.get()); + secondToken.tryEmitValue(new AccessToken("second-token", OffsetDateTime.now().plusHours(1))); + firstToken.tryEmitValue(new AccessToken("first-token", OffsetDateTime.now().plusHours(1))); + }).expectComplete().verify(Duration.ofSeconds(5)); + assertEquals("Bearer first-token", firstContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals("Bearer second-token", secondContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + StepVerifier.create(policy.setAuthorizationHeader(secondContext, secondRequest)).verifyComplete(); + assertEquals(2, secondTokenRequests.get()); + } + } + + private static HttpResponse tokenCacheChallenge(HttpRequest request, String tenant, String scope, String claims) { + String challenge = "Bearer authorization=\"https://login.example/" + tenant + "\", scope=\"" + scope + "\""; + if (claims != null) { + challenge += ", error=\"insufficient_claims\", claims=\"" + + Base64Util.encodeToString(claims.getBytes(StandardCharsets.UTF_8)) + "\""; + } + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, challenge)); + } + + @SyncAsyncTest + public void cachedChallengeIsBoundToRequestOrigin() { + AtomicInteger tokenRequests = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false); + SyncAsyncExtension.execute( + () -> policy.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> policy.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + assertEquals(1, tokenRequests.get()); + + for (KeyVaultCredentialPolicy cachedPolicy : Arrays.asList(policy, new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, false))) { + for (String endpoint : Arrays.asList("https://other.vault.azure.net", "https://kvtest.vault.azure.net:8443", + "http://kvtest.vault.azure.net")) { + HttpPipelineCallContext foreignContext + = createCallContext(new HttpRequest(HttpMethod.GET, endpoint), Context.NONE); + int previousTokenRequests = tokenRequests.get(); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(foreignContext), + () -> cachedPolicy.authorizeRequest(foreignContext)); + assertNull(foreignContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals(previousTokenRequests, tokenRequests.get()); + } + + HttpPipelineCallContext normalizedContext = createCallContext( + new HttpRequest(HttpMethod.GET, "HTTPS://KVTEST.VAULT.AZURE.NET:443/secrets"), Context.NONE); + SyncAsyncExtension.execute(() -> cachedPolicy.authorizeRequestSync(normalizedContext), + () -> cachedPolicy.authorizeRequest(normalizedContext)); + assertNotNull(normalizedContext.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + } + } + + @SyncAsyncTest + public void foreignContinuationIsRejectedBeforeFirstRequest() { + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + SecretClientBuilder builder + = new SecretClientBuilder().vaultUrl("https://kvtest.vault.azure.net").credential(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }).httpClient(request -> { + sends.incrementAndGet(); + return Mono.just(new MockHttpResponse(request, 200, + new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), + "{\"value\":[]}".getBytes(StandardCharsets.UTF_8))); + }); + + assertThrows(IllegalArgumentException.class, + () -> SyncAsyncExtension.execute( + () -> builder.buildClient() + .listPropertiesOfSecrets() + .iterableByPage("https://other.vault.azure.net/secrets") + .iterator() + .next(), + () -> builder.buildAsyncClient() + .listPropertiesOfSecrets() + .byPage("https://other.vault.azure.net/secrets") + .next())); + assertEquals(0, tokenRequests.get()); + assertEquals(0, sends.get()); + } + + @SyncAsyncTest + public void interleavedRequestsUseTheirOwnChallenge() { + // Inspect the authorization contexts independently of the single access-token cache. + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(credential, false) { + @Override + public Mono setAuthorizationHeader(HttpPipelineCallContext context, + TokenRequestContext tokenRequestContext) { + return Mono.fromRunnable(() -> setAuthorizationHeaderSync(context, tokenRequestContext)); + } + + @Override + public void setAuthorizationHeaderSync(HttpPipelineCallContext context, + TokenRequestContext tokenRequestContext) { + context.getHttpRequest().setHeader(AUTHORIZATION, "Bearer " + tokenRequestContext.getTenantId()); + } + }; + List contexts = new ArrayList<>(); + for (String tenant : Arrays.asList("first", "second")) { + String endpoint = "https://" + tenant + ".vault.azure.net"; + HttpPipelineCallContext context + = createCallContext(new HttpRequest(HttpMethod.GET, endpoint), Context.NONE); + HttpResponse response = new MockHttpResponse(context.getHttpRequest(), 401, new HttpHeaders().set( + HttpHeaderName.WWW_AUTHENTICATE, + "Bearer authorization=\"https://login.example/" + tenant + "\", resource=\"https://vault.azure.net\"")); + SyncAsyncExtension.execute(() -> policy.authorizeRequestOnChallengeSync(context, response), + () -> policy.authorizeRequestOnChallenge(context, response)); + } + for (int i = 0; i < 20; i++) { + contexts.add(createCallContext( + new HttpRequest(HttpMethod.GET, "https://" + (i % 2 == 0 ? "first" : "second") + ".vault.azure.net"), + Context.NONE)); + } + SyncAsyncExtension.execute(() -> contexts.forEach(policy::authorizeRequestSync), + () -> Flux.fromIterable(contexts) + .flatMap(context -> policy.authorizeRequest(context).subscribeOn(Schedulers.parallel()), 2) + .then()); + for (int i = 0; i < contexts.size(); i++) { + assertEquals("Bearer " + (i % 2 == 0 ? "first" : "second"), + contexts.get(i).getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + } + } + + @SyncAsyncTest + public void requestOriginIsRevalidatedDuringTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean cachedChallenge : new boolean[] { false, true }) { + for (String destination : Arrays.asList("https://other.example/secrets", + "https://other.vault.azure.net/secrets", "https://kvtest.vault.azure.net:8443/secrets", + "http://kvtest.vault.azure.net/secrets", "https://user@kvtest.vault.azure.net/secrets")) { + KeyVaultCredentialPolicy.clearCache(); + if (cachedChallenge) { + KeyVaultCredentialPolicy seed = new KeyVaultCredentialPolicy(credential, false); + SyncAsyncExtension.execute( + () -> seed.authorizeRequestOnChallengeSync(callContext, unauthorizedHttpResponseWithHeader), + () -> seed.authorizeRequestOnChallenge(callContext, unauthorizedHttpResponseWithHeader)); + } + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/secrets"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + TokenCredential mutatingCredential = context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + request.setUrl(destination); + return new AccessToken("fake-token", OffsetDateTime.now().plusHours(1)); + }); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new KeyVaultCredentialPolicy(mutatingCredential, disableVerification)) + .httpClient(ignored -> { + sends.incrementAndGet(); + return Mono.just(request.getHeaders().getValue(AUTHORIZATION) == null + ? unauthorizedHttpResponseWithHeader + : simpleResponse); + }) + .build(); + + assertThrows(IllegalArgumentException.class, + () -> SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(cachedChallenge ? 0 : 1, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + } + } + + @SyncAsyncTest + public void requestOriginIsRevalidatedBeforeCaeTokenAcquisition() { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/secrets"); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger sends = new AtomicInteger(); + HttpPipeline pipeline = new HttpPipelineBuilder().policies(new KeyVaultCredentialPolicy(context -> { + tokenRequests.incrementAndGet(); + return credential.getToken(context); + }, disableVerification)).httpClient(ignored -> { + if (sends.incrementAndGet() == 1) { + return Mono.just(unauthorizedHttpResponseWithHeader); + } + request.setUrl("https://other.vault.azure.net/secrets"); + return Mono.just(unauthorizedHttpResponseWithHeaderAndClaims); + }).build(); + + assertThrows(IllegalArgumentException.class, () -> SyncAsyncExtension + .execute(() -> pipeline.sendSync(request, Context.NONE), () -> pipeline.send(request, Context.NONE))); + assertEquals(1, tokenRequests.get()); + assertEquals(2, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + } + } + + @SyncAsyncTest + public void sameOriginChangeDuringTokenAcquisitionIsAllowed() { + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/secrets"); + AtomicInteger sends = new AtomicInteger(); + HttpPipeline pipeline + = new HttpPipelineBuilder().policies(new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + request.setUrl("HTTPS://KVTEST.VAULT.AZURE.NET:443/secrets?skip=1"); + return new AccessToken("fake-token", OffsetDateTime.now().plusHours(1)); + }), false)).httpClient(ignored -> { + sends.incrementAndGet(); + return Mono.just(request.getHeaders().getValue(AUTHORIZATION) == null + ? unauthorizedHttpResponseWithHeader + : simpleResponse); + }).build(); + + HttpResponse response = SyncAsyncExtension.execute(() -> pipeline.sendSync(request, Context.NONE), + () -> pipeline.send(request, Context.NONE)); + assertEquals(200, response.getStatusCode()); + assertEquals(2, sends.get()); + assertEquals("Bearer fake-token", request.getHeaders().getValue(AUTHORIZATION)); + } + + @SyncAsyncTest + public void requestReplacementDuringTokenAcquisitionIsRejected() { + HttpRequest request = new HttpRequest(HttpMethod.GET, "https://kvtest.vault.azure.net/secrets"); + HttpRequest replacement = new HttpRequest(HttpMethod.GET, "https://other.example/secrets"); + AtomicReference activeContext = new AtomicReference<>(); + AtomicInteger sends = new AtomicInteger(); + HttpPipeline pipeline = new HttpPipelineBuilder().policies((context, next) -> { + activeContext.set(context); + return next.process(); + }, new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + activeContext.get().setHttpRequest(replacement); + return new AccessToken("fake-token", OffsetDateTime.now().plusHours(1)); + }), true)).httpClient(ignored -> { + sends.incrementAndGet(); + return Mono.just(unauthorizedHttpResponseWithHeader); + }).build(); + + assertThrows(IllegalArgumentException.class, () -> SyncAsyncExtension + .execute(() -> pipeline.sendSync(request, Context.NONE), () -> pipeline.send(request, Context.NONE))); + assertEquals(1, sends.get()); + assertNull(request.getHeaders().getValue(AUTHORIZATION)); + assertNull(replacement.getHeaders().getValue(AUTHORIZATION)); + } + @SyncAsyncTest public void onNon401ErrorResponse() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(this.credential, false); diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java new file mode 100644 index 0000000000000..cc6e93fa578a4 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java @@ -0,0 +1,186 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.HttpClient; +import com.azure.core.http.HttpHeaderName; +import com.azure.core.http.HttpHeaders; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.rest.PagedFlux; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.test.SyncAsyncExtension; +import com.azure.core.test.annotation.SyncAsyncTest; +import com.azure.core.test.http.MockHttpResponse; +import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import reactor.core.publisher.Mono; + +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Execution(ExecutionMode.SAME_THREAD) +public class KeyVaultPaginationTest { + private static final String ENDPOINT = "https://paging.vault.azure.net"; + private final AtomicInteger tokenRequests = new AtomicInteger(); + private final AtomicInteger sends = new AtomicInteger(); + private final AtomicInteger authorizedSends = new AtomicInteger(); + private final AtomicInteger customPolicyCalls = new AtomicInteger(); + private final AtomicReference responseNextLink = new AtomicReference<>(); + private final AtomicReference lastRequestUrl = new AtomicReference<>(); + + @AfterEach + public void cleanup() { + KeyVaultCredentialPolicy.clearCache(); + } + + @SyncAsyncTest + public void allContinuationOperationsValidateBeforePipeline() { + for (boolean customPipeline : new boolean[] { false, true }) { + for (boolean disableVerification : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + SecretClientBuilder builder = builder(ENDPOINT, customPipeline, disableVerification); + SecretClient client = builder.buildClient(); + SecretAsyncClient asyncClient = builder.buildAsyncClient(); + List> syncPages = Arrays.asList(client.listPropertiesOfSecrets(), + client.listPropertiesOfSecretVersions("secret"), client.listDeletedSecrets()); + List> asyncPages = Arrays.asList(asyncClient.listPropertiesOfSecrets(), + asyncClient.listPropertiesOfSecretVersions("secret"), asyncClient.listDeletedSecrets()); + + for (int i = 0; i < syncPages.size(); i++) { + PagedIterable sync = syncPages.get(i); + PagedFlux async = asyncPages.get(i); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, null)); + assertRejectedContinuations(sync, async); + assertEquals(1, readPages(sync, async, "HTTPS://PAGING.VAULT.AZURE.NET:443/secrets?skip=1")); + } + + // A new client may reuse the static challenge cache, but must still validate its first continuation. + assertRejectedContinuations(builder.buildClient().listPropertiesOfSecrets(), + builder.buildAsyncClient().listPropertiesOfSecrets()); + } + } + assertTrue(tokenRequests.get() > 0); + assertTrue(authorizedSends.get() > 0); + } + + @SyncAsyncTest + public void serviceProvidedContinuationIsValidated() { + SecretClientBuilder builder = builder(ENDPOINT, false, false); + SecretClient client = builder.buildClient(); + SecretAsyncClient asyncClient = builder.buildAsyncClient(); + responseNextLink.set(ENDPOINT + "/secrets?skip=1"); + assertEquals(2, readPages(client.listPropertiesOfSecrets(), asyncClient.listPropertiesOfSecrets(), null)); + + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + responseNextLink.set("https://other.example/secrets"); + assertThrows(IllegalArgumentException.class, + () -> readPages(client.listPropertiesOfSecrets(), asyncClient.listPropertiesOfSecrets(), null)); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends + 1, sends.get()); + } + + @SyncAsyncTest + public void configuredCloudAndCustomOriginsAreSupported() { + for (String endpoint : Arrays.asList("https://paging.vault.usgovcloudapi.net", "https://paging.vault.azure.cn", + "https://vault.example:8443", "https://localhost:443", "HTTPS://PAGING.VAULT.AZURE.NET:443")) { + SecretClientBuilder builder = builder(endpoint, false, true); + assertEquals(1, readPages(builder.buildClient().listPropertiesOfSecrets(), + builder.buildAsyncClient().listPropertiesOfSecrets(), endpoint + "/secrets?skip=1")); + } + } + + @SyncAsyncTest + public void normalizedContinuationRetainsPathAndQuery() { + SecretClientBuilder builder = builder("HTTPS://PAGING.VAULT.AZURE.NET:443", false, false); + SecretClient client = builder.buildClient(); + SecretAsyncClient asyncClient = builder.buildAsyncClient(); + for (String continuation : Arrays.asList("https://paging.vault.azure.net/secrets?skip=1", + "HTTPS://PAGING.VAULT.AZURE.NET:443/secrets?skip=1")) { + assertEquals(1, + readPages(client.listPropertiesOfSecrets(), asyncClient.listPropertiesOfSecrets(), continuation)); + assertEquals("/secrets", lastRequestUrl.get().getPath()); + assertEquals("skip=1", lastRequestUrl.get().getQuery()); + assertEquals("paging.vault.azure.net", lastRequestUrl.get().getHost().toLowerCase(Locale.ROOT)); + } + } + + private void assertRejectedContinuations(PagedIterable sync, PagedFlux async) { + for (String nextLink : Arrays.asList("https://other.example/secrets", "https://other.vault.azure.net/secrets", + "http://paging.vault.azure.net/secrets", ENDPOINT + ":8443/secrets", + "https://paging.vault.azure.net.other.example/secrets", "https://user@paging.vault.azure.net/secrets", + "https://paging.vault.azure.net@other.example/secrets", ENDPOINT + ":invalid/secrets", + ENDPOINT + ":65536/secrets", ENDPOINT + "/bad path", ENDPOINT + "/secrets#fragment", "/secrets", + "//other.example/secrets")) { + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + int previousAuthorizedSends = authorizedSends.get(); + int previousPolicyCalls = customPolicyCalls.get(); + assertThrows(IllegalArgumentException.class, () -> readPages(sync, async, nextLink), nextLink); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + assertEquals(previousAuthorizedSends, authorizedSends.get()); + assertEquals(previousPolicyCalls, customPolicyCalls.get()); + } + } + + private static int readPages(PagedIterable sync, PagedFlux async, String nextLink) { + AtomicInteger pages = new AtomicInteger(); + SyncAsyncExtension.execute(() -> sync.iterableByPage(nextLink).forEach(page -> pages.incrementAndGet()), + () -> (nextLink == null ? async.byPage() : async.byPage(nextLink)).doOnNext(page -> pages.incrementAndGet()) + .then()); + return pages.get(); + } + + private SecretClientBuilder builder(String endpoint, boolean customPipeline, boolean disableVerification) { + TokenCredential credential = context -> { + tokenRequests.incrementAndGet(); + return Mono.just(new AccessToken("fake-key-vault-token", OffsetDateTime.now().plusHours(1))); + }; + HttpClient httpClient = request -> Mono.fromSupplier(() -> { + lastRequestUrl.set(request.getUrl()); + sends.incrementAndGet(); + String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); + if (authorization == null) { + return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, + "Bearer authorization=\"https://login.example/tenant\", resource=\"https://vault.azure.net\"")); + } + assertEquals("Bearer fake-key-vault-token", authorization); + authorizedSends.incrementAndGet(); + String nextLink = responseNextLink.getAndSet(null); + String body = nextLink == null ? "{\"value\":[]}" : "{\"value\":[],\"nextLink\":\"" + nextLink + "\"}"; + return new MockHttpResponse(request, 200, + new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), + body.getBytes(StandardCharsets.UTF_8)); + }); + SecretClientBuilder builder + = new SecretClientBuilder().vaultUrl(endpoint).credential(credential).httpClient(httpClient); + if (disableVerification) { + builder.disableChallengeResourceVerification(); + } + if (customPipeline) { + builder.pipeline(new HttpPipelineBuilder().httpClient(httpClient).policies((context, next) -> { + customPolicyCalls.incrementAndGet(); + return next.process(); + }, new BearerTokenAuthenticationPolicy(credential, "https://vault.azure.net/.default")).build()); + } + return builder; + } +} From 3a7c8f9f81b3144a1408d50d89b8899b2bb8c20e Mon Sep 17 00:00:00 2001 From: Rohit Singhal Date: Tue, 24 Nov 2026 19:52:40 +0000 Subject: [PATCH 2/2] Preserve Key Vault challenge context and align regression coverage Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../CHANGELOG.md | 3 + .../KeyVaultCredentialPolicy.java | 94 +++--- .../KeyVaultCredentialPolicyTest.java | 67 ++++ .../KeyVaultPaginationTest.java | 107 +++++- .../CHANGELOG.md | 3 + .../implementation/CertificateClientImpl.java | 305 +++++++++--------- .../KeyVaultCredentialPolicy.java | 94 +++--- .../CertificateClientTestBase.java | 8 + .../KeyVaultCredentialPolicyTest.java | 67 ++++ .../certificates/KeyVaultPaginationTest.java | 118 ++++++- .../azure-security-keyvault-keys/CHANGELOG.md | 3 + .../keys/implementation/KeyClientImpl.java | 297 ++++++++--------- .../KeyVaultCredentialPolicy.java | 94 +++--- .../keyvault/keys/KeyClientTestBase.java | 13 + .../keys/KeyVaultCredentialPolicyTest.java | 67 ++++ .../keyvault/keys/KeyVaultPaginationTest.java | 125 ++++++- .../CHANGELOG.md | 3 + .../KeyVaultCredentialPolicy.java | 94 +++--- .../implementation/SecretClientImpl.java | 169 +++++----- .../secrets/KeyVaultCredentialPolicyTest.java | 113 +++++++ .../secrets/KeyVaultPaginationTest.java | 139 +++++++- .../secrets/SecretClientTestBase.java | 10 + .../KeyVaultEndpointValidationTest.java | 62 ++++ 23 files changed, 1449 insertions(+), 606 deletions(-) create mode 100644 sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidationTest.java diff --git a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md index 75d3abcb61386..e594bdb444777 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-administration/CHANGELOG.md @@ -9,7 +9,10 @@ ### Bugs Fixed - Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. + Continuation validation now requires absolute HTTP(S) URIs with ASCII (including punycode) hosts and no user information + or fragment; relative continuations and URL-permissive non-URI forms are no longer accepted. - Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. +- Preserve request-local challenge claims when retrying failed token acquisitions. ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java index 59ac079af3544..5f60bc898cb48 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/main/java/com/azure/security/keyvault/administration/implementation/KeyVaultCredentialPolicy.java @@ -48,6 +48,7 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; + private static final String KEY_VAULT_REQUEST_CHALLENGE_KEY = "KeyVaultCredentialPolicyRequestChallenge"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; @@ -94,12 +95,7 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - return setAuthorizationHeader(context, tokenRequestContext); + return setAuthorizationHeader(context, challenge.toTokenRequestContext()); } // The body is removed from the initial request because Key Vault supports other authentication schemes @@ -185,26 +181,8 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext - .setClaims(new String(Base64Util.decodeString(claims), StandardCharsets.UTF_8)); - } - } - } - - return setAuthorizationHeader(context, tokenRequestContext).then(Mono.just(true)); + return setAuthorizationHeader(context, saveRequestChallenge(context, challenge, challengeAttributes)) + .then(Mono.just(true)); }); } @@ -215,12 +193,7 @@ public void authorizeRequestSync(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, challenge.toTokenRequestContext()); return; } @@ -302,25 +275,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext.setClaims(new String(Base64Util.decodeString(claims))); - } - } - } - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, saveRequestChallenge(context, challenge, challengeAttributes)); return true; } @@ -454,6 +409,23 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private static TokenRequestContext saveRequestChallenge(HttpPipelineCallContext context, + ChallengeParameters challenge, Map attributes) { + String claims = null; + String error = attributes.get("error"); + if (error != null) { + LOGGER.verbose("The challenge response contained an error: {}", error); + if ("insufficient_claims".equalsIgnoreCase(error) && attributes.get("claims") != null) { + claims = new String(Base64Util.decodeString(attributes.get("claims")), StandardCharsets.UTF_8); + } + } + ChallengeParameters requestChallenge + = new ChallengeParameters(challenge.authority, challenge.authorizationUri, challenge.scopes, claims); + // Persist an immutable, request-local snapshot before acquisition, including when acquisition fails. + context.setData(KEY_VAULT_REQUEST_CHALLENGE_KEY, requestChallenge); + return requestChallenge.toTokenRequestContext(); + } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { if (context == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); @@ -493,12 +465,25 @@ private static class ChallengeParameters { private final URI authorizationUri; private final String tenantId; private final String[] scopes; + private final String claims; ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this(authority, authorizationUri, scopes, null); + } + + private ChallengeParameters(String authority, URI authorizationUri, String[] scopes, String claims) { this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; - this.scopes = scopes; + this.scopes = scopes.clone(); + this.claims = claims; + } + + private TokenRequestContext toTokenRequestContext() { + return new TokenRequestContext().addScopes(scopes) + .setTenantId(tenantId) + .setClaims(claims) + .setCaeEnabled(true); } /** @@ -530,6 +515,11 @@ public static void clearCache() { private ChallengeParameters getChallenge(HttpPipelineCallContext context) { String authority = getRequestAuthority(context); + ChallengeParameters requestChallenge + = (ChallengeParameters) context.getData(KEY_VAULT_REQUEST_CHALLENGE_KEY).orElse(null); + if (requestChallenge != null) { + return requestChallenge; + } // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. ChallengeParameters cachedChallenge = this.challenge; if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java index 9babdbda02c3c..41e6b3112f79e 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultCredentialPolicyTest.java @@ -216,6 +216,10 @@ public void failedContextChangeCannotReusePreviousToken() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { tokenRequests.incrementAndGet(); if (changedChallenge.get()) { + assertEquals(tenant, context.getTenantId()); + assertEquals(Arrays.asList(scope), context.getScopes()); + assertEquals(claims, context.getClaims()); + assertTrue(context.isCaeEnabled()); throw new IllegalStateException("Token acquisition failed."); } return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); @@ -331,6 +335,69 @@ private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String () -> pipeline.send(request, Context.NONE)); } + @SyncAsyncTest + public void challengedContextSurvivesFailedAcquisitionAndRetry() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean changeTenantAndScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean challenged = new AtomicBoolean(); + AtomicBoolean independentRequest = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger challengedTokenRequests = new AtomicInteger(); + String tenant = changeTenantAndScope ? "second" : "first"; + String scope = changeTenantAndScope ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + assertEquals(challenged.get() ? tenant : "first", context.getTenantId()); + assertEquals(Arrays.asList(challenged.get() ? scope : "https://vault.azure.net/.default"), + context.getScopes()); + assertTrue(context.isCaeEnabled()); + assertEquals(challenged.get() && !independentRequest.get() ? DECODED_CLAIMS : null, + context.getClaims()); + if (challenged.get() && !independentRequest.get()) { + if (challengedTokenRequests.incrementAndGet() == 1) { + context.getScopes().clear(); + context.setTenantId("credential-mutated").setClaims("mutated").setCaeEnabled(false); + throw new IllegalStateException("Transient challenged token acquisition failure."); + } + return new AccessToken("claims-token", OffsetDateTime.now().plusHours(1)); + } + return new AccessToken("ordinary-token", OffsetDateTime.now().plusHours(1)); + }), disableVerification); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if ("/changed".equals(request.getUrl().getPath())) { + if (challenged.compareAndSet(false, true)) { + assertEquals("Bearer ordinary-token", authorization); + return Mono.just(tokenCacheChallenge(request, tenant, scope, DECODED_CLAIMS)); + } + assertEquals("Bearer claims-token", authorization); + } else if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null)); + } else { + assertEquals("Bearer ordinary-token", authorization); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + assertEquals(200, sendTokenCacheRequest(pipeline, "https://first.vault.azure.net").getStatusCode()); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed").getStatusCode()); + assertEquals(2, challengedTokenRequests.get()); + assertEquals(3, tokenRequests.get()); + + independentRequest.set(true); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/independent").getStatusCode()); + assertEquals(4, tokenRequests.get(), "Claims must not leak into a separate request."); + } + } + } + private static HttpResponse tokenCacheChallenge(HttpRequest request, String tenant, String scope, String claims) { String challenge = "Bearer authorization=\"https://login.example/" + tenant + "\", scope=\"" + scope + "\""; if (claims != null) { diff --git a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java index 2359e41ed8761..b0a5b9b26a477 100644 --- a/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java +++ b/sdk/keyvault/azure-security-keyvault-administration/src/test/java/com/azure/security/keyvault/administration/KeyVaultPaginationTest.java @@ -10,6 +10,8 @@ import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.policy.FixedDelayOptions; +import com.azure.core.http.policy.RetryOptions; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.test.SyncAsyncExtension; @@ -23,6 +25,7 @@ import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.Arrays; import java.util.List; @@ -112,6 +115,97 @@ private void assertRejectedContinuations(PagedIterable sync, PagedFlux asy } } + @SyncAsyncTest + public void validCloudAndCustomChallengesWorkWithVerificationEnabled() { + // DNS routing does not change the logical URL origin. + String[][] endpoints = { + { "https://paging.managedhsm.azure.net", "https://managedhsm.azure.net" }, + { "https://paging.region.managedhsm.azure.net", "https://managedhsm.azure.net" }, + { "https://paging.managedhsm.azure.cn", "https://managedhsm.azure.cn" }, + { "https://paging.managedhsm.usgovcloudapi.net", "https://managedhsm.usgovcloudapi.net" }, + { "https://hsm.arbitrary.example:8443", "https://arbitrary.example" }, + { "HTTPS://HSM.XN--BCHER-KVA.EXAMPLE:443", "https://xn--bcher-kva.example" } }; + for (boolean disableVerification : new boolean[] { false, true }) { + for (String[] endpoint : endpoints) { + KeyVaultCredentialPolicy.clearCache(); + KeyVaultAccessControlClientBuilder builder + = builder(endpoint[0], endpoint[1], false, disableVerification); + assertEquals(1, + readPages(builder.buildClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + builder.buildAsyncClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + endpoint[0] + "/roles?skip=1")); + } + } + } + + @SyncAsyncTest + public void defaultResourceVerificationDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(false); + } + + @SyncAsyncTest + public void verificationOptOutDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(true); + } + + private void assertValidChallengeCannotAuthorizeForeignContinuation(boolean disableVerification) { + KeyVaultAccessControlClientBuilder original = builder(false, disableVerification); + KeyVaultAccessControlClient client = original.buildClient(); + KeyVaultAccessControlAsyncClient asyncClient = original.buildAsyncClient(); + assertEquals(1, readPages(client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), null)); + String otherOrigin = "https://other.managedhsm.azure.net"; + KeyVaultAccessControlClientBuilder other + = builder(otherOrigin, "https://managedhsm.azure.net", false, disableVerification); + assertEquals(1, readPages(other.buildClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + other.buildAsyncClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), null)); + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + assertThrows(IllegalArgumentException.class, + () -> readPages(client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), otherOrigin + "/roles?skip=1")); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + + @SyncAsyncTest + public void verificationOptOutChangesOnlyChallengeResourceValidation() { + String endpoint = "https://hsm.example:8443"; + String resource = "https://managedhsm.azure.net"; + KeyVaultAccessControlClientBuilder verified = builder(endpoint, resource, false, false); + RuntimeException rejected = assertThrows(RuntimeException.class, + () -> readPages(verified.buildClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + verified.buildAsyncClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), endpoint + "/roles")); + assertTrue(rejected.getMessage().contains("challenge resource")); + assertEquals(0, tokenRequests.get()); + assertEquals(1, sends.get()); + + KeyVaultAccessControlClientBuilder optedOut = builder(endpoint, resource, false, true); + KeyVaultAccessControlClient client = optedOut.buildClient(); + KeyVaultAccessControlAsyncClient asyncClient = optedOut.buildAsyncClient(); + assertEquals(1, readPages(client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), endpoint + "/roles")); + assertEquals(1, tokenRequests.get()); + int previousSends = sends.get(); + for (boolean disableVerification : new boolean[] { false, true }) { + String insecureEndpoint = "http://hsm.example:8443"; + KeyVaultAccessControlClientBuilder insecure + = builder(insecureEndpoint, resource, false, disableVerification); + RuntimeException insecureRejected = assertThrows(RuntimeException.class, + () -> readPages(insecure.buildClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + insecure.buildAsyncClient().listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + insecureEndpoint + "/roles")); + assertTrue(insecureRejected.getMessage().contains("HTTPS")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + assertThrows(IllegalArgumentException.class, + () -> readPages(client.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), + asyncClient.listRoleDefinitions(KeyVaultRoleScope.GLOBAL), "https://other.example:8443/roles")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + private static int readPages(PagedIterable sync, PagedFlux async, String nextLink) { AtomicInteger pages = new AtomicInteger(); SyncAsyncExtension.execute(() -> sync.iterableByPage(nextLink).forEach(page -> pages.incrementAndGet()), @@ -121,6 +215,11 @@ private static int readPages(PagedIterable sync, PagedFlux async, String n } private KeyVaultAccessControlClientBuilder builder(boolean customPipeline, boolean disableVerification) { + return builder(ENDPOINT, "https://managedhsm.azure.net", customPipeline, disableVerification); + } + + private KeyVaultAccessControlClientBuilder builder(String endpoint, String resource, boolean customPipeline, + boolean disableVerification) { TokenCredential credential = context -> { tokenRequests.incrementAndGet(); return Mono.just(new AccessToken("fake-key-vault-token", OffsetDateTime.now().plusHours(1))); @@ -130,7 +229,7 @@ private KeyVaultAccessControlClientBuilder builder(boolean customPipeline, boole String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); if (authorization == null) { return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, - "Bearer authorization=\"https://login.example/tenant\", resource=\"https://managedhsm.azure.net\"")); + "Bearer authorization=\"https://login.example/tenant\", resource=\"" + resource + "\"")); } assertEquals("Bearer fake-key-vault-token", authorization); authorizedSends.incrementAndGet(); @@ -140,8 +239,10 @@ private KeyVaultAccessControlClientBuilder builder(boolean customPipeline, boole new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), body.getBytes(StandardCharsets.UTF_8)); }); - KeyVaultAccessControlClientBuilder builder - = new KeyVaultAccessControlClientBuilder().vaultUrl(ENDPOINT).credential(credential).httpClient(httpClient); + KeyVaultAccessControlClientBuilder builder = new KeyVaultAccessControlClientBuilder().vaultUrl(endpoint) + .credential(credential) + .httpClient(httpClient) + .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))); if (disableVerification) { builder.disableChallengeResourceVerification(); } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md index 09c9608dbd473..cfc6907376dac 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md @@ -9,7 +9,10 @@ ### Bugs Fixed - Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. + Continuation validation now requires absolute HTTP(S) URIs with ASCII (including punycode) hosts and no user information + or fragment; relative continuations and URL-permissive non-URI forms are no longer accepted. - Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. +- Preserve request-local challenge claims when retrying failed token acquisitions. ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java index 82ca5d816f05e..1cc94a52e24fb 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/CertificateClientImpl.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) TypeSpec Code Generator. - package com.azure.security.keyvault.certificates.implementation; import com.azure.core.annotation.BodyParam; @@ -50,6 +49,7 @@ * Initializes a new instance of the CertificateClient type. */ public final class CertificateClientImpl { + /** * The proxy service used to perform REST calls. */ @@ -61,7 +61,7 @@ public final class CertificateClientImpl { /** * Gets. - * + * * @return the vaultBaseUrl value. */ public String getVaultBaseUrl() { @@ -75,7 +75,7 @@ public String getVaultBaseUrl() { /** * Gets Service version. - * + * * @return the serviceVersion value. */ public CertificateServiceVersion getServiceVersion() { @@ -89,7 +89,7 @@ public CertificateServiceVersion getServiceVersion() { /** * Gets The HTTP pipeline to send requests through. - * + * * @return the httpPipeline value. */ public HttpPipeline getHttpPipeline() { @@ -103,7 +103,7 @@ public HttpPipeline getHttpPipeline() { /** * Gets The serializer to serialize an object into a string. - * + * * @return the serializerAdapter value. */ public SerializerAdapter getSerializerAdapter() { @@ -112,7 +112,7 @@ public SerializerAdapter getSerializerAdapter() { /** * Initializes an instance of CertificateClient client. - * + * * @param vaultBaseUrl * @param serviceVersion Service version. */ @@ -123,7 +123,7 @@ public CertificateClientImpl(String vaultBaseUrl, CertificateServiceVersion serv /** * Initializes an instance of CertificateClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. * @param vaultBaseUrl * @param serviceVersion Service version. @@ -135,7 +135,7 @@ public CertificateClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl, /** * Initializes an instance of CertificateClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. * @param serializerAdapter The serializer to serialize an object into a string. * @param vaultBaseUrl @@ -157,6 +157,7 @@ public CertificateClientImpl(HttpPipeline httpPipeline, SerializerAdapter serial @Host("{vaultBaseUrl}") @ServiceInterface(name = "CertificateClient") public interface CertificateClientService { + @Get("/certificates") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) @@ -814,7 +815,7 @@ Response getDeletedCertificatesNextSync( /** * List certificates in a specified key vault - * + * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -849,7 +850,7 @@ Response getDeletedCertificatesNextSync( * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -869,7 +870,7 @@ private Mono> getCertificatesSinglePageAsync(RequestOp /** * List certificates in a specified key vault - * + * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -904,7 +905,7 @@ private Mono> getCertificatesSinglePageAsync(RequestOp * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -923,7 +924,7 @@ public PagedFlux getCertificatesAsync(RequestOptions requestOptions) /** * List certificates in a specified key vault - * + * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -958,7 +959,7 @@ public PagedFlux getCertificatesAsync(RequestOptions requestOptions) * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -977,7 +978,7 @@ private PagedResponse getCertificatesSinglePage(RequestOptions reque /** * List certificates in a specified key vault - * + * * The GetCertificates operation returns the set of certificates resources in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -1012,7 +1013,7 @@ private PagedResponse getCertificatesSinglePage(RequestOptions reque * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1031,7 +1032,7 @@ public PagedIterable getCertificates(RequestOptions requestOptions) /** * Deletes a certificate from a specified key vault. - * + * * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used * to remove individual versions of a certificate object. This operation requires the certificates/delete * permission. @@ -1128,7 +1129,7 @@ public PagedIterable getCertificates(RequestOptions requestOptions) * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1148,7 +1149,7 @@ public Mono> deleteCertificateWithResponseAsync(String cert /** * Deletes a certificate from a specified key vault. - * + * * Deletes all versions of a certificate object along with its associated policy. Delete certificate cannot be used * to remove individual versions of a certificate object. This operation requires the certificates/delete * permission. @@ -1245,7 +1246,7 @@ public Mono> deleteCertificateWithResponseAsync(String cert * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1264,7 +1265,7 @@ public Response deleteCertificateWithResponse(String certificateName /** * Sets the certificate contacts for the specified key vault. - * + * * Sets the certificate contacts for the specified key vault. This operation requires the * certificates/managecontacts permission. *

Request Body Schema

@@ -1300,7 +1301,7 @@ public Response deleteCertificateWithResponse(String certificateName * } * } * - * + * * @param contacts The contacts for the key vault certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1321,7 +1322,7 @@ public Mono> setCertificateContactsWithResponseAsync(Binary /** * Sets the certificate contacts for the specified key vault. - * + * * Sets the certificate contacts for the specified key vault. This operation requires the * certificates/managecontacts permission. *

Request Body Schema

@@ -1357,7 +1358,7 @@ public Mono> setCertificateContactsWithResponseAsync(Binary * } * } * - * + * * @param contacts The contacts for the key vault certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1376,7 +1377,7 @@ public Response setCertificateContactsWithResponse(BinaryData contac /** * Lists the certificate contacts for a specified key vault. - * + * * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. * This operation requires the certificates/managecontacts permission. *

Response Body Schema

@@ -1395,7 +1396,7 @@ public Response setCertificateContactsWithResponse(BinaryData contac * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1413,7 +1414,7 @@ public Mono> getCertificateContactsWithResponseAsync(Reques /** * Lists the certificate contacts for a specified key vault. - * + * * The GetCertificateContacts operation returns the set of certificate contact resources in the specified key vault. * This operation requires the certificates/managecontacts permission. *

Response Body Schema

@@ -1432,7 +1433,7 @@ public Mono> getCertificateContactsWithResponseAsync(Reques * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1449,7 +1450,7 @@ public Response getCertificateContactsWithResponse(RequestOptions re /** * Deletes the certificate contacts for a specified key vault. - * + * * Deletes the certificate contacts for a specified key vault certificate. This operation requires the * certificates/managecontacts permission. *

Response Body Schema

@@ -1468,7 +1469,7 @@ public Response getCertificateContactsWithResponse(RequestOptions re * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1486,7 +1487,7 @@ public Mono> deleteCertificateContactsWithResponseAsync(Req /** * Deletes the certificate contacts for a specified key vault. - * + * * Deletes the certificate contacts for a specified key vault certificate. This operation requires the * certificates/managecontacts permission. *

Response Body Schema

@@ -1505,7 +1506,7 @@ public Mono> deleteCertificateContactsWithResponseAsync(Req * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1522,7 +1523,7 @@ public Response deleteCertificateContactsWithResponse(RequestOptions /** * List certificate issuers for a specified key vault. - * + * * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. * This operation requires the certificates/manageissuers/getissuers permission. *

Query Parameters

@@ -1543,7 +1544,7 @@ public Response deleteCertificateContactsWithResponse(RequestOptions * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1564,7 +1565,7 @@ private Mono> getCertificateIssuersSinglePageAsync(Req /** * List certificate issuers for a specified key vault. - * + * * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. * This operation requires the certificates/manageissuers/getissuers permission. *

Query Parameters

@@ -1585,7 +1586,7 @@ private Mono> getCertificateIssuersSinglePageAsync(Req * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1604,7 +1605,7 @@ public PagedFlux getCertificateIssuersAsync(RequestOptions requestOp /** * List certificate issuers for a specified key vault. - * + * * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. * This operation requires the certificates/manageissuers/getissuers permission. *

Query Parameters

@@ -1625,7 +1626,7 @@ public PagedFlux getCertificateIssuersAsync(RequestOptions requestOp * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1644,7 +1645,7 @@ private PagedResponse getCertificateIssuersSinglePage(RequestOptions /** * List certificate issuers for a specified key vault. - * + * * The GetCertificateIssuers operation returns the set of certificate issuer resources in the specified key vault. * This operation requires the certificates/manageissuers/getissuers permission. *

Query Parameters

@@ -1665,7 +1666,7 @@ private PagedResponse getCertificateIssuersSinglePage(RequestOptions * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1684,7 +1685,7 @@ public PagedIterable getCertificateIssuers(RequestOptions requestOpt /** * Sets the specified certificate issuer. - * + * * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the * certificates/setissuers permission. *

Request Body Schema

@@ -1747,7 +1748,7 @@ public PagedIterable getCertificateIssuers(RequestOptions requestOpt * } * } * - * + * * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. * @param parameter Certificate issuer set parameter. @@ -1771,7 +1772,7 @@ public Mono> setCertificateIssuerWithResponseAsync(String i /** * Sets the specified certificate issuer. - * + * * The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the * certificates/setissuers permission. *

Request Body Schema

@@ -1834,7 +1835,7 @@ public Mono> setCertificateIssuerWithResponseAsync(String i * } * } * - * + * * @param issuerName The name of the issuer. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. * @param parameter Certificate issuer set parameter. @@ -1856,7 +1857,7 @@ public Response setCertificateIssuerWithResponse(String issuerName, /** * Updates the specified certificate issuer. - * + * * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This * operation requires the certificates/setissuers permission. *

Request Body Schema

@@ -1919,7 +1920,7 @@ public Response setCertificateIssuerWithResponse(String issuerName, * } * } * - * + * * @param issuerName The name of the issuer. * @param parameter Certificate issuer update parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -1942,7 +1943,7 @@ public Mono> updateCertificateIssuerWithResponseAsync(Strin /** * Updates the specified certificate issuer. - * + * * The UpdateCertificateIssuer operation performs an update on the specified certificate issuer entity. This * operation requires the certificates/setissuers permission. *

Request Body Schema

@@ -2005,7 +2006,7 @@ public Mono> updateCertificateIssuerWithResponseAsync(Strin * } * } * - * + * * @param issuerName The name of the issuer. * @param parameter Certificate issuer update parameter. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -2026,7 +2027,7 @@ public Response updateCertificateIssuerWithResponse(String issuerNam /** * Lists the specified certificate issuer. - * + * * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. * This operation requires the certificates/manageissuers/getissuers permission. *

Response Body Schema

@@ -2059,7 +2060,7 @@ public Response updateCertificateIssuerWithResponse(String issuerNam * } * } * - * + * * @param issuerName The name of the issuer. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2079,7 +2080,7 @@ public Mono> getCertificateIssuerWithResponseAsync(String i /** * Lists the specified certificate issuer. - * + * * The GetCertificateIssuer operation returns the specified certificate issuer resources in the specified key vault. * This operation requires the certificates/manageissuers/getissuers permission. *

Response Body Schema

@@ -2112,7 +2113,7 @@ public Mono> getCertificateIssuerWithResponseAsync(String i * } * } * - * + * * @param issuerName The name of the issuer. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2130,7 +2131,7 @@ public Response getCertificateIssuerWithResponse(String issuerName, /** * Deletes the specified certificate issuer. - * + * * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This * operation requires the certificates/manageissuers/deleteissuers permission. *

Response Body Schema

@@ -2163,7 +2164,7 @@ public Response getCertificateIssuerWithResponse(String issuerName, * } * } * - * + * * @param issuerName The name of the issuer. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2183,7 +2184,7 @@ public Mono> deleteCertificateIssuerWithResponseAsync(Strin /** * Deletes the specified certificate issuer. - * + * * The DeleteCertificateIssuer operation permanently removes the specified certificate issuer from the vault. This * operation requires the certificates/manageissuers/deleteissuers permission. *

Response Body Schema

@@ -2216,7 +2217,7 @@ public Mono> deleteCertificateIssuerWithResponseAsync(Strin * } * } * - * + * * @param issuerName The name of the issuer. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2234,7 +2235,7 @@ public Response deleteCertificateIssuerWithResponse(String issuerNam /** * Creates a new certificate. - * + * * If this is the first version, the certificate resource is created. This operation requires the * certificates/create permission. *

Request Body Schema

@@ -2348,7 +2349,7 @@ public Response deleteCertificateIssuerWithResponse(String issuerNam * } * } * - * + * * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose * of running the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters to create a certificate. @@ -2372,7 +2373,7 @@ public Mono> createCertificateWithResponseAsync(String cert /** * Creates a new certificate. - * + * * If this is the first version, the certificate resource is created. This operation requires the * certificates/create permission. *

Request Body Schema

@@ -2486,7 +2487,7 @@ public Mono> createCertificateWithResponseAsync(String cert * } * } * - * + * * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose * of running the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters to create a certificate. @@ -2508,7 +2509,7 @@ public Response createCertificateWithResponse(String certificateName /** * Imports a certificate into a specified key vault. - * + * * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only @@ -2690,7 +2691,7 @@ public Response createCertificateWithResponse(String certificateName * } * } * - * + * * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose * of running the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters to import the certificate. @@ -2714,7 +2715,7 @@ public Mono> importCertificateWithResponseAsync(String cert /** * Imports a certificate into a specified key vault. - * + * * Imports an existing valid certificate, containing a private key, into Azure Key Vault. This operation requires * the certificates/import permission. The certificate to be imported can be in either PFX or PEM format. If the * certificate is in PEM format the PEM file must contain the key as well as x509 certificates. Key Vault will only @@ -2896,7 +2897,7 @@ public Mono> importCertificateWithResponseAsync(String cert * } * } * - * + * * @param certificateName The name of the certificate. The value you provide may be copied globally for the purpose * of running the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters to import the certificate. @@ -2918,7 +2919,7 @@ public Response importCertificateWithResponse(String certificateName /** * List the versions of a certificate. - * + * * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -2951,7 +2952,7 @@ public Response importCertificateWithResponse(String certificateName * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2973,7 +2974,7 @@ private Mono> getCertificateVersionsSinglePageAsync(St /** * List the versions of a certificate. - * + * * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -3006,7 +3007,7 @@ private Mono> getCertificateVersionsSinglePageAsync(St * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -3026,7 +3027,7 @@ public PagedFlux getCertificateVersionsAsync(String certificateName, /** * List the versions of a certificate. - * + * * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -3059,7 +3060,7 @@ public PagedFlux getCertificateVersionsAsync(String certificateName, * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -3080,7 +3081,7 @@ private PagedResponse getCertificateVersionsSinglePage(String certif /** * List the versions of a certificate. - * + * * The GetCertificateVersions operation returns the versions of a certificate in the specified key vault. This * operation requires the certificates/list permission. *

Query Parameters

@@ -3113,7 +3114,7 @@ private PagedResponse getCertificateVersionsSinglePage(String certif * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -3133,7 +3134,7 @@ public PagedIterable getCertificateVersions(String certificateName, /** * Lists the policy for a certificate. - * + * * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. * This operation requires the certificates/get permission. *

Response Body Schema

@@ -3213,7 +3214,7 @@ public PagedIterable getCertificateVersions(String certificateName, * } * } * - * + * * @param certificateName The name of the certificate in a given key vault. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -3232,7 +3233,7 @@ public Mono> getCertificatePolicyWithResponseAsync(String c /** * Lists the policy for a certificate. - * + * * The GetCertificatePolicy operation returns the specified certificate policy resources in the specified key vault. * This operation requires the certificates/get permission. *

Response Body Schema

@@ -3312,7 +3313,7 @@ public Mono> getCertificatePolicyWithResponseAsync(String c * } * } * - * + * * @param certificateName The name of the certificate in a given key vault. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -3331,7 +3332,7 @@ public Response getCertificatePolicyWithResponse(String certificateN /** * Updates the policy for a certificate. - * + * * Set specified members in the certificate policy. Leave others as null. This operation requires the * certificates/update permission. *

Request Body Schema

@@ -3489,7 +3490,7 @@ public Response getCertificatePolicyWithResponse(String certificateN * } * } * - * + * * @param certificateName The name of the certificate in the given vault. * @param certificatePolicy The policy for the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -3511,7 +3512,7 @@ public Mono> updateCertificatePolicyWithResponseAsync(Strin /** * Updates the policy for a certificate. - * + * * Set specified members in the certificate policy. Leave others as null. This operation requires the * certificates/update permission. *

Request Body Schema

@@ -3669,7 +3670,7 @@ public Mono> updateCertificatePolicyWithResponseAsync(Strin * } * } * - * + * * @param certificateName The name of the certificate in the given vault. * @param certificatePolicy The policy for the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -3690,7 +3691,7 @@ public Response updateCertificatePolicyWithResponse(String certifica /** * Updates the specified attributes associated with the given certificate. - * + * * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated * are the certificate's attributes. This operation requires the certificates/update permission. *

Request Body Schema

@@ -3867,7 +3868,7 @@ public Response updateCertificatePolicyWithResponse(String certifica * } * } * - * + * * @param certificateName The name of the certificate in the given key vault. * @param certificateVersion The version of the certificate. * @param parameters The parameters for certificate update. @@ -3891,7 +3892,7 @@ public Mono> updateCertificateWithResponseAsync(String cert /** * Updates the specified attributes associated with the given certificate. - * + * * The UpdateCertificate operation applies the specified update on the given certificate; the only elements updated * are the certificate's attributes. This operation requires the certificates/update permission. *

Request Body Schema

@@ -4068,7 +4069,7 @@ public Mono> updateCertificateWithResponseAsync(String cert * } * } * - * + * * @param certificateName The name of the certificate in the given key vault. * @param certificateVersion The version of the certificate. * @param parameters The parameters for certificate update. @@ -4090,7 +4091,7 @@ public Response updateCertificateWithResponse(String certificateName /** * Gets information about a certificate. - * + * * Gets information about a specific certificate. This operation requires the certificates/get permission. *

Response Body Schema

* @@ -4182,7 +4183,7 @@ public Response updateCertificateWithResponse(String certificateName * } * } * - * + * * @param certificateName The name of the certificate in the given vault. * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the * latest version of the certificate is returned. @@ -4192,7 +4193,7 @@ public Response updateCertificateWithResponse(String certificateName * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return information about a certificate. - * + * * Gets information about a specific certificate along with {@link Response} on successful completion of * {@link Mono}. */ @@ -4207,7 +4208,7 @@ public Mono> getCertificateWithResponseAsync(String certifi /** * Gets information about a certificate. - * + * * Gets information about a specific certificate. This operation requires the certificates/get permission. *

Response Body Schema

* @@ -4299,7 +4300,7 @@ public Mono> getCertificateWithResponseAsync(String certifi * } * } * - * + * * @param certificateName The name of the certificate in the given vault. * @param certificateVersion The version of the certificate. This URI fragment is optional. If not specified, the * latest version of the certificate is returned. @@ -4309,7 +4310,7 @@ public Mono> getCertificateWithResponseAsync(String certifi * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return information about a certificate. - * + * * Gets information about a specific certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) @@ -4322,7 +4323,7 @@ public Response getCertificateWithResponse(String certificateName, S /** * Updates a certificate operation. - * + * * Updates a certificate creation operation that is already in progress. This operation requires the * certificates/update permission. *

Request Body Schema

@@ -4361,7 +4362,7 @@ public Response getCertificateWithResponse(String certificateName, S * } * } * - * + * * @param certificateName The name of the certificate. * @param certificateOperation The certificate operation response. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -4384,7 +4385,7 @@ public Mono> updateCertificateOperationWithResponseAsync(St /** * Updates a certificate operation. - * + * * Updates a certificate creation operation that is already in progress. This operation requires the * certificates/update permission. *

Request Body Schema

@@ -4423,7 +4424,7 @@ public Mono> updateCertificateOperationWithResponseAsync(St * } * } * - * + * * @param certificateName The name of the certificate. * @param certificateOperation The certificate operation response. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -4444,7 +4445,7 @@ public Response updateCertificateOperationWithResponse(String certif /** * Gets the creation operation of a certificate. - * + * * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get * permission. *

Response Body Schema

@@ -4473,7 +4474,7 @@ public Response updateCertificateOperationWithResponse(String certif * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4481,7 +4482,7 @@ public Response updateCertificateOperationWithResponse(String certif * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the creation operation of a certificate. - * + * * Gets the creation operation associated with a specified certificate along with {@link Response} on successful * completion of {@link Mono}. */ @@ -4495,7 +4496,7 @@ public Mono> getCertificateOperationWithResponseAsync(Strin /** * Gets the creation operation of a certificate. - * + * * Gets the creation operation associated with a specified certificate. This operation requires the certificates/get * permission. *

Response Body Schema

@@ -4524,7 +4525,7 @@ public Mono> getCertificateOperationWithResponseAsync(Strin * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4532,7 +4533,7 @@ public Mono> getCertificateOperationWithResponseAsync(Strin * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the creation operation of a certificate. - * + * * Gets the creation operation associated with a specified certificate along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) @@ -4545,7 +4546,7 @@ public Response getCertificateOperationWithResponse(String certifica /** * Deletes the creation operation for a specific certificate. - * + * * Deletes the creation operation for a specified certificate that is in the process of being created. The * certificate is no longer created. This operation requires the certificates/update permission. *

Response Body Schema

@@ -4574,7 +4575,7 @@ public Response getCertificateOperationWithResponse(String certifica * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4594,7 +4595,7 @@ public Mono> deleteCertificateOperationWithResponseAsync(St /** * Deletes the creation operation for a specific certificate. - * + * * Deletes the creation operation for a specified certificate that is in the process of being created. The * certificate is no longer created. This operation requires the certificates/update permission. *

Response Body Schema

@@ -4623,7 +4624,7 @@ public Mono> deleteCertificateOperationWithResponseAsync(St * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4642,7 +4643,7 @@ public Response deleteCertificateOperationWithResponse(String certif /** * Merges a certificate or a certificate chain with a key pair existing on the server. - * + * * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair * currently available in the service. This operation requires the certificates/create permission. *

Request Body Schema

@@ -4759,7 +4760,7 @@ public Response deleteCertificateOperationWithResponse(String certif * } * } * - * + * * @param certificateName The name of the certificate. * @param parameters The parameters to merge certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -4782,7 +4783,7 @@ public Mono> mergeCertificateWithResponseAsync(String certi /** * Merges a certificate or a certificate chain with a key pair existing on the server. - * + * * The MergeCertificate operation performs the merging of a certificate or certificate chain with a key pair * currently available in the service. This operation requires the certificates/create permission. *

Request Body Schema

@@ -4899,7 +4900,7 @@ public Mono> mergeCertificateWithResponseAsync(String certi * } * } * - * + * * @param certificateName The name of the certificate. * @param parameters The parameters to merge certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -4920,7 +4921,7 @@ public Response mergeCertificateWithResponse(String certificateName, /** * Backs up the specified certificate. - * + * * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate * will be downloaded. This operation requires the certificates/backup permission. *

Response Body Schema

@@ -4932,7 +4933,7 @@ public Response mergeCertificateWithResponse(String certificateName, * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4952,7 +4953,7 @@ public Mono> backupCertificateWithResponseAsync(String cert /** * Backs up the specified certificate. - * + * * Requests that a backup of the specified certificate be downloaded to the client. All versions of the certificate * will be downloaded. This operation requires the certificates/backup permission. *

Response Body Schema

@@ -4964,7 +4965,7 @@ public Mono> backupCertificateWithResponseAsync(String cert * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4982,7 +4983,7 @@ public Response backupCertificateWithResponse(String certificateName /** * Restores a backed up certificate to a vault. - * + * * Restores a backed up certificate, and all its versions, to a vault. This operation requires the * certificates/restore permission. *

Request Body Schema

@@ -5085,7 +5086,7 @@ public Response backupCertificateWithResponse(String certificateName * } * } * - * + * * @param parameters The parameters to restore the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5106,7 +5107,7 @@ public Mono> restoreCertificateWithResponseAsync(BinaryData /** * Restores a backed up certificate to a vault. - * + * * Restores a backed up certificate, and all its versions, to a vault. This operation requires the * certificates/restore permission. *

Request Body Schema

@@ -5209,7 +5210,7 @@ public Mono> restoreCertificateWithResponseAsync(BinaryData * } * } * - * + * * @param parameters The parameters to restore the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5228,7 +5229,7 @@ public Response restoreCertificateWithResponse(BinaryData parameters /** * Lists the deleted certificates in the specified vault currently available for recovery. - * + * * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. @@ -5267,7 +5268,7 @@ public Response restoreCertificateWithResponse(BinaryData parameters * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -5288,7 +5289,7 @@ private Mono> getDeletedCertificatesSinglePageAsync(Re /** * Lists the deleted certificates in the specified vault currently available for recovery. - * + * * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. @@ -5327,7 +5328,7 @@ private Mono> getDeletedCertificatesSinglePageAsync(Re * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -5346,7 +5347,7 @@ public PagedFlux getDeletedCertificatesAsync(RequestOptions requestO /** * Lists the deleted certificates in the specified vault currently available for recovery. - * + * * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. @@ -5385,7 +5386,7 @@ public PagedFlux getDeletedCertificatesAsync(RequestOptions requestO * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -5404,7 +5405,7 @@ private PagedResponse getDeletedCertificatesSinglePage(RequestOption /** * Lists the deleted certificates in the specified vault currently available for recovery. - * + * * The GetDeletedCertificates operation retrieves the certificates in the current vault which are in a deleted state * and ready for recovery or purging. This operation includes deletion-specific information. This operation requires * the certificates/get/list permission. This operation can only be enabled on soft-delete enabled vaults. @@ -5443,7 +5444,7 @@ private PagedResponse getDeletedCertificatesSinglePage(RequestOption * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -5463,7 +5464,7 @@ public PagedIterable getDeletedCertificates(RequestOptions requestOp /** * Retrieves information about the specified deleted certificate. - * + * * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires * the certificates/get permission. @@ -5560,7 +5561,7 @@ public PagedIterable getDeletedCertificates(RequestOptions requestOp * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5580,7 +5581,7 @@ public Mono> getDeletedCertificateWithResponseAsync(String /** * Retrieves information about the specified deleted certificate. - * + * * The GetDeletedCertificate operation retrieves the deleted certificate information plus its attributes, such as * retention interval, scheduled permanent deletion and the current deletion recovery level. This operation requires * the certificates/get permission. @@ -5677,7 +5678,7 @@ public Mono> getDeletedCertificateWithResponseAsync(String * } * } * - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5697,11 +5698,11 @@ public Response getDeletedCertificateWithResponse(String certificate /** * Permanently deletes the specified deleted certificate. - * + * * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This * operation requires the certificate/purge permission. - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5719,11 +5720,11 @@ public Mono> purgeDeletedCertificateWithResponseAsync(String cert /** * Permanently deletes the specified deleted certificate. - * + * * The PurgeDeletedCertificate operation performs an irreversible deletion of the specified certificate, without * possibility for recovery. The operation is not available if the recovery level does not specify 'Purgeable'. This * operation requires the certificate/purge permission. - * + * * @param certificateName The name of the certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5740,7 +5741,7 @@ public Response purgeDeletedCertificateWithResponse(String certificateName /** * Recovers the deleted certificate back to its current version under /certificates. - * + * * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the * deleted certificate's attributes). This operation requires the certificates/recover permission. @@ -5834,7 +5835,7 @@ public Response purgeDeletedCertificateWithResponse(String certificateName * } * } * - * + * * @param certificateName The name of the deleted certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5854,7 +5855,7 @@ public Mono> recoverDeletedCertificateWithResponseAsync(Str /** * Recovers the deleted certificate back to its current version under /certificates. - * + * * The RecoverDeletedCertificate operation performs the reversal of the Delete operation. The operation is * applicable in vaults enabled for soft-delete, and must be issued during the retention interval (available in the * deleted certificate's attributes). This operation requires the certificates/recover permission. @@ -5948,7 +5949,7 @@ public Mono> recoverDeletedCertificateWithResponseAsync(Str * } * } * - * + * * @param certificateName The name of the deleted certificate. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5967,7 +5968,7 @@ public Response recoverDeletedCertificateWithResponse(String certifi /** * List certificates in a specified key vault - * + * * Get the next page of items. *

Response Body Schema

* @@ -5991,7 +5992,7 @@ public Response recoverDeletedCertificateWithResponse(String certifi * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -6014,7 +6015,7 @@ private Mono> getCertificatesNextSinglePageAsync(Strin /** * List certificates in a specified key vault - * + * * Get the next page of items. *

Response Body Schema

* @@ -6038,7 +6039,7 @@ private Mono> getCertificatesNextSinglePageAsync(Strin * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -6059,7 +6060,7 @@ private PagedResponse getCertificatesNextSinglePage(String nextLink, /** * List certificate issuers for a specified key vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -6071,7 +6072,7 @@ private PagedResponse getCertificatesNextSinglePage(String nextLink, * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -6095,7 +6096,7 @@ private Mono> getCertificateIssuersNextSinglePageAsync /** * List certificate issuers for a specified key vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -6107,7 +6108,7 @@ private Mono> getCertificateIssuersNextSinglePageAsync * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -6129,7 +6130,7 @@ private PagedResponse getCertificateIssuersNextSinglePage(String nex /** * List the versions of a certificate. - * + * * Get the next page of items. *

Response Body Schema

* @@ -6153,7 +6154,7 @@ private PagedResponse getCertificateIssuersNextSinglePage(String nex * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -6176,7 +6177,7 @@ private Mono> getCertificateVersionsNextSinglePageAsyn /** * List the versions of a certificate. - * + * * Get the next page of items. *

Response Body Schema

* @@ -6200,7 +6201,7 @@ private Mono> getCertificateVersionsNextSinglePageAsyn * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -6222,7 +6223,7 @@ private PagedResponse getCertificateVersionsNextSinglePage(String ne /** * Lists the deleted certificates in the specified vault currently available for recovery. - * + * * Get the next page of items. *

Response Body Schema

* @@ -6249,7 +6250,7 @@ private PagedResponse getCertificateVersionsNextSinglePage(String ne * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -6273,7 +6274,7 @@ private Mono> getDeletedCertificatesNextSinglePageAsyn /** * Lists the deleted certificates in the specified vault currently available for recovery. - * + * * Get the next page of items. *

Response Body Schema

* @@ -6300,7 +6301,7 @@ private Mono> getDeletedCertificatesNextSinglePageAsyn * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java index ca7725b3ab39a..8c346456962f0 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/main/java/com/azure/security/keyvault/certificates/implementation/KeyVaultCredentialPolicy.java @@ -48,6 +48,7 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; + private static final String KEY_VAULT_REQUEST_CHALLENGE_KEY = "KeyVaultCredentialPolicyRequestChallenge"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; @@ -94,12 +95,7 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - return setAuthorizationHeader(context, tokenRequestContext); + return setAuthorizationHeader(context, challenge.toTokenRequestContext()); } // The body is removed from the initial request because Key Vault supports other authentication schemes @@ -185,26 +181,8 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext - .setClaims(new String(Base64Util.decodeString(claims), StandardCharsets.UTF_8)); - } - } - } - - return setAuthorizationHeader(context, tokenRequestContext).then(Mono.just(true)); + return setAuthorizationHeader(context, saveRequestChallenge(context, challenge, challengeAttributes)) + .then(Mono.just(true)); }); } @@ -215,12 +193,7 @@ public void authorizeRequestSync(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, challenge.toTokenRequestContext()); return; } @@ -302,25 +275,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext.setClaims(new String(Base64Util.decodeString(claims))); - } - } - } - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, saveRequestChallenge(context, challenge, challengeAttributes)); return true; } @@ -454,6 +409,23 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private static TokenRequestContext saveRequestChallenge(HttpPipelineCallContext context, + ChallengeParameters challenge, Map attributes) { + String claims = null; + String error = attributes.get("error"); + if (error != null) { + LOGGER.verbose("The challenge response contained an error: {}", error); + if ("insufficient_claims".equalsIgnoreCase(error) && attributes.get("claims") != null) { + claims = new String(Base64Util.decodeString(attributes.get("claims")), StandardCharsets.UTF_8); + } + } + ChallengeParameters requestChallenge + = new ChallengeParameters(challenge.authority, challenge.authorizationUri, challenge.scopes, claims); + // Persist an immutable, request-local snapshot before acquisition, including when acquisition fails. + context.setData(KEY_VAULT_REQUEST_CHALLENGE_KEY, requestChallenge); + return requestChallenge.toTokenRequestContext(); + } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { if (context == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); @@ -493,12 +465,25 @@ private static class ChallengeParameters { private final URI authorizationUri; private final String tenantId; private final String[] scopes; + private final String claims; ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this(authority, authorizationUri, scopes, null); + } + + private ChallengeParameters(String authority, URI authorizationUri, String[] scopes, String claims) { this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; - this.scopes = scopes; + this.scopes = scopes.clone(); + this.claims = claims; + } + + private TokenRequestContext toTokenRequestContext() { + return new TokenRequestContext().addScopes(scopes) + .setTenantId(tenantId) + .setClaims(claims) + .setCaeEnabled(true); } /** @@ -530,6 +515,11 @@ public static void clearCache() { private ChallengeParameters getChallenge(HttpPipelineCallContext context) { String authority = getRequestAuthority(context); + ChallengeParameters requestChallenge + = (ChallengeParameters) context.getData(KEY_VAULT_REQUEST_CHALLENGE_KEY).orElse(null); + if (requestChallenge != null) { + return requestChallenge; + } // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. ChallengeParameters cachedChallenge = this.challenge; if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTestBase.java b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTestBase.java index da3676e687a1d..dcd8f9e117a33 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTestBase.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/CertificateClientTestBase.java @@ -46,6 +46,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.net.URI; import java.nio.file.Files; import java.nio.file.Paths; import java.security.KeyFactory; @@ -130,6 +131,7 @@ CertificateClientBuilder getCertificateClientBuilder(HttpClient httpClient, Stri } if (interceptorManager.isPlaybackMode()) { + interceptorManager.addSanitizers(Collections.singletonList(playbackNextLinkSanitizer(endpoint))); return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); @@ -140,6 +142,12 @@ CertificateClientBuilder getCertificateClientBuilder(HttpClient httpClient, Stri } } + static TestProxySanitizer playbackNextLinkSanitizer(String endpoint) { + // Only the origin used in the pinned recordings is translated; retain the complete path and query. + return new TestProxySanitizer("$.nextLink", "(?i)^https://REDACTED(?::443)?/", + URI.create(endpoint).resolve("/").toString(), TestProxySanitizerType.BODY_KEY); + } + @Test public abstract void createCertificate(HttpClient httpClient, CertificateServiceVersion serviceVersion); diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java index ab2b560140762..051752dba7cac 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultCredentialPolicyTest.java @@ -216,6 +216,10 @@ public void failedContextChangeCannotReusePreviousToken() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { tokenRequests.incrementAndGet(); if (changedChallenge.get()) { + assertEquals(tenant, context.getTenantId()); + assertEquals(Arrays.asList(scope), context.getScopes()); + assertEquals(claims, context.getClaims()); + assertTrue(context.isCaeEnabled()); throw new IllegalStateException("Token acquisition failed."); } return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); @@ -331,6 +335,69 @@ private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String () -> pipeline.send(request, Context.NONE)); } + @SyncAsyncTest + public void challengedContextSurvivesFailedAcquisitionAndRetry() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean changeTenantAndScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean challenged = new AtomicBoolean(); + AtomicBoolean independentRequest = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger challengedTokenRequests = new AtomicInteger(); + String tenant = changeTenantAndScope ? "second" : "first"; + String scope = changeTenantAndScope ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + assertEquals(challenged.get() ? tenant : "first", context.getTenantId()); + assertEquals(Arrays.asList(challenged.get() ? scope : "https://vault.azure.net/.default"), + context.getScopes()); + assertTrue(context.isCaeEnabled()); + assertEquals(challenged.get() && !independentRequest.get() ? DECODED_CLAIMS : null, + context.getClaims()); + if (challenged.get() && !independentRequest.get()) { + if (challengedTokenRequests.incrementAndGet() == 1) { + context.getScopes().clear(); + context.setTenantId("credential-mutated").setClaims("mutated").setCaeEnabled(false); + throw new IllegalStateException("Transient challenged token acquisition failure."); + } + return new AccessToken("claims-token", OffsetDateTime.now().plusHours(1)); + } + return new AccessToken("ordinary-token", OffsetDateTime.now().plusHours(1)); + }), disableVerification); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if ("/changed".equals(request.getUrl().getPath())) { + if (challenged.compareAndSet(false, true)) { + assertEquals("Bearer ordinary-token", authorization); + return Mono.just(tokenCacheChallenge(request, tenant, scope, DECODED_CLAIMS)); + } + assertEquals("Bearer claims-token", authorization); + } else if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null)); + } else { + assertEquals("Bearer ordinary-token", authorization); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + assertEquals(200, sendTokenCacheRequest(pipeline, "https://first.vault.azure.net").getStatusCode()); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed").getStatusCode()); + assertEquals(2, challengedTokenRequests.get()); + assertEquals(3, tokenRequests.get()); + + independentRequest.set(true); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/independent").getStatusCode()); + assertEquals(4, tokenRequests.get(), "Claims must not leak into a separate request."); + } + } + } + private static HttpResponse tokenCacheChallenge(HttpRequest request, String tenant, String scope, String claims) { String challenge = "Bearer authorization=\"https://login.example/" + tenant + "\", scope=\"" + scope + "\""; if (claims != null) { diff --git a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java index 73755ba4c0dd6..c81301cb9529d 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java +++ b/sdk/keyvault/azure-security-keyvault-certificates/src/test/java/com/azure/security/keyvault/certificates/KeyVaultPaginationTest.java @@ -10,23 +10,29 @@ import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.policy.FixedDelayOptions; +import com.azure.core.http.policy.RetryOptions; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.test.SyncAsyncExtension; import com.azure.core.test.annotation.SyncAsyncTest; import com.azure.core.test.http.MockHttpResponse; +import com.azure.core.test.models.TestProxySanitizer; import com.azure.security.keyvault.certificates.implementation.KeyVaultCredentialPolicy; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -46,6 +52,23 @@ public void cleanup() { KeyVaultCredentialPolicy.clearCache(); } + @Test + public void playbackSanitizerOnlyRewritesRecordedOrigin() { + TestProxySanitizer sanitizer + = CertificateClientTestBase.playbackNextLinkSanitizer("https://localhost:8080/base"); + Pattern pattern = Pattern.compile(sanitizer.getRegex()); + String suffix = "certificates/name%2Fpart?api-version=7.6&skiptoken=a%2Bb%3D"; + for (String origin : Arrays.asList("https://REDACTED:443/", "HTTPS://redacted/")) { + assertEquals("https://localhost:8080/" + suffix, + pattern.matcher(origin + suffix).replaceFirst(sanitizer.getRedactedValue())); + } + for (String origin : Arrays.asList("https://other.example/", "http://REDACTED/", "https://REDACTED:8443/", + "https://REDACTED.other.example/", "https://user@REDACTED/", "https://REDACTED@other.example/")) { + assertEquals(origin + suffix, pattern.matcher(origin + suffix).replaceFirst(sanitizer.getRedactedValue())); + } + assertEquals("$.nextLink", sanitizer.getKey()); + } + @SyncAsyncTest public void allContinuationOperationsValidateBeforePipeline() { for (boolean customPipeline : new boolean[] { false, true }) { @@ -113,6 +136,88 @@ private void assertRejectedContinuations(PagedIterable sync, PagedFlux asy } } + @SyncAsyncTest + public void validCloudAndCustomChallengesWorkWithVerificationEnabled() { + String[][] endpoints = { + { "https://paging.vault.azure.net", "https://vault.azure.net" }, + { "https://paging.vault.azure.cn", "https://vault.azure.cn" }, + { "https://paging.vault.usgovcloudapi.net", "https://vault.usgovcloudapi.net" }, + { "https://certificates.arbitrary.example:8443", "https://arbitrary.example" }, + { "HTTPS://CERTIFICATES.XN--BCHER-KVA.EXAMPLE:443", "https://xn--bcher-kva.example" }, + { "https://certificates.custom.example.:8443", "https://custom.example." } }; + for (boolean disableVerification : new boolean[] { false, true }) { + for (String[] endpoint : endpoints) { + KeyVaultCredentialPolicy.clearCache(); + CertificateClientBuilder builder = builder(endpoint[0], endpoint[1], false, disableVerification); + assertEquals(1, readPages(builder.buildClient().listPropertiesOfCertificates(), + builder.buildAsyncClient().listPropertiesOfCertificates(), endpoint[0] + "/certificates?skip=1")); + } + } + } + + @SyncAsyncTest + public void defaultResourceVerificationDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(false); + } + + @SyncAsyncTest + public void verificationOptOutDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(true); + } + + private void assertValidChallengeCannotAuthorizeForeignContinuation(boolean disableVerification) { + CertificateClientBuilder original = builder(false, disableVerification); + CertificateClient client = original.buildClient(); + CertificateAsyncClient asyncClient = original.buildAsyncClient(); + assertEquals(1, + readPages(client.listPropertiesOfCertificates(), asyncClient.listPropertiesOfCertificates(), null)); + String otherOrigin = "https://other.vault.azure.net"; + CertificateClientBuilder other = builder(otherOrigin, "https://vault.azure.net", false, disableVerification); + assertEquals(1, readPages(other.buildClient().listPropertiesOfCertificates(), + other.buildAsyncClient().listPropertiesOfCertificates(), null)); + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + assertThrows(IllegalArgumentException.class, () -> readPages(client.listPropertiesOfCertificates(), + asyncClient.listPropertiesOfCertificates(), otherOrigin + "/certificates?skip=1")); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + + @SyncAsyncTest + public void verificationOptOutChangesOnlyChallengeResourceValidation() { + String endpoint = "https://certificates.example:8443"; + String resource = "https://vault.azure.net"; + CertificateClientBuilder verified = builder(endpoint, resource, false, false); + RuntimeException rejected = assertThrows(RuntimeException.class, + () -> readPages(verified.buildClient().listPropertiesOfCertificates(), + verified.buildAsyncClient().listPropertiesOfCertificates(), endpoint + "/certificates")); + assertTrue(rejected.getMessage().contains("challenge resource")); + assertEquals(0, tokenRequests.get()); + assertEquals(1, sends.get()); + + CertificateClientBuilder optedOut = builder(endpoint, resource, false, true); + CertificateClient client = optedOut.buildClient(); + CertificateAsyncClient asyncClient = optedOut.buildAsyncClient(); + assertEquals(1, readPages(client.listPropertiesOfCertificates(), asyncClient.listPropertiesOfCertificates(), + endpoint + "/certificates")); + assertEquals(1, tokenRequests.get()); + int previousSends = sends.get(); + for (boolean disableVerification : new boolean[] { false, true }) { + String insecureEndpoint = "http://certificates.example:8443"; + CertificateClientBuilder insecure = builder(insecureEndpoint, resource, false, disableVerification); + RuntimeException insecureRejected = assertThrows(RuntimeException.class, + () -> readPages(insecure.buildClient().listPropertiesOfCertificates(), + insecure.buildAsyncClient().listPropertiesOfCertificates(), insecureEndpoint + "/certificates")); + assertTrue(insecureRejected.getMessage().contains("HTTPS")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + assertThrows(IllegalArgumentException.class, () -> readPages(client.listPropertiesOfCertificates(), + asyncClient.listPropertiesOfCertificates(), "https://other.example:8443/certificates")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + private static int readPages(PagedIterable sync, PagedFlux async, String nextLink) { AtomicInteger pages = new AtomicInteger(); SyncAsyncExtension.execute(() -> sync.iterableByPage(nextLink).forEach(page -> pages.incrementAndGet()), @@ -122,6 +227,11 @@ private static int readPages(PagedIterable sync, PagedFlux async, String n } private CertificateClientBuilder builder(boolean customPipeline, boolean disableVerification) { + return builder(ENDPOINT, "https://vault.azure.net", customPipeline, disableVerification); + } + + private CertificateClientBuilder builder(String endpoint, String resource, boolean customPipeline, + boolean disableVerification) { TokenCredential credential = context -> { tokenRequests.incrementAndGet(); return Mono.just(new AccessToken("fake-key-vault-token", OffsetDateTime.now().plusHours(1))); @@ -131,7 +241,7 @@ private CertificateClientBuilder builder(boolean customPipeline, boolean disable String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); if (authorization == null) { return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, - "Bearer authorization=\"https://login.example/tenant\", resource=\"https://vault.azure.net\"")); + "Bearer authorization=\"https://login.example/tenant\", resource=\"" + resource + "\"")); } assertEquals("Bearer fake-key-vault-token", authorization); authorizedSends.incrementAndGet(); @@ -141,8 +251,10 @@ private CertificateClientBuilder builder(boolean customPipeline, boolean disable new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), body.getBytes(StandardCharsets.UTF_8)); }); - CertificateClientBuilder builder - = new CertificateClientBuilder().vaultUrl(ENDPOINT).credential(credential).httpClient(httpClient); + CertificateClientBuilder builder = new CertificateClientBuilder().vaultUrl(endpoint) + .credential(credential) + .httpClient(httpClient) + .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))); if (disableVerification) { builder.disableChallengeResourceVerification(); } diff --git a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md index 21783704538bf..91552c60a414e 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md @@ -9,7 +9,10 @@ ### Bugs Fixed - Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. + Continuation validation now requires absolute HTTP(S) URIs with ASCII (including punycode) hosts and no user information + or fragment; relative continuations and URL-permissive non-URI forms are no longer accepted. - Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. +- Preserve request-local challenge claims when retrying failed token acquisitions. ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java index 7f331ace0925b..814cd12c616c8 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyClientImpl.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) TypeSpec Code Generator. - package com.azure.security.keyvault.keys.implementation; import com.azure.core.annotation.BodyParam; @@ -50,6 +49,7 @@ * Initializes a new instance of the KeyClient type. */ public final class KeyClientImpl { + /** * The proxy service used to perform REST calls. */ @@ -61,7 +61,7 @@ public final class KeyClientImpl { /** * Gets. - * + * * @return the vaultBaseUrl value. */ public String getVaultBaseUrl() { @@ -75,7 +75,7 @@ public String getVaultBaseUrl() { /** * Gets Service version. - * + * * @return the serviceVersion value. */ public KeyServiceVersion getServiceVersion() { @@ -89,7 +89,7 @@ public KeyServiceVersion getServiceVersion() { /** * Gets The HTTP pipeline to send requests through. - * + * * @return the httpPipeline value. */ public HttpPipeline getHttpPipeline() { @@ -103,7 +103,7 @@ public HttpPipeline getHttpPipeline() { /** * Gets The serializer to serialize an object into a string. - * + * * @return the serializerAdapter value. */ public SerializerAdapter getSerializerAdapter() { @@ -112,7 +112,7 @@ public SerializerAdapter getSerializerAdapter() { /** * Initializes an instance of KeyClient client. - * + * * @param vaultBaseUrl * @param serviceVersion Service version. */ @@ -123,7 +123,7 @@ public KeyClientImpl(String vaultBaseUrl, KeyServiceVersion serviceVersion) { /** * Initializes an instance of KeyClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. * @param vaultBaseUrl * @param serviceVersion Service version. @@ -134,7 +134,7 @@ public KeyClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl, KeyServiceV /** * Initializes an instance of KeyClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. * @param serializerAdapter The serializer to serialize an object into a string. * @param vaultBaseUrl @@ -155,6 +155,7 @@ public KeyClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerAdap @Host("{vaultBaseUrl}") @ServiceInterface(name = "KeyClient") public interface KeyClientService { + @Post("/keys/{key-name}/create") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) @@ -814,7 +815,7 @@ Response getDeletedKeysNextSync(@PathParam(value = "nextLink", encod /** * Creates a new key, stores it, then returns key parameters and attributes to the client. - * + * * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, * Azure Key Vault creates a new version of the key. It requires the keys/create permission. *

Request Body Schema

@@ -920,7 +921,7 @@ Response getDeletedKeysNextSync(@PathParam(value = "nextLink", encod * } * } * - * + * * @param keyName The name for the new key. The system will generate the version name for the new key. The value you * provide may be copied globally for the purpose of running the service. The value provided should not include * personally identifiable or sensitive information. @@ -944,7 +945,7 @@ public Mono> createKeyWithResponseAsync(String keyName, Bin /** * Creates a new key, stores it, then returns key parameters and attributes to the client. - * + * * The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, * Azure Key Vault creates a new version of the key. It requires the keys/create permission. *

Request Body Schema

@@ -1050,7 +1051,7 @@ public Mono> createKeyWithResponseAsync(String keyName, Bin * } * } * - * + * * @param keyName The name for the new key. The system will generate the version name for the new key. The value you * provide may be copied globally for the purpose of running the service. The value provided should not include * personally identifiable or sensitive information. @@ -1073,7 +1074,7 @@ public Response createKeyWithResponse(String keyName, BinaryData par /** * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * + * * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. *

Response Body Schema

* @@ -1133,7 +1134,7 @@ public Response createKeyWithResponse(String keyName, BinaryData par * } * } * - * + * * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1152,7 +1153,7 @@ public Mono> rotateKeyWithResponseAsync(String keyName, Req /** * Creates a new key version, stores it, then returns key parameters, attributes and policy to the client. - * + * * The operation will rotate the key based on the key policy. It requires the keys/rotate permission. *

Response Body Schema

* @@ -1212,7 +1213,7 @@ public Mono> rotateKeyWithResponseAsync(String keyName, Req * } * } * - * + * * @param keyName The name of key to be rotated. The system will generate a new version in the specified key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1230,7 +1231,7 @@ public Response rotateKeyWithResponse(String keyName, RequestOptions /** * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * + * * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. *

Request Body Schema

@@ -1350,7 +1351,7 @@ public Response rotateKeyWithResponse(String keyName, RequestOptions * } * } * - * + * * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters to import a key. @@ -1373,7 +1374,7 @@ public Mono> importKeyWithResponseAsync(String keyName, Bin /** * Imports an externally created key, stores it, and returns key parameters and attributes to the client. - * + * * The import key operation may be used to import any key type into an Azure Key Vault. If the named key already * exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. *

Request Body Schema

@@ -1493,7 +1494,7 @@ public Mono> importKeyWithResponseAsync(String keyName, Bin * } * } * - * + * * @param keyName Name for the imported key. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters to import a key. @@ -1515,7 +1516,7 @@ public Response importKeyWithResponse(String keyName, BinaryData par /** * Deletes a key of any type from storage in Azure Key Vault. - * + * * The delete key operation cannot be used to remove individual versions of a key. This operation removes the * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or * Encrypt/Decrypt operations. This operation requires the keys/delete permission. @@ -1580,7 +1581,7 @@ public Response importKeyWithResponse(String keyName, BinaryData par * } * } * - * + * * @param keyName The name of the key to delete. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1599,7 +1600,7 @@ public Mono> deleteKeyWithResponseAsync(String keyName, Req /** * Deletes a key of any type from storage in Azure Key Vault. - * + * * The delete key operation cannot be used to remove individual versions of a key. This operation removes the * cryptographic material associated with the key, which means the key is not usable for Sign/Verify, Wrap/Unwrap or * Encrypt/Decrypt operations. This operation requires the keys/delete permission. @@ -1664,7 +1665,7 @@ public Mono> deleteKeyWithResponseAsync(String keyName, Req * } * } * - * + * * @param keyName The name of the key to delete. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1684,7 +1685,7 @@ public Response deleteKeyWithResponse(String keyName, RequestOptions /** * The update key operation changes specified attributes of a stored key and can be applied to any key type and key * version stored in Azure Key Vault. - * + * * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material * of a key itself cannot be changed. This operation requires the keys/update permission. *

Request Body Schema

@@ -1786,7 +1787,7 @@ public Response deleteKeyWithResponse(String keyName, RequestOptions * } * } * - * + * * @param keyName The name of key to update. * @param keyVersion The version of the key to update. * @param parameters The parameters of the key to update. @@ -1811,7 +1812,7 @@ public Mono> updateKeyWithResponseAsync(String keyName, Str /** * The update key operation changes specified attributes of a stored key and can be applied to any key type and key * version stored in Azure Key Vault. - * + * * In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material * of a key itself cannot be changed. This operation requires the keys/update permission. *

Request Body Schema

@@ -1913,7 +1914,7 @@ public Mono> updateKeyWithResponseAsync(String keyName, Str * } * } * - * + * * @param keyName The name of key to update. * @param keyVersion The version of the key to update. * @param parameters The parameters of the key to update. @@ -1935,7 +1936,7 @@ public Response updateKeyWithResponse(String keyName, String keyVers /** * Gets the public part of a stored key. - * + * * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is * released in the response. This operation requires the keys/get permission. *

Response Body Schema

@@ -1996,7 +1997,7 @@ public Response updateKeyWithResponse(String keyName, String keyVers * } * } * - * + * * @param keyName The name of the key to get. * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is * optional. If not specified, the latest version of the key is returned. @@ -2006,7 +2007,7 @@ public Response updateKeyWithResponse(String keyName, String keyVers * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the public part of a stored key. - * + * * The get key operation is applicable to all key types along with {@link Response} on successful completion of * {@link Mono}. */ @@ -2020,7 +2021,7 @@ public Mono> getKeyWithResponseAsync(String keyName, String /** * Gets the public part of a stored key. - * + * * The get key operation is applicable to all key types. If the requested key is symmetric, then no key material is * released in the response. This operation requires the keys/get permission. *

Response Body Schema

@@ -2081,7 +2082,7 @@ public Mono> getKeyWithResponseAsync(String keyName, String * } * } * - * + * * @param keyName The name of the key to get. * @param keyVersion Adding the version parameter retrieves a specific version of a key. This URI fragment is * optional. If not specified, the latest version of the key is returned. @@ -2091,7 +2092,7 @@ public Mono> getKeyWithResponseAsync(String keyName, String * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the public part of a stored key. - * + * * The get key operation is applicable to all key types along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) @@ -2103,7 +2104,7 @@ public Response getKeyWithResponse(String keyName, String keyVersion /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. *

Query Parameters

@@ -2148,7 +2149,7 @@ public Response getKeyWithResponse(String keyName, String keyVersion * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2170,7 +2171,7 @@ private Mono> getKeyVersionsSinglePageAsync(String key /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. *

Query Parameters

@@ -2215,7 +2216,7 @@ private Mono> getKeyVersionsSinglePageAsync(String key * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2235,7 +2236,7 @@ public PagedFlux getKeyVersionsAsync(String keyName, RequestOptions /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. *

Query Parameters

@@ -2280,7 +2281,7 @@ public PagedFlux getKeyVersionsAsync(String keyName, RequestOptions * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2300,7 +2301,7 @@ private PagedResponse getKeyVersionsSinglePage(String keyName, Reque /** * Retrieves a list of individual key versions with the same key name. - * + * * The full key identifier, attributes, and tags are provided in the response. This operation requires the keys/list * permission. *

Query Parameters

@@ -2345,7 +2346,7 @@ private PagedResponse getKeyVersionsSinglePage(String keyName, Reque * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2365,7 +2366,7 @@ public PagedIterable getKeyVersions(String keyName, RequestOptions r /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation @@ -2412,7 +2413,7 @@ public PagedIterable getKeyVersions(String keyName, RequestOptions r * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -2432,7 +2433,7 @@ private Mono> getKeysSinglePageAsync(RequestOptions re /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation @@ -2479,7 +2480,7 @@ private Mono> getKeysSinglePageAsync(RequestOptions re * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -2498,7 +2499,7 @@ public PagedFlux getKeysAsync(RequestOptions requestOptions) { /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation @@ -2545,7 +2546,7 @@ public PagedFlux getKeysAsync(RequestOptions requestOptions) { * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -2564,7 +2565,7 @@ private PagedResponse getKeysSinglePage(RequestOptions requestOption /** * List keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a stored * key. The LIST operation is applicable to all key types, however only the base key identifier, attributes, and * tags are provided in the response. Individual versions of a key are not listed in the response. This operation @@ -2611,7 +2612,7 @@ private PagedResponse getKeysSinglePage(RequestOptions requestOption * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -2630,7 +2631,7 @@ public PagedIterable getKeys(RequestOptions requestOptions) { /** * Requests that a backup of the specified key be downloaded to the client. - * + * * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to @@ -2649,7 +2650,7 @@ public PagedIterable getKeys(RequestOptions requestOptions) { * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2668,7 +2669,7 @@ public Mono> backupKeyWithResponseAsync(String keyName, Req /** * Requests that a backup of the specified key be downloaded to the client. - * + * * The Key Backup operation exports a key from Azure Key Vault in a protected form. Note that this operation does * NOT return key material in a form that can be used outside the Azure Key Vault system, the returned key material * is either protected to a Azure Key Vault HSM or to Azure Key Vault itself. The intent of this operation is to @@ -2687,7 +2688,7 @@ public Mono> backupKeyWithResponseAsync(String keyName, Req * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2705,7 +2706,7 @@ public Response backupKeyWithResponse(String keyName, RequestOptions /** * Restores a backed up key to a vault. - * + * * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when @@ -2783,7 +2784,7 @@ public Response backupKeyWithResponse(String keyName, RequestOptions * } * } * - * + * * @param parameters The parameters to restore the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2804,7 +2805,7 @@ public Mono> restoreKeyWithResponseAsync(BinaryData paramet /** * Restores a backed up key to a vault. - * + * * Imports a previously backed up key into Azure Key Vault, restoring the key, its key identifier, attributes and * access control policies. The RESTORE operation may be used to import a previously backed up key. Individual * versions of a key cannot be restored. The key is restored in its entirety with the same key name as it had when @@ -2882,7 +2883,7 @@ public Mono> restoreKeyWithResponseAsync(BinaryData paramet * } * } * - * + * * @param parameters The parameters to restore the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2901,7 +2902,7 @@ public Response restoreKeyWithResponse(BinaryData parameters, Reques /** * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * + * * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for @@ -2936,7 +2937,7 @@ public Response restoreKeyWithResponse(BinaryData parameters, Reques * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the encryption operation. @@ -2959,7 +2960,7 @@ public Mono> encryptWithResponseAsync(String keyName, Strin /** * Encrypts an arbitrary sequence of bytes using an encryption key that is stored in a key vault. - * + * * The ENCRYPT operation encrypts an arbitrary sequence of bytes using an encryption key that is stored in Azure Key * Vault. Note that the ENCRYPT operation only supports a single block of data, the size of which is dependent on * the target key and the encryption algorithm to be used. The ENCRYPT operation is only strictly necessary for @@ -2994,7 +2995,7 @@ public Mono> encryptWithResponseAsync(String keyName, Strin * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the encryption operation. @@ -3016,7 +3017,7 @@ public Response encryptWithResponse(String keyName, String keyVersio /** * Decrypts a single block of encrypted data. - * + * * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies @@ -3051,7 +3052,7 @@ public Response encryptWithResponse(String keyName, String keyVersio * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the decryption operation. @@ -3074,7 +3075,7 @@ public Mono> decryptWithResponseAsync(String keyName, Strin /** * Decrypts a single block of encrypted data. - * + * * The DECRYPT operation decrypts a well-formed block of ciphertext using the target encryption key and specified * algorithm. This operation is the reverse of the ENCRYPT operation; only a single block of data may be decrypted, * the size of this block is dependent on the target key and the algorithm to be used. The DECRYPT operation applies @@ -3109,7 +3110,7 @@ public Mono> decryptWithResponseAsync(String keyName, Strin * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the decryption operation. @@ -3131,7 +3132,7 @@ public Response decryptWithResponse(String keyName, String keyVersio /** * Creates a signature from a digest using the specified key. - * + * * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation * uses the private portion of the key. This operation requires the keys/sign permission. *

Request Body Schema

@@ -3158,7 +3159,7 @@ public Response decryptWithResponse(String keyName, String keyVersio * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the signing operation. @@ -3181,7 +3182,7 @@ public Mono> signWithResponseAsync(String keyName, String k /** * Creates a signature from a digest using the specified key. - * + * * The SIGN operation is applicable to asymmetric and symmetric keys stored in Azure Key Vault since this operation * uses the private portion of the key. This operation requires the keys/sign permission. *

Request Body Schema

@@ -3208,7 +3209,7 @@ public Mono> signWithResponseAsync(String keyName, String k * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the signing operation. @@ -3230,7 +3231,7 @@ public Response signWithResponse(String keyName, String keyVersion, /** * Verifies a signature using a specified key. - * + * * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public * portion of the key but this operation is supported as a convenience for callers that only have a key-reference @@ -3256,7 +3257,7 @@ public Response signWithResponse(String keyName, String keyVersion, * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for verify operations. @@ -3279,7 +3280,7 @@ public Mono> verifyWithResponseAsync(String keyName, String /** * Verifies a signature using a specified key. - * + * * The VERIFY operation is applicable to symmetric keys stored in Azure Key Vault. VERIFY is not strictly necessary * for asymmetric keys stored in Azure Key Vault since signature verification can be performed using the public * portion of the key but this operation is supported as a convenience for callers that only have a key-reference @@ -3305,7 +3306,7 @@ public Mono> verifyWithResponseAsync(String keyName, String * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for verify operations. @@ -3327,7 +3328,7 @@ public Response verifyWithResponse(String keyName, String keyVersion /** * Wraps a symmetric key using a specified key. - * + * * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This @@ -3360,7 +3361,7 @@ public Response verifyWithResponse(String keyName, String keyVersion * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for wrap operation. @@ -3383,7 +3384,7 @@ public Mono> wrapKeyWithResponseAsync(String keyName, Strin /** * Wraps a symmetric key using a specified key. - * + * * The WRAP operation supports encryption of a symmetric key using a key encryption key that has previously been * stored in an Azure Key Vault. The WRAP operation is only strictly necessary for symmetric keys stored in Azure * Key Vault since protection with an asymmetric key can be performed using the public portion of the key. This @@ -3416,7 +3417,7 @@ public Mono> wrapKeyWithResponseAsync(String keyName, Strin * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for wrap operation. @@ -3438,7 +3439,7 @@ public Response wrapKeyWithResponse(String keyName, String keyVersio /** * Creates a new 256 bit AES key within the trusted execution environment and wraps this key using a specified key. - * + * * The SECURE WRAP operation creates a new 256 bit AES key within the trusted execution environment(TEE) and * encrypts the same with a key encryption key that has previously been stored in an Azure Key Vault. The WRAP * operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection with an @@ -3466,7 +3467,7 @@ public Response wrapKeyWithResponse(String keyName, String keyVersio * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for wrap operation. @@ -3490,7 +3491,7 @@ public Mono> secureWrapKeyWithResponseAsync(String keyName, /** * Creates a new 256 bit AES key within the trusted execution environment and wraps this key using a specified key. - * + * * The SECURE WRAP operation creates a new 256 bit AES key within the trusted execution environment(TEE) and * encrypts the same with a key encryption key that has previously been stored in an Azure Key Vault. The WRAP * operation is only strictly necessary for symmetric keys stored in Azure Key Vault since protection with an @@ -3518,7 +3519,7 @@ public Mono> secureWrapKeyWithResponseAsync(String keyName, * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for wrap operation. @@ -3541,7 +3542,7 @@ public Response secureWrapKeyWithResponse(String keyName, String key /** * Securely unwraps a previously wrapped symmetric key using a specified key, ensuring TEE attestation via Microsoft * Azure Attestation (MAA) before unwrapping. - * + * * The SECURE UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This * operation is the reverse of the SECURE WRAP operation. The SECURE UNWRAP operation applies to asymmetric and * symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires @@ -3571,7 +3572,7 @@ public Response secureWrapKeyWithResponse(String keyName, String key * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for unwrap operation. @@ -3596,7 +3597,7 @@ public Mono> secureUnwrapKeyWithResponseAsync(String keyNam /** * Securely unwraps a previously wrapped symmetric key using a specified key, ensuring TEE attestation via Microsoft * Azure Attestation (MAA) before unwrapping. - * + * * The SECURE UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This * operation is the reverse of the SECURE WRAP operation. The SECURE UNWRAP operation applies to asymmetric and * symmetric keys stored in Azure Key Vault since it uses the private portion of the key. This operation requires @@ -3626,7 +3627,7 @@ public Mono> secureUnwrapKeyWithResponseAsync(String keyNam * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for unwrap operation. @@ -3648,7 +3649,7 @@ public Response secureUnwrapKeyWithResponse(String keyName, String k /** * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * + * * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey @@ -3680,7 +3681,7 @@ public Response secureUnwrapKeyWithResponse(String keyName, String k * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the key operation. @@ -3703,7 +3704,7 @@ public Mono> unwrapKeyWithResponseAsync(String keyName, Str /** * Unwraps a symmetric key using the specified key that was initially used for wrapping that key. - * + * * The UNWRAP operation supports decryption of a symmetric key using the target key encryption key. This operation * is the reverse of the WRAP operation. The UNWRAP operation applies to asymmetric and symmetric keys stored in * Azure Key Vault since it uses the private portion of the key. This operation requires the keys/unwrapKey @@ -3735,7 +3736,7 @@ public Mono> unwrapKeyWithResponseAsync(String keyName, Str * } * } * - * + * * @param keyName The name of the key. * @param keyVersion The version of the key. * @param parameters The parameters for the key operation. @@ -3757,7 +3758,7 @@ public Response unwrapKeyWithResponse(String keyName, String keyVers /** * Releases a key. - * + * * The release key operation is applicable to all key types. The target key must be marked exportable. This * operation requires the keys/release permission. *

Request Body Schema

@@ -3781,7 +3782,7 @@ public Response unwrapKeyWithResponse(String keyName, String keyVers * } * } * - * + * * @param keyName The name of the key to get. * @param keyVersion Adding the version parameter retrieves a specific version of a key. * @param parameters The parameters for the key release operation. @@ -3805,7 +3806,7 @@ public Mono> releaseWithResponseAsync(String keyName, Strin /** * Releases a key. - * + * * The release key operation is applicable to all key types. The target key must be marked exportable. This * operation requires the keys/release permission. *

Request Body Schema

@@ -3829,7 +3830,7 @@ public Mono> releaseWithResponseAsync(String keyName, Strin * } * } * - * + * * @param keyName The name of the key to get. * @param keyVersion Adding the version parameter retrieves a specific version of a key. * @param parameters The parameters for the key release operation. @@ -3851,7 +3852,7 @@ public Response releaseWithResponse(String keyName, String keyVersio /** * Lists the deleted keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if @@ -3901,7 +3902,7 @@ public Response releaseWithResponse(String keyName, String keyVersio * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -3922,7 +3923,7 @@ private Mono> getDeletedKeysSinglePageAsync(RequestOpt /** * Lists the deleted keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if @@ -3972,7 +3973,7 @@ private Mono> getDeletedKeysSinglePageAsync(RequestOpt * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -3991,7 +3992,7 @@ public PagedFlux getDeletedKeysAsync(RequestOptions requestOptions) /** * Lists the deleted keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if @@ -4041,7 +4042,7 @@ public PagedFlux getDeletedKeysAsync(RequestOptions requestOptions) * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -4060,7 +4061,7 @@ private PagedResponse getDeletedKeysSinglePage(RequestOptions reques /** * Lists the deleted keys in the specified vault. - * + * * Retrieves a list of the keys in the Key Vault as JSON Web Key structures that contain the public part of a * deleted key. This operation includes deletion-specific information. The Get Deleted Keys operation is applicable * for vaults enabled for soft-delete. While the operation can be invoked on any vault, it will return an error if @@ -4110,7 +4111,7 @@ private PagedResponse getDeletedKeysSinglePage(RequestOptions reques * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -4129,7 +4130,7 @@ public PagedIterable getDeletedKeys(RequestOptions requestOptions) { /** * Gets the public part of a deleted key. - * + * * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the * keys/get permission. @@ -4194,7 +4195,7 @@ public PagedIterable getDeletedKeys(RequestOptions requestOptions) { * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4202,7 +4203,7 @@ public PagedIterable getDeletedKeys(RequestOptions requestOptions) { * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the public part of a deleted key. - * + * * The Get Deleted Key operation is applicable for soft-delete enabled vaults along with {@link Response} on * successful completion of {@link Mono}. */ @@ -4215,7 +4216,7 @@ public Mono> getDeletedKeyWithResponseAsync(String keyName, /** * Gets the public part of a deleted key. - * + * * The Get Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked on * any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the * keys/get permission. @@ -4280,7 +4281,7 @@ public Mono> getDeletedKeyWithResponseAsync(String keyName, * } * } * - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4288,7 +4289,7 @@ public Mono> getDeletedKeyWithResponseAsync(String keyName, * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the public part of a deleted key. - * + * * The Get Deleted Key operation is applicable for soft-delete enabled vaults along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) @@ -4300,11 +4301,11 @@ public Response getDeletedKeyWithResponse(String keyName, RequestOpt /** * Permanently deletes the specified key. - * + * * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the * keys/purge permission. - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4321,11 +4322,11 @@ public Mono> purgeDeletedKeyWithResponseAsync(String keyName, Req /** * Permanently deletes the specified key. - * + * * The Purge Deleted Key operation is applicable for soft-delete enabled vaults. While the operation can be invoked * on any vault, it will return an error if invoked on a non soft-delete enabled vault. This operation requires the * keys/purge permission. - * + * * @param keyName The name of the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4342,7 +4343,7 @@ public Response purgeDeletedKeyWithResponse(String keyName, RequestOptions /** * Recovers the deleted key to its latest version. - * + * * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires @@ -4405,7 +4406,7 @@ public Response purgeDeletedKeyWithResponse(String keyName, RequestOptions * } * } * - * + * * @param keyName The name of the deleted key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4425,7 +4426,7 @@ public Mono> recoverDeletedKeyWithResponseAsync(String keyN /** * Recovers the deleted key to its latest version. - * + * * The Recover Deleted Key operation is applicable for deleted keys in soft-delete enabled vaults. It recovers the * deleted key back to its latest version under /keys. An attempt to recover an non-deleted key will return an * error. Consider this the inverse of the delete operation on soft-delete enabled vaults. This operation requires @@ -4488,7 +4489,7 @@ public Mono> recoverDeletedKeyWithResponseAsync(String keyN * } * } * - * + * * @param keyName The name of the deleted key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4506,7 +4507,7 @@ public Response recoverDeletedKeyWithResponse(String keyName, Reques /** * Lists the policy for a key. - * + * * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This * operation requires the keys/get permission. *

Response Body Schema

@@ -4534,7 +4535,7 @@ public Response recoverDeletedKeyWithResponse(String keyName, Reques * } * } * - * + * * @param keyName The name of the key in a given key vault. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4553,7 +4554,7 @@ public Mono> getKeyRotationPolicyWithResponseAsync(String k /** * Lists the policy for a key. - * + * * The GetKeyRotationPolicy operation returns the specified key policy resources in the specified key vault. This * operation requires the keys/get permission. *

Response Body Schema

@@ -4581,7 +4582,7 @@ public Mono> getKeyRotationPolicyWithResponseAsync(String k * } * } * - * + * * @param keyName The name of the key in a given key vault. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4599,7 +4600,7 @@ public Response getKeyRotationPolicyWithResponse(String keyName, Req /** * Updates the rotation policy for a key. - * + * * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update * permission. *

Request Body Schema

@@ -4653,7 +4654,7 @@ public Response getKeyRotationPolicyWithResponse(String keyName, Req * } * } * - * + * * @param keyName The name of the key in the given vault. * @param keyRotationPolicy The policy for the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -4675,7 +4676,7 @@ public Mono> updateKeyRotationPolicyWithResponseAsync(Strin /** * Updates the rotation policy for a key. - * + * * Set specified members in the key policy. Leave others as undefined. This operation requires the keys/update * permission. *

Request Body Schema

@@ -4729,7 +4730,7 @@ public Mono> updateKeyRotationPolicyWithResponseAsync(Strin * } * } * - * + * * @param keyName The name of the key in the given vault. * @param keyRotationPolicy The policy for the key. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. @@ -4750,7 +4751,7 @@ public Response updateKeyRotationPolicyWithResponse(String keyName, /** * Get the requested number of bytes containing random values. - * + * * Get the requested number of bytes containing random values from a managed HSM. *

Request Body Schema

* @@ -4771,7 +4772,7 @@ public Response updateKeyRotationPolicyWithResponse(String keyName, * } * } * - * + * * @param parameters The request object to get random bytes. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4779,7 +4780,7 @@ public Response updateKeyRotationPolicyWithResponse(String keyName, * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the requested number of bytes containing random values. - * + * * Get the requested number of bytes containing random values from a managed HSM along with {@link Response} on * successful completion of {@link Mono}. */ @@ -4794,7 +4795,7 @@ public Mono> getRandomBytesWithResponseAsync(BinaryData par /** * Get the requested number of bytes containing random values. - * + * * Get the requested number of bytes containing random values from a managed HSM. *

Request Body Schema

* @@ -4815,7 +4816,7 @@ public Mono> getRandomBytesWithResponseAsync(BinaryData par * } * } * - * + * * @param parameters The request object to get random bytes. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -4823,7 +4824,7 @@ public Mono> getRandomBytesWithResponseAsync(BinaryData par * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the requested number of bytes containing random values. - * + * * Get the requested number of bytes containing random values from a managed HSM along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) @@ -4836,7 +4837,7 @@ public Response getRandomBytesWithResponse(BinaryData parameters, Re /** * Gets the public part of a stored key along with its attestation blob. - * + * * The get key attestation operation returns the key along with its attestation blob. This operation requires the * keys/get permission. *

Response Body Schema

@@ -4897,7 +4898,7 @@ public Response getRandomBytesWithResponse(BinaryData parameters, Re * } * } * - * + * * @param keyName The name of the key to retrieve attestation for. * @param keyVersion Adding the version parameter retrieves attestation blob for specific version of a key. This URI * fragment is optional. If not specified, the latest version of the key attestation blob is returned. @@ -4907,7 +4908,7 @@ public Response getRandomBytesWithResponse(BinaryData parameters, Re * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the public part of a stored key along with its attestation blob. - * + * * The get key attestation operation returns the key along with its attestation blob along with {@link Response} on * successful completion of {@link Mono}. */ @@ -4921,7 +4922,7 @@ public Mono> getKeyAttestationWithResponseAsync(String keyN /** * Gets the public part of a stored key along with its attestation blob. - * + * * The get key attestation operation returns the key along with its attestation blob. This operation requires the * keys/get permission. *

Response Body Schema

@@ -4982,7 +4983,7 @@ public Mono> getKeyAttestationWithResponseAsync(String keyN * } * } * - * + * * @param keyName The name of the key to retrieve attestation for. * @param keyVersion Adding the version parameter retrieves attestation blob for specific version of a key. This URI * fragment is optional. If not specified, the latest version of the key attestation blob is returned. @@ -4992,7 +4993,7 @@ public Mono> getKeyAttestationWithResponseAsync(String keyN * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the public part of a stored key along with its attestation blob. - * + * * The get key attestation operation returns the key along with its attestation blob along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) @@ -5005,7 +5006,7 @@ public Response getKeyAttestationWithResponse(String keyName, String /** * Retrieves a list of individual key versions with the same key name. - * + * * Get the next page of items. *

Response Body Schema

* @@ -5041,7 +5042,7 @@ public Response getKeyAttestationWithResponse(String keyName, String * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5064,7 +5065,7 @@ private Mono> getKeyVersionsNextSinglePageAsync(String /** * Retrieves a list of individual key versions with the same key name. - * + * * Get the next page of items. *

Response Body Schema

* @@ -5100,7 +5101,7 @@ private Mono> getKeyVersionsNextSinglePageAsync(String * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5121,7 +5122,7 @@ private PagedResponse getKeyVersionsNextSinglePage(String nextLink, /** * List keys in the specified vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -5157,7 +5158,7 @@ private PagedResponse getKeyVersionsNextSinglePage(String nextLink, * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5179,7 +5180,7 @@ private Mono> getKeysNextSinglePageAsync(String nextLi /** * List keys in the specified vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -5215,7 +5216,7 @@ private Mono> getKeysNextSinglePageAsync(String nextLi * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5236,7 +5237,7 @@ private PagedResponse getKeysNextSinglePage(String nextLink, Request /** * Lists the deleted keys in the specified vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -5275,7 +5276,7 @@ private PagedResponse getKeysNextSinglePage(String nextLink, Request * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -5299,7 +5300,7 @@ private Mono> getDeletedKeysNextSinglePageAsync(String /** * Lists the deleted keys in the specified vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -5338,7 +5339,7 @@ private Mono> getDeletedKeysNextSinglePageAsync(String * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java index 4eb339ab7a6a8..014eeb47a2d62 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/implementation/KeyVaultCredentialPolicy.java @@ -48,6 +48,7 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; + private static final String KEY_VAULT_REQUEST_CHALLENGE_KEY = "KeyVaultCredentialPolicyRequestChallenge"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; @@ -94,12 +95,7 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - return setAuthorizationHeader(context, tokenRequestContext); + return setAuthorizationHeader(context, challenge.toTokenRequestContext()); } // The body is removed from the initial request because Key Vault supports other authentication schemes @@ -185,26 +181,8 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext - .setClaims(new String(Base64Util.decodeString(claims), StandardCharsets.UTF_8)); - } - } - } - - return setAuthorizationHeader(context, tokenRequestContext).then(Mono.just(true)); + return setAuthorizationHeader(context, saveRequestChallenge(context, challenge, challengeAttributes)) + .then(Mono.just(true)); }); } @@ -215,12 +193,7 @@ public void authorizeRequestSync(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, challenge.toTokenRequestContext()); return; } @@ -302,25 +275,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext.setClaims(new String(Base64Util.decodeString(claims))); - } - } - } - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, saveRequestChallenge(context, challenge, challengeAttributes)); return true; } @@ -454,6 +409,23 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private static TokenRequestContext saveRequestChallenge(HttpPipelineCallContext context, + ChallengeParameters challenge, Map attributes) { + String claims = null; + String error = attributes.get("error"); + if (error != null) { + LOGGER.verbose("The challenge response contained an error: {}", error); + if ("insufficient_claims".equalsIgnoreCase(error) && attributes.get("claims") != null) { + claims = new String(Base64Util.decodeString(attributes.get("claims")), StandardCharsets.UTF_8); + } + } + ChallengeParameters requestChallenge + = new ChallengeParameters(challenge.authority, challenge.authorizationUri, challenge.scopes, claims); + // Persist an immutable, request-local snapshot before acquisition, including when acquisition fails. + context.setData(KEY_VAULT_REQUEST_CHALLENGE_KEY, requestChallenge); + return requestChallenge.toTokenRequestContext(); + } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { if (context == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); @@ -493,12 +465,25 @@ private static class ChallengeParameters { private final URI authorizationUri; private final String tenantId; private final String[] scopes; + private final String claims; ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this(authority, authorizationUri, scopes, null); + } + + private ChallengeParameters(String authority, URI authorizationUri, String[] scopes, String claims) { this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; - this.scopes = scopes; + this.scopes = scopes.clone(); + this.claims = claims; + } + + private TokenRequestContext toTokenRequestContext() { + return new TokenRequestContext().addScopes(scopes) + .setTenantId(tenantId) + .setClaims(claims) + .setCaeEnabled(true); } /** @@ -530,6 +515,11 @@ public static void clearCache() { private ChallengeParameters getChallenge(HttpPipelineCallContext context) { String authority = getRequestAuthority(context); + ChallengeParameters requestChallenge + = (ChallengeParameters) context.getData(KEY_VAULT_REQUEST_CHALLENGE_KEY).orElse(null); + if (requestChallenge != null) { + return requestChallenge; + } // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. ChallengeParameters cachedChallenge = this.challenge; if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java index 6795a0ed2c1fb..d020874b6f5bf 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyClientTestBase.java @@ -17,6 +17,8 @@ import com.azure.core.test.models.BodilessMatcher; import com.azure.core.test.models.CustomMatcher; import com.azure.core.test.models.TestProxyRequestMatcher; +import com.azure.core.test.models.TestProxySanitizer; +import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.BinaryData; import com.azure.core.util.Configuration; @@ -47,6 +49,7 @@ import java.io.IOException; import java.math.BigInteger; +import java.net.URI; import java.time.Duration; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -139,6 +142,8 @@ KeyClientBuilder getKeyClientBuilder(HttpClient httpClient, String testTenantId, .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { + interceptorManager + .addSanitizers(Collections.singletonList(playbackNextLinkSanitizer(endpoint, runManagedHsmTest))); return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); @@ -149,6 +154,14 @@ KeyClientBuilder getKeyClientBuilder(HttpClient httpClient, String testTenantId, } } + static TestProxySanitizer playbackNextLinkSanitizer(String endpoint, boolean managedHsm) { + // Match the pinned recording's vault, not every vault or HSM host. + String host + = managedHsm ? "externalkeysdkhsm[.]managedhsm[.]azure[.]net" : "externalkeysdk[.]vault[.]azure[.]net"; + return new TestProxySanitizer("$.nextLink", "(?i)^https://" + host + "(?::443)?/", + URI.create(endpoint).resolve("/").toString(), TestProxySanitizerType.BODY_KEY); + } + @Test public abstract void createKey(HttpClient httpClient, KeyServiceVersion serviceVersion); diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java index d1f47227f4bc5..8d0a45c2103eb 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultCredentialPolicyTest.java @@ -216,6 +216,10 @@ public void failedContextChangeCannotReusePreviousToken() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { tokenRequests.incrementAndGet(); if (changedChallenge.get()) { + assertEquals(tenant, context.getTenantId()); + assertEquals(Arrays.asList(scope), context.getScopes()); + assertEquals(claims, context.getClaims()); + assertTrue(context.isCaeEnabled()); throw new IllegalStateException("Token acquisition failed."); } return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); @@ -331,6 +335,69 @@ private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String () -> pipeline.send(request, Context.NONE)); } + @SyncAsyncTest + public void challengedContextSurvivesFailedAcquisitionAndRetry() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean changeTenantAndScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean challenged = new AtomicBoolean(); + AtomicBoolean independentRequest = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger challengedTokenRequests = new AtomicInteger(); + String tenant = changeTenantAndScope ? "second" : "first"; + String scope = changeTenantAndScope ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + assertEquals(challenged.get() ? tenant : "first", context.getTenantId()); + assertEquals(Arrays.asList(challenged.get() ? scope : "https://vault.azure.net/.default"), + context.getScopes()); + assertTrue(context.isCaeEnabled()); + assertEquals(challenged.get() && !independentRequest.get() ? DECODED_CLAIMS : null, + context.getClaims()); + if (challenged.get() && !independentRequest.get()) { + if (challengedTokenRequests.incrementAndGet() == 1) { + context.getScopes().clear(); + context.setTenantId("credential-mutated").setClaims("mutated").setCaeEnabled(false); + throw new IllegalStateException("Transient challenged token acquisition failure."); + } + return new AccessToken("claims-token", OffsetDateTime.now().plusHours(1)); + } + return new AccessToken("ordinary-token", OffsetDateTime.now().plusHours(1)); + }), disableVerification); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if ("/changed".equals(request.getUrl().getPath())) { + if (challenged.compareAndSet(false, true)) { + assertEquals("Bearer ordinary-token", authorization); + return Mono.just(tokenCacheChallenge(request, tenant, scope, DECODED_CLAIMS)); + } + assertEquals("Bearer claims-token", authorization); + } else if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null)); + } else { + assertEquals("Bearer ordinary-token", authorization); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + assertEquals(200, sendTokenCacheRequest(pipeline, "https://first.vault.azure.net").getStatusCode()); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed").getStatusCode()); + assertEquals(2, challengedTokenRequests.get()); + assertEquals(3, tokenRequests.get()); + + independentRequest.set(true); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/independent").getStatusCode()); + assertEquals(4, tokenRequests.get(), "Claims must not leak into a separate request."); + } + } + } + private static HttpResponse tokenCacheChallenge(HttpRequest request, String tenant, String scope, String claims) { String challenge = "Bearer authorization=\"https://login.example/" + tenant + "\", scope=\"" + scope + "\""; if (claims != null) { diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java index 235fd9b22bd4a..924bd18e26182 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/test/java/com/azure/security/keyvault/keys/KeyVaultPaginationTest.java @@ -10,23 +10,29 @@ import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.policy.FixedDelayOptions; +import com.azure.core.http.policy.RetryOptions; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.test.SyncAsyncExtension; import com.azure.core.test.annotation.SyncAsyncTest; import com.azure.core.test.http.MockHttpResponse; +import com.azure.core.test.models.TestProxySanitizer; import com.azure.security.keyvault.keys.implementation.KeyVaultCredentialPolicy; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Mono; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -46,6 +52,28 @@ public void cleanup() { KeyVaultCredentialPolicy.clearCache(); } + @Test + public void playbackSanitizerOnlyRewritesRecordedOrigin() { + for (boolean managedHsm : new boolean[] { false, true }) { + TestProxySanitizer sanitizer + = KeyClientTestBase.playbackNextLinkSanitizer("https://localhost:8080/base", managedHsm); + Pattern pattern = Pattern.compile(sanitizer.getRegex()); + String host = managedHsm ? "externalkeysdkhsm.managedhsm.azure.net" : "externalkeysdk.vault.azure.net"; + String suffix = "keys/name%2Fpart?api-version=7.6&skiptoken=a%2Bb%3D"; + for (String origin : Arrays.asList("https://" + host + ":443/", "HTTPS://" + host + "/")) { + assertEquals("https://localhost:8080/" + suffix, + pattern.matcher(origin + suffix).replaceFirst(sanitizer.getRedactedValue())); + } + for (String origin : Arrays.asList("https://other.example/", "http://" + host + "/", + "https://" + host + ":8443/", "https://" + host + ".other.example/", "https://user@" + host + "/", + "https://" + host + "@other.example/")) { + assertEquals(origin + suffix, + pattern.matcher(origin + suffix).replaceFirst(sanitizer.getRedactedValue())); + } + assertEquals("$.nextLink", sanitizer.getKey()); + } + } + @SyncAsyncTest public void allContinuationOperationsValidateBeforePipeline() { for (boolean customPipeline : new boolean[] { false, true }) { @@ -109,6 +137,90 @@ private void assertRejectedContinuations(PagedIterable sync, PagedFlux asy } } + @SyncAsyncTest + public void validCloudAndCustomChallengesWorkWithVerificationEnabled() { + // Service suffix examples from https://aka.ms/azsdk/blog/vault-uri, plus custom origins. + String[][] endpoints = { + { "https://paging.vault.azure.net", "https://vault.azure.net" }, + { "https://paging.vault.azure.cn", "https://vault.azure.cn" }, + { "https://paging.vault.usgovcloudapi.net", "https://vault.usgovcloudapi.net" }, + { "https://paging.region.managedhsm.azure.net", "https://managedhsm.azure.net" }, + { "https://paging.managedhsm.azure.cn", "https://managedhsm.azure.cn" }, + { "https://paging.managedhsm.usgovcloudapi.net", "https://managedhsm.usgovcloudapi.net" }, + { "https://keys.arbitrary.example:8443", "https://arbitrary.example" }, + { "HTTPS://KEYS.XN--BCHER-KVA.EXAMPLE:443", "https://xn--bcher-kva.example" } }; + for (boolean disableVerification : new boolean[] { false, true }) { + for (String[] endpoint : endpoints) { + KeyVaultCredentialPolicy.clearCache(); + KeyClientBuilder builder = builder(endpoint[0], endpoint[1], false, disableVerification); + assertEquals(1, readPages(builder.buildClient().listPropertiesOfKeys(), + builder.buildAsyncClient().listPropertiesOfKeys(), endpoint[0] + "/keys?skip=1")); + } + } + } + + @SyncAsyncTest + public void defaultResourceVerificationDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(false); + } + + @SyncAsyncTest + public void verificationOptOutDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(true); + } + + private void assertValidChallengeCannotAuthorizeForeignContinuation(boolean disableVerification) { + KeyClientBuilder original = builder(false, disableVerification); + KeyClient client = original.buildClient(); + KeyAsyncClient asyncClient = original.buildAsyncClient(); + assertEquals(1, readPages(client.listPropertiesOfKeys(), asyncClient.listPropertiesOfKeys(), null)); + String otherOrigin = "https://other.vault.azure.net"; + KeyClientBuilder other = builder(otherOrigin, "https://vault.azure.net", false, disableVerification); + assertEquals(1, readPages(other.buildClient().listPropertiesOfKeys(), + other.buildAsyncClient().listPropertiesOfKeys(), null)); + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + assertThrows(IllegalArgumentException.class, () -> readPages(client.listPropertiesOfKeys(), + asyncClient.listPropertiesOfKeys(), otherOrigin + "/keys?skip=1")); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + + @SyncAsyncTest + public void verificationOptOutChangesOnlyChallengeResourceValidation() { + String endpoint = "https://keys.example:8443"; + String resource = "https://vault.azure.net"; + KeyClientBuilder verified = builder(endpoint, resource, false, false); + RuntimeException rejected + = assertThrows(RuntimeException.class, () -> readPages(verified.buildClient().listPropertiesOfKeys(), + verified.buildAsyncClient().listPropertiesOfKeys(), endpoint + "/keys")); + assertTrue(rejected.getMessage().contains("challenge resource")); + assertEquals(0, tokenRequests.get()); + assertEquals(1, sends.get()); + + KeyClientBuilder optedOut = builder(endpoint, resource, false, true); + KeyClient client = optedOut.buildClient(); + KeyAsyncClient asyncClient = optedOut.buildAsyncClient(); + assertEquals(1, + readPages(client.listPropertiesOfKeys(), asyncClient.listPropertiesOfKeys(), endpoint + "/keys")); + assertEquals(1, tokenRequests.get()); + int previousSends = sends.get(); + for (boolean disableVerification : new boolean[] { false, true }) { + String insecureEndpoint = "http://keys.example:8443"; + KeyClientBuilder insecure = builder(insecureEndpoint, resource, false, disableVerification); + RuntimeException insecureRejected + = assertThrows(RuntimeException.class, () -> readPages(insecure.buildClient().listPropertiesOfKeys(), + insecure.buildAsyncClient().listPropertiesOfKeys(), insecureEndpoint + "/keys")); + assertTrue(insecureRejected.getMessage().contains("HTTPS")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + assertThrows(IllegalArgumentException.class, () -> readPages(client.listPropertiesOfKeys(), + asyncClient.listPropertiesOfKeys(), "https://other.example:8443/keys")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + private static int readPages(PagedIterable sync, PagedFlux async, String nextLink) { AtomicInteger pages = new AtomicInteger(); SyncAsyncExtension.execute(() -> sync.iterableByPage(nextLink).forEach(page -> pages.incrementAndGet()), @@ -118,6 +230,11 @@ private static int readPages(PagedIterable sync, PagedFlux async, String n } private KeyClientBuilder builder(boolean customPipeline, boolean disableVerification) { + return builder(ENDPOINT, "https://vault.azure.net", customPipeline, disableVerification); + } + + private KeyClientBuilder builder(String endpoint, String resource, boolean customPipeline, + boolean disableVerification) { TokenCredential credential = context -> { tokenRequests.incrementAndGet(); return Mono.just(new AccessToken("fake-key-vault-token", OffsetDateTime.now().plusHours(1))); @@ -127,7 +244,7 @@ private KeyClientBuilder builder(boolean customPipeline, boolean disableVerifica String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); if (authorization == null) { return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, - "Bearer authorization=\"https://login.example/tenant\", resource=\"https://vault.azure.net\"")); + "Bearer authorization=\"https://login.example/tenant\", resource=\"" + resource + "\"")); } assertEquals("Bearer fake-key-vault-token", authorization); authorizedSends.incrementAndGet(); @@ -137,8 +254,10 @@ private KeyClientBuilder builder(boolean customPipeline, boolean disableVerifica new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), body.getBytes(StandardCharsets.UTF_8)); }); - KeyClientBuilder builder - = new KeyClientBuilder().vaultUrl(ENDPOINT).credential(credential).httpClient(httpClient); + KeyClientBuilder builder = new KeyClientBuilder().vaultUrl(endpoint) + .credential(credential) + .httpClient(httpClient) + .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))); if (disableVerification) { builder.disableChallengeResourceVerification(); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md index 271fbf3032e86..04a0770cff468 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md @@ -9,7 +9,10 @@ ### Bugs Fixed - Validate pagination destinations against the configured endpoint and bind cached authentication challenges to their origin, including during token acquisition. + Continuation validation now requires absolute HTTP(S) URIs with ASCII (including punycode) hosts and no user information + or fragment; relative continuations and URL-permissive non-URI forms are no longer accepted. - Isolate cached access tokens by endpoint origin and authentication context when acquisitions fail or are retried. +- Preserve request-local challenge claims when retrying failed token acquisitions. ### Other Changes diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java index b7725fb91f93f..f030393b55558 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/KeyVaultCredentialPolicy.java @@ -48,6 +48,7 @@ public class KeyVaultCredentialPolicy extends BearerTokenAuthenticationPolicy { private static final String KEY_VAULT_STASHED_CONTENT_KEY = "KeyVaultCredentialPolicyStashedBody"; private static final String KEY_VAULT_STASHED_CONTENT_LENGTH_KEY = "KeyVaultCredentialPolicyStashedContentLength"; private static final String KEY_VAULT_REQUEST_ORIGIN_KEY = "KeyVaultCredentialPolicyRequestOrigin"; + private static final String KEY_VAULT_REQUEST_CHALLENGE_KEY = "KeyVaultCredentialPolicyRequestChallenge"; private static final ConcurrentMap CHALLENGE_CACHE = new ConcurrentHashMap<>(); private volatile ChallengeParameters challenge; private final boolean disableChallengeResourceVerification; @@ -94,12 +95,7 @@ public Mono authorizeRequest(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - return setAuthorizationHeader(context, tokenRequestContext); + return setAuthorizationHeader(context, challenge.toTokenRequestContext()); } // The body is removed from the initial request because Key Vault supports other authentication schemes @@ -185,26 +181,8 @@ public Mono authorizeRequestOnChallenge(HttpPipelineCallContext context } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext - .setClaims(new String(Base64Util.decodeString(claims), StandardCharsets.UTF_8)); - } - } - } - - return setAuthorizationHeader(context, tokenRequestContext).then(Mono.just(true)); + return setAuthorizationHeader(context, saveRequestChallenge(context, challenge, challengeAttributes)) + .then(Mono.just(true)); }); } @@ -215,12 +193,7 @@ public void authorizeRequestSync(HttpPipelineCallContext context) { ChallengeParameters challenge = getChallenge(context); if (challenge != null) { - // We fetched the challenge from the cache, but we have not initialized the scopes in the base yet. - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, challenge.toTokenRequestContext()); return; } @@ -302,25 +275,7 @@ public boolean authorizeRequestOnChallengeSync(HttpPipelineCallContext context, } this.challenge = challenge; - TokenRequestContext tokenRequestContext = new TokenRequestContext().addScopes(challenge.getScopes()) - .setTenantId(challenge.getTenantId()) - .setCaeEnabled(true); - - String error = challengeAttributes.get("error"); - - if (error != null) { - LOGGER.verbose("The challenge response contained an error: {}", error); - - if ("insufficient_claims".equalsIgnoreCase(error)) { - String claims = challengeAttributes.get("claims"); - - if (claims != null) { - tokenRequestContext.setClaims(new String(Base64Util.decodeString(claims))); - } - } - } - - setAuthorizationHeaderSync(context, tokenRequestContext); + setAuthorizationHeaderSync(context, saveRequestChallenge(context, challenge, challengeAttributes)); return true; } @@ -454,6 +409,23 @@ private boolean isClaimsPresent(HttpResponse httpResponse) { return false; } + private static TokenRequestContext saveRequestChallenge(HttpPipelineCallContext context, + ChallengeParameters challenge, Map attributes) { + String claims = null; + String error = attributes.get("error"); + if (error != null) { + LOGGER.verbose("The challenge response contained an error: {}", error); + if ("insufficient_claims".equalsIgnoreCase(error) && attributes.get("claims") != null) { + claims = new String(Base64Util.decodeString(attributes.get("claims")), StandardCharsets.UTF_8); + } + } + ChallengeParameters requestChallenge + = new ChallengeParameters(challenge.authority, challenge.authorizationUri, challenge.scopes, claims); + // Persist an immutable, request-local snapshot before acquisition, including when acquisition fails. + context.setData(KEY_VAULT_REQUEST_CHALLENGE_KEY, requestChallenge); + return requestChallenge.toTokenRequestContext(); + } + private AccessTokenCache getAccessTokenCache(String authority, TokenRequestContext context) { if (context == null) { throw LOGGER.logExceptionAsError(new IllegalArgumentException("'tokenRequestContext' cannot be null.")); @@ -493,12 +465,25 @@ private static class ChallengeParameters { private final URI authorizationUri; private final String tenantId; private final String[] scopes; + private final String claims; ChallengeParameters(String authority, URI authorizationUri, String[] scopes) { + this(authority, authorizationUri, scopes, null); + } + + private ChallengeParameters(String authority, URI authorizationUri, String[] scopes, String claims) { this.authority = authority; this.authorizationUri = authorizationUri; tenantId = authorizationUri.getPath().split("/")[1]; - this.scopes = scopes; + this.scopes = scopes.clone(); + this.claims = claims; + } + + private TokenRequestContext toTokenRequestContext() { + return new TokenRequestContext().addScopes(scopes) + .setTenantId(tenantId) + .setClaims(claims) + .setCaeEnabled(true); } /** @@ -530,6 +515,11 @@ public static void clearCache() { private ChallengeParameters getChallenge(HttpPipelineCallContext context) { String authority = getRequestAuthority(context); + ChallengeParameters requestChallenge + = (ChallengeParameters) context.getData(KEY_VAULT_REQUEST_CHALLENGE_KEY).orElse(null); + if (requestChallenge != null) { + return requestChallenge; + } // Use one immutable snapshot so concurrent requests cannot mix origins, scopes, or tenants. ChallengeParameters cachedChallenge = this.challenge; if (cachedChallenge == null || !authority.equals(cachedChallenge.authority)) { diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java index d71fbc2621c7b..65ebd83b0a372 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/main/java/com/azure/security/keyvault/secrets/implementation/SecretClientImpl.java @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) TypeSpec Code Generator. - package com.azure.security.keyvault.secrets.implementation; import com.azure.core.annotation.BodyParam; @@ -50,6 +49,7 @@ * Initializes a new instance of the SecretClient type. */ public final class SecretClientImpl { + /** * The proxy service used to perform REST calls. */ @@ -61,7 +61,7 @@ public final class SecretClientImpl { /** * Gets. - * + * * @return the vaultBaseUrl value. */ public String getVaultBaseUrl() { @@ -75,7 +75,7 @@ public String getVaultBaseUrl() { /** * Gets Service version. - * + * * @return the serviceVersion value. */ public SecretServiceVersion getServiceVersion() { @@ -89,7 +89,7 @@ public SecretServiceVersion getServiceVersion() { /** * Gets The HTTP pipeline to send requests through. - * + * * @return the httpPipeline value. */ public HttpPipeline getHttpPipeline() { @@ -103,7 +103,7 @@ public HttpPipeline getHttpPipeline() { /** * Gets The serializer to serialize an object into a string. - * + * * @return the serializerAdapter value. */ public SerializerAdapter getSerializerAdapter() { @@ -112,7 +112,7 @@ public SerializerAdapter getSerializerAdapter() { /** * Initializes an instance of SecretClient client. - * + * * @param vaultBaseUrl * @param serviceVersion Service version. */ @@ -123,7 +123,7 @@ public SecretClientImpl(String vaultBaseUrl, SecretServiceVersion serviceVersion /** * Initializes an instance of SecretClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. * @param vaultBaseUrl * @param serviceVersion Service version. @@ -134,7 +134,7 @@ public SecretClientImpl(HttpPipeline httpPipeline, String vaultBaseUrl, SecretSe /** * Initializes an instance of SecretClient client. - * + * * @param httpPipeline The HTTP pipeline to send requests through. * @param serializerAdapter The serializer to serialize an object into a string. * @param vaultBaseUrl @@ -155,6 +155,7 @@ public SecretClientImpl(HttpPipeline httpPipeline, SerializerAdapter serializerA @Host("{vaultBaseUrl}") @ServiceInterface(name = "SecretClient") public interface SecretClientService { + @Put("/secrets/{secret-name}") @ExpectedResponses({ 200 }) @UnexpectedResponseExceptionType(value = ClientAuthenticationException.class, code = { 401 }) @@ -468,7 +469,7 @@ Response getDeletedSecretsNextSync(@PathParam(value = "nextLink", en /** * Sets a secret in a specified key vault. - * + * * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault * creates a new version of that secret. This operation requires the secrets/set permission. *

Request Body Schema

@@ -520,7 +521,7 @@ Response getDeletedSecretsNextSync(@PathParam(value = "nextLink", en * } * } * - * + * * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters for setting the secret. @@ -544,7 +545,7 @@ public Mono> setSecretWithResponseAsync(String secretName, /** * Sets a secret in a specified key vault. - * + * * The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault * creates a new version of that secret. This operation requires the secrets/set permission. *

Request Body Schema

@@ -596,7 +597,7 @@ public Mono> setSecretWithResponseAsync(String secretName, * } * } * - * + * * @param secretName The name of the secret. The value you provide may be copied globally for the purpose of running * the service. The value provided should not include personally identifiable or sensitive information. * @param parameters The parameters for setting the secret. @@ -618,7 +619,7 @@ public Response setSecretWithResponse(String secretName, BinaryData /** * Deletes a secret from a specified key vault. - * + * * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual * version of a secret. This operation requires the secrets/delete permission. *

Response Body Schema

@@ -650,7 +651,7 @@ public Response setSecretWithResponse(String secretName, BinaryData * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -669,7 +670,7 @@ public Mono> deleteSecretWithResponseAsync(String secretNam /** * Deletes a secret from a specified key vault. - * + * * The DELETE operation applies to any secret stored in Azure Key Vault. DELETE cannot be applied to an individual * version of a secret. This operation requires the secrets/delete permission. *

Response Body Schema

@@ -701,7 +702,7 @@ public Mono> deleteSecretWithResponseAsync(String secretNam * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -720,7 +721,7 @@ public Response deleteSecretWithResponse(String secretName, RequestO /** * Updates the attributes associated with a specified secret in a given key vault. - * + * * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the * secrets/set permission. @@ -772,7 +773,7 @@ public Response deleteSecretWithResponse(String secretName, RequestO * } * } * - * + * * @param secretName The name of the secret. * @param secretVersion The version of the secret. * @param parameters The parameters for update secret operation. @@ -796,7 +797,7 @@ public Mono> updateSecretWithResponseAsync(String secretNam /** * Updates the attributes associated with a specified secret in a given key vault. - * + * * The UPDATE operation changes specified attributes of an existing stored secret. Attributes that are not specified * in the request are left unchanged. The value of a secret itself cannot be changed. This operation requires the * secrets/set permission. @@ -848,7 +849,7 @@ public Mono> updateSecretWithResponseAsync(String secretNam * } * } * - * + * * @param secretName The name of the secret. * @param secretVersion The version of the secret. * @param parameters The parameters for update secret operation. @@ -870,7 +871,7 @@ public Response updateSecretWithResponse(String secretName, String s /** * Get a specified secret from a given key vault. - * + * * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get * permission. *

Query Parameters

@@ -910,7 +911,7 @@ public Response updateSecretWithResponse(String secretName, String s * } * } * - * + * * @param secretName The name of the secret. * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest * version of the secret is returned. @@ -920,7 +921,7 @@ public Response updateSecretWithResponse(String secretName, String s * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a specified secret from a given key vault. - * + * * The GET operation is applicable to any secret stored in Azure Key Vault along with {@link Response} on successful * completion of {@link Mono}. */ @@ -934,7 +935,7 @@ public Mono> getSecretWithResponseAsync(String secretName, /** * Get a specified secret from a given key vault. - * + * * The GET operation is applicable to any secret stored in Azure Key Vault. This operation requires the secrets/get * permission. *

Query Parameters

@@ -974,7 +975,7 @@ public Mono> getSecretWithResponseAsync(String secretName, * } * } * - * + * * @param secretName The name of the secret. * @param secretVersion The version of the secret. This URI fragment is optional. If not specified, the latest * version of the secret is returned. @@ -984,7 +985,7 @@ public Mono> getSecretWithResponseAsync(String secretName, * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return a specified secret from a given key vault. - * + * * The GET operation is applicable to any secret stored in Azure Key Vault along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) @@ -997,7 +998,7 @@ public Response getSecretWithResponse(String secretName, String secr /** * List secrets in a specified key vault. - * + * * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. @@ -1032,7 +1033,7 @@ public Response getSecretWithResponse(String secretName, String secr * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1052,7 +1053,7 @@ private Mono> getSecretsSinglePageAsync(RequestOptions /** * List secrets in a specified key vault. - * + * * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. @@ -1087,7 +1088,7 @@ private Mono> getSecretsSinglePageAsync(RequestOptions * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1106,7 +1107,7 @@ public PagedFlux getSecretsAsync(RequestOptions requestOptions) { /** * List secrets in a specified key vault. - * + * * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. @@ -1141,7 +1142,7 @@ public PagedFlux getSecretsAsync(RequestOptions requestOptions) { * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1160,7 +1161,7 @@ private PagedResponse getSecretsSinglePage(RequestOptions requestOpt /** * List secrets in a specified key vault. - * + * * The Get Secrets operation is applicable to the entire vault. However, only the base secret identifier and its * attributes are provided in the response. Individual secret versions are not listed in the response. This * operation requires the secrets/list permission. @@ -1195,7 +1196,7 @@ private PagedResponse getSecretsSinglePage(RequestOptions requestOpt * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1214,7 +1215,7 @@ public PagedIterable getSecrets(RequestOptions requestOptions) { /** * List all versions of the specified secret. - * + * * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. * This operations requires the secrets/list permission. *

Query Parameters

@@ -1248,7 +1249,7 @@ public PagedIterable getSecrets(RequestOptions requestOptions) { * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1270,7 +1271,7 @@ private Mono> getSecretVersionsSinglePageAsync(String /** * List all versions of the specified secret. - * + * * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. * This operations requires the secrets/list permission. *

Query Parameters

@@ -1304,7 +1305,7 @@ private Mono> getSecretVersionsSinglePageAsync(String * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1324,7 +1325,7 @@ public PagedFlux getSecretVersionsAsync(String secretName, RequestOp /** * List all versions of the specified secret. - * + * * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. * This operations requires the secrets/list permission. *

Query Parameters

@@ -1358,7 +1359,7 @@ public PagedFlux getSecretVersionsAsync(String secretName, RequestOp * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1378,7 +1379,7 @@ private PagedResponse getSecretVersionsSinglePage(String secretName, /** * List all versions of the specified secret. - * + * * The full secret identifier and attributes are provided in the response. No values are returned for the secrets. * This operations requires the secrets/list permission. *

Query Parameters

@@ -1412,7 +1413,7 @@ private PagedResponse getSecretVersionsSinglePage(String secretName, * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1432,7 +1433,7 @@ public PagedIterable getSecretVersions(String secretName, RequestOpt /** * Lists deleted secrets for the specified vault. - * + * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. *

Query Parameters

@@ -1469,7 +1470,7 @@ public PagedIterable getSecretVersions(String secretName, RequestOpt * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1489,7 +1490,7 @@ private Mono> getDeletedSecretsSinglePageAsync(Request /** * Lists deleted secrets for the specified vault. - * + * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. *

Query Parameters

@@ -1526,7 +1527,7 @@ private Mono> getDeletedSecretsSinglePageAsync(Request * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1545,7 +1546,7 @@ public PagedFlux getDeletedSecretsAsync(RequestOptions requestOption /** * Lists deleted secrets for the specified vault. - * + * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. *

Query Parameters

@@ -1582,7 +1583,7 @@ public PagedFlux getDeletedSecretsAsync(RequestOptions requestOption * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1601,7 +1602,7 @@ private PagedResponse getDeletedSecretsSinglePage(RequestOptions req /** * Lists deleted secrets for the specified vault. - * + * * The Get Deleted Secrets operation returns the secrets that have been deleted for a vault enabled for soft-delete. * This operation requires the secrets/list permission. *

Query Parameters

@@ -1638,7 +1639,7 @@ private PagedResponse getDeletedSecretsSinglePage(RequestOptions req * } * } * - * + * * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. * @throws ClientAuthenticationException thrown if the request is rejected by server on status code 401. @@ -1657,7 +1658,7 @@ public PagedIterable getDeletedSecrets(RequestOptions requestOptions /** * Gets the specified deleted secret. - * + * * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation * requires the secrets/get permission. *

Response Body Schema

@@ -1689,7 +1690,7 @@ public PagedIterable getDeletedSecrets(RequestOptions requestOptions * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1697,7 +1698,7 @@ public PagedIterable getDeletedSecrets(RequestOptions requestOptions * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the specified deleted secret. - * + * * The Get Deleted Secret operation returns the specified deleted secret along with its attributes along with * {@link Response} on successful completion of {@link Mono}. */ @@ -1711,7 +1712,7 @@ public Mono> getDeletedSecretWithResponseAsync(String secre /** * Gets the specified deleted secret. - * + * * The Get Deleted Secret operation returns the specified deleted secret along with its attributes. This operation * requires the secrets/get permission. *

Response Body Schema

@@ -1743,7 +1744,7 @@ public Mono> getDeletedSecretWithResponseAsync(String secre * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1751,7 +1752,7 @@ public Mono> getDeletedSecretWithResponseAsync(String secre * @throws ResourceNotFoundException thrown if the request is rejected by server on status code 404. * @throws ResourceModifiedException thrown if the request is rejected by server on status code 409. * @return the specified deleted secret. - * + * * The Get Deleted Secret operation returns the specified deleted secret along with its attributes along with * {@link Response}. */ @@ -1764,11 +1765,11 @@ public Response getDeletedSecretWithResponse(String secretName, Requ /** * Permanently deletes the specified secret. - * + * * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge * permission. - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1785,11 +1786,11 @@ public Mono> purgeDeletedSecretWithResponseAsync(String secretNam /** * Permanently deletes the specified secret. - * + * * The purge deleted secret operation removes the secret permanently, without the possibility of recovery. This * operation can only be enabled on a soft-delete enabled vault. This operation requires the secrets/purge * permission. - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1806,7 +1807,7 @@ public Response purgeDeletedSecretWithResponse(String secretName, RequestO /** * Recovers the deleted secret to the latest version. - * + * * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled * vault. This operation requires the secrets/recover permission. *

Response Body Schema

@@ -1835,7 +1836,7 @@ public Response purgeDeletedSecretWithResponse(String secretName, RequestO * } * } * - * + * * @param secretName The name of the deleted secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1855,7 +1856,7 @@ public Mono> recoverDeletedSecretWithResponseAsync(String s /** * Recovers the deleted secret to the latest version. - * + * * Recovers the deleted secret in the specified vault. This operation can only be performed on a soft-delete enabled * vault. This operation requires the secrets/recover permission. *

Response Body Schema

@@ -1884,7 +1885,7 @@ public Mono> recoverDeletedSecretWithResponseAsync(String s * } * } * - * + * * @param secretName The name of the deleted secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1902,7 +1903,7 @@ public Response recoverDeletedSecretWithResponse(String secretName, /** * Backs up the specified secret. - * + * * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be * downloaded. This operation requires the secrets/backup permission. *

Response Body Schema

@@ -1914,7 +1915,7 @@ public Response recoverDeletedSecretWithResponse(String secretName, * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1933,7 +1934,7 @@ public Mono> backupSecretWithResponseAsync(String secretNam /** * Backs up the specified secret. - * + * * Requests that a backup of the specified secret be downloaded to the client. All versions of the secret will be * downloaded. This operation requires the secrets/backup permission. *

Response Body Schema

@@ -1945,7 +1946,7 @@ public Mono> backupSecretWithResponseAsync(String secretNam * } * } * - * + * * @param secretName The name of the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -1963,7 +1964,7 @@ public Response backupSecretWithResponse(String secretName, RequestO /** * Restores a backed up secret to a vault. - * + * * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore * permission. *

Request Body Schema

@@ -2002,7 +2003,7 @@ public Response backupSecretWithResponse(String secretName, RequestO * } * } * - * + * * @param parameters The parameters to restore the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2023,7 +2024,7 @@ public Mono> restoreSecretWithResponseAsync(BinaryData para /** * Restores a backed up secret to a vault. - * + * * Restores a backed up secret, and all its versions, to a vault. This operation requires the secrets/restore * permission. *

Request Body Schema

@@ -2062,7 +2063,7 @@ public Mono> restoreSecretWithResponseAsync(BinaryData para * } * } * - * + * * @param parameters The parameters to restore the secret. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2081,7 +2082,7 @@ public Response restoreSecretWithResponse(BinaryData parameters, Req /** * List secrets in a specified key vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -2106,7 +2107,7 @@ public Response restoreSecretWithResponse(BinaryData parameters, Req * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2129,7 +2130,7 @@ private Mono> getSecretsNextSinglePageAsync(String nex /** * List secrets in a specified key vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -2154,7 +2155,7 @@ private Mono> getSecretsNextSinglePageAsync(String nex * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2175,7 +2176,7 @@ private PagedResponse getSecretsNextSinglePage(String nextLink, Requ /** * List all versions of the specified secret. - * + * * Get the next page of items. *

Response Body Schema

* @@ -2200,7 +2201,7 @@ private PagedResponse getSecretsNextSinglePage(String nextLink, Requ * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2223,7 +2224,7 @@ private Mono> getSecretVersionsNextSinglePageAsync(Str /** * List all versions of the specified secret. - * + * * Get the next page of items. *

Response Body Schema

* @@ -2248,7 +2249,7 @@ private Mono> getSecretVersionsNextSinglePageAsync(Str * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2269,7 +2270,7 @@ private PagedResponse getSecretVersionsNextSinglePage(String nextLin /** * Lists deleted secrets for the specified vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -2297,7 +2298,7 @@ private PagedResponse getSecretVersionsNextSinglePage(String nextLin * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. @@ -2320,7 +2321,7 @@ private Mono> getDeletedSecretsNextSinglePageAsync(Str /** * Lists deleted secrets for the specified vault. - * + * * Get the next page of items. *

Response Body Schema

* @@ -2348,7 +2349,7 @@ private Mono> getDeletedSecretsNextSinglePageAsync(Str * } * } * - * + * * @param nextLink The URL to get the next list of items. * @param requestOptions The options to configure the HTTP request before HTTP client sends it. * @throws HttpResponseException thrown if the request is rejected by server. diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java index f45828b5187fb..f357e79c9770c 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultCredentialPolicyTest.java @@ -217,6 +217,10 @@ public void failedContextChangeCannotReusePreviousToken() { KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { tokenRequests.incrementAndGet(); if (changedChallenge.get()) { + assertEquals(tenant, context.getTenantId()); + assertEquals(Arrays.asList(scope), context.getScopes()); + assertEquals(claims, context.getClaims()); + assertTrue(context.isCaeEnabled()); throw new IllegalStateException("Token acquisition failed."); } return new AccessToken("previous-context-token", OffsetDateTime.now().plusHours(1)); @@ -253,6 +257,69 @@ private static HttpResponse sendTokenCacheRequest(HttpPipeline pipeline, String () -> pipeline.send(request, Context.NONE)); } + @SyncAsyncTest + public void challengedContextSurvivesFailedAcquisitionAndRetry() { + for (boolean disableVerification : new boolean[] { false, true }) { + for (boolean changeTenantAndScope : new boolean[] { false, true }) { + KeyVaultCredentialPolicy.clearCache(); + AtomicBoolean challenged = new AtomicBoolean(); + AtomicBoolean independentRequest = new AtomicBoolean(); + AtomicInteger tokenRequests = new AtomicInteger(); + AtomicInteger challengedTokenRequests = new AtomicInteger(); + String tenant = changeTenantAndScope ? "second" : "first"; + String scope = changeTenantAndScope ? "https://azure.net/.default" : "https://vault.azure.net/.default"; + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> Mono.fromSupplier(() -> { + tokenRequests.incrementAndGet(); + assertEquals(challenged.get() ? tenant : "first", context.getTenantId()); + assertEquals(Arrays.asList(challenged.get() ? scope : "https://vault.azure.net/.default"), + context.getScopes()); + assertTrue(context.isCaeEnabled()); + assertEquals(challenged.get() && !independentRequest.get() ? DECODED_CLAIMS : null, + context.getClaims()); + if (challenged.get() && !independentRequest.get()) { + if (challengedTokenRequests.incrementAndGet() == 1) { + context.getScopes().clear(); + context.setTenantId("credential-mutated").setClaims("mutated").setCaeEnabled(false); + throw new IllegalStateException("Transient challenged token acquisition failure."); + } + return new AccessToken("claims-token", OffsetDateTime.now().plusHours(1)); + } + return new AccessToken("ordinary-token", OffsetDateTime.now().plusHours(1)); + }), disableVerification); + HttpPipeline pipeline = new HttpPipelineBuilder() + .policies(new RetryPolicy(new FixedDelay(2, Duration.ofMillis(1))), policy) + .httpClient(request -> { + String authorization = request.getHeaders().getValue(AUTHORIZATION); + if ("/changed".equals(request.getUrl().getPath())) { + if (challenged.compareAndSet(false, true)) { + assertEquals("Bearer ordinary-token", authorization); + return Mono.just(tokenCacheChallenge(request, tenant, scope, DECODED_CLAIMS)); + } + assertEquals("Bearer claims-token", authorization); + } else if (authorization == null) { + return Mono + .just(tokenCacheChallenge(request, "first", "https://vault.azure.net/.default", null)); + } else { + assertEquals("Bearer ordinary-token", authorization); + } + return Mono.just(new MockHttpResponse(request, 200)); + }) + .build(); + + assertEquals(200, sendTokenCacheRequest(pipeline, "https://first.vault.azure.net").getStatusCode()); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/changed").getStatusCode()); + assertEquals(2, challengedTokenRequests.get()); + assertEquals(3, tokenRequests.get()); + + independentRequest.set(true); + assertEquals(200, + sendTokenCacheRequest(pipeline, "https://first.vault.azure.net/independent").getStatusCode()); + assertEquals(4, tokenRequests.get(), "Claims must not leak into a separate request."); + } + } + } + @SyncAsyncTest public void originScopedTokensSupportRetriesAndNormalization() { AtomicInteger firstTokenRequests = new AtomicInteger(); @@ -341,6 +408,52 @@ private static HttpResponse tokenCacheChallenge(HttpRequest request, String tena return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, challenge)); } + @Test + public void concurrentChallengeCannotReplaceRequestLocalRetryContext() { + Sinks.One pendingToken = Sinks.one(); + AtomicInteger firstAcquisitions = new AtomicInteger(); + AtomicInteger secondAcquisitions = new AtomicInteger(); + KeyVaultCredentialPolicy policy = new KeyVaultCredentialPolicy(context -> { + boolean first = "first".equals(context.getTenantId()); + assertEquals(first ? "first" : "second", context.getTenantId()); + assertEquals(Arrays.asList(first ? "https://vault.azure.net/.default" : "https://azure.net/.default"), + context.getScopes()); + assertEquals(first ? DECODED_CLAIMS : "{}", context.getClaims()); + assertTrue(context.isCaeEnabled()); + if (first && firstAcquisitions.incrementAndGet() == 1) { + return pendingToken.asMono(); + } + if (!first) { + secondAcquisitions.incrementAndGet(); + } + return Mono + .just(new AccessToken(first ? "first-token" : "second-token", OffsetDateTime.now().plusHours(1))); + }, false); + HttpPipelineCallContext first + = createCallContext(new HttpRequest(HttpMethod.GET, "https://same.vault.azure.net/first"), Context.NONE); + HttpPipelineCallContext second + = createCallContext(new HttpRequest(HttpMethod.GET, "https://same.vault.azure.net/second"), Context.NONE); + HttpResponse firstChallenge + = tokenCacheChallenge(first.getHttpRequest(), "first", "https://vault.azure.net/.default", DECODED_CLAIMS); + HttpResponse secondChallenge + = tokenCacheChallenge(second.getHttpRequest(), "second", "https://azure.net/.default", "{}"); + + StepVerifier + .create(policy.authorizeRequestOnChallenge(first, firstChallenge) + .onErrorResume(IllegalStateException.class, error -> policy.authorizeRequest(first).thenReturn(true))) + .then(() -> { + assertTrue(policy.authorizeRequestOnChallengeSync(second, secondChallenge)); + pendingToken.tryEmitError(new IllegalStateException("Transient acquisition failure.")); + }) + .expectNext(true) + .expectComplete() + .verify(Duration.ofSeconds(5)); + assertEquals(2, firstAcquisitions.get()); + assertEquals(1, secondAcquisitions.get()); + assertEquals("Bearer first-token", first.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + assertEquals("Bearer second-token", second.getHttpRequest().getHeaders().getValue(AUTHORIZATION)); + } + @SyncAsyncTest public void cachedChallengeIsBoundToRequestOrigin() { AtomicInteger tokenRequests = new AtomicInteger(); diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java index cc6e93fa578a4..d7ca5071c387b 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/KeyVaultPaginationTest.java @@ -10,25 +10,31 @@ import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpPipelineBuilder; import com.azure.core.http.policy.BearerTokenAuthenticationPolicy; +import com.azure.core.http.policy.FixedDelayOptions; +import com.azure.core.http.policy.RetryOptions; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.test.SyncAsyncExtension; import com.azure.core.test.annotation.SyncAsyncTest; import com.azure.core.test.http.MockHttpResponse; +import com.azure.core.test.models.TestProxySanitizer; import com.azure.security.keyvault.secrets.implementation.KeyVaultCredentialPolicy; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import reactor.core.publisher.Mono; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.time.OffsetDateTime; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.regex.Pattern; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -42,6 +48,7 @@ public class KeyVaultPaginationTest { private final AtomicInteger authorizedSends = new AtomicInteger(); private final AtomicInteger customPolicyCalls = new AtomicInteger(); private final AtomicReference responseNextLink = new AtomicReference<>(); + private final AtomicReference challengeResource = new AtomicReference<>("https://vault.azure.net"); private final AtomicReference lastRequestUrl = new AtomicReference<>(); @AfterEach @@ -49,6 +56,22 @@ public void cleanup() { KeyVaultCredentialPolicy.clearCache(); } + @Test + public void playbackSanitizerOnlyRewritesRecordedOrigin() { + TestProxySanitizer sanitizer = SecretClientTestBase.playbackNextLinkSanitizer("https://localhost:8080/base"); + Pattern pattern = Pattern.compile(sanitizer.getRegex()); + String suffix = "secrets/name%2Fpart?api-version=7.6&skiptoken=a%2Bb%3D"; + for (String origin : Arrays.asList("https://REDACTED:443/", "HTTPS://redacted/")) { + assertEquals("https://localhost:8080/" + suffix, + pattern.matcher(origin + suffix).replaceFirst(sanitizer.getRedactedValue())); + } + for (String origin : Arrays.asList("https://other.example/", "http://REDACTED/", "https://REDACTED:8443/", + "https://REDACTED.other.example/", "https://user@REDACTED/", "https://REDACTED@other.example/")) { + assertEquals(origin + suffix, pattern.matcher(origin + suffix).replaceFirst(sanitizer.getRedactedValue())); + } + assertEquals("$.nextLink", sanitizer.getKey()); + } + @SyncAsyncTest public void allContinuationOperationsValidateBeforePipeline() { for (boolean customPipeline : new boolean[] { false, true }) { @@ -100,13 +123,96 @@ public void serviceProvidedContinuationIsValidated() { @SyncAsyncTest public void configuredCloudAndCustomOriginsAreSupported() { for (String endpoint : Arrays.asList("https://paging.vault.usgovcloudapi.net", "https://paging.vault.azure.cn", - "https://vault.example:8443", "https://localhost:443", "HTTPS://PAGING.VAULT.AZURE.NET:443")) { + "https://vault.example:8443", "https://localhost:443", "HTTPS://PAGING.VAULT.AZURE.NET:443", + "https://vault.example.:8443", "https://vault.xn--bcher-kva.example:8443")) { SecretClientBuilder builder = builder(endpoint, false, true); assertEquals(1, readPages(builder.buildClient().listPropertiesOfSecrets(), builder.buildAsyncClient().listPropertiesOfSecrets(), endpoint + "/secrets?skip=1")); } } + @SyncAsyncTest + public void validCloudAndCustomChallengesWorkWithVerificationEnabled() { + String[][] endpoints = { + { "https://paging.vault.azure.net", "https://vault.azure.net" }, + { "https://paging.vault.usgovcloudapi.net", "https://vault.usgovcloudapi.net" }, + { "https://paging.vault.azure.cn", "https://vault.azure.cn" }, + { "https://paging.vault.microsoftazure.de", "https://vault.microsoftazure.de" }, + { "https://vault.arbitrary.example:8443", "https://arbitrary.example" } }; + for (boolean disableVerification : new boolean[] { false, true }) { + for (String[] endpoint : endpoints) { + KeyVaultCredentialPolicy.clearCache(); + challengeResource.set(endpoint[1]); + SecretClientBuilder builder = builder(endpoint[0], false, disableVerification); + assertEquals(1, readPages(builder.buildClient().listPropertiesOfSecrets(), + builder.buildAsyncClient().listPropertiesOfSecrets(), endpoint[0] + "/secrets?skip=1")); + } + } + } + + @SyncAsyncTest + public void defaultResourceVerificationDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(false); + } + + @SyncAsyncTest + public void verificationOptOutDoesNotAuthorizeForeignContinuation() { + assertValidChallengeCannotAuthorizeForeignContinuation(true); + } + + private void assertValidChallengeCannotAuthorizeForeignContinuation(boolean disableVerification) { + SecretClientBuilder original = builder(ENDPOINT, false, disableVerification); + SecretClient client = original.buildClient(); + SecretAsyncClient asyncClient = original.buildAsyncClient(); + assertEquals(1, readPages(client.listPropertiesOfSecrets(), asyncClient.listPropertiesOfSecrets(), null)); + + String otherOrigin = "https://other.vault.azure.net"; + SecretClientBuilder other = builder(otherOrigin, false, disableVerification); + // The existing challenge-resource rule accepts this other vault, but it is not our configured origin. + assertEquals(1, readPages(other.buildClient().listPropertiesOfSecrets(), + other.buildAsyncClient().listPropertiesOfSecrets(), null)); + int previousTokens = tokenRequests.get(); + int previousSends = sends.get(); + assertThrows(IllegalArgumentException.class, () -> readPages(client.listPropertiesOfSecrets(), + asyncClient.listPropertiesOfSecrets(), otherOrigin + "/secrets?skip=1")); + assertEquals(previousTokens, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + + @SyncAsyncTest + public void verificationOptOutChangesOnlyChallengeResourceValidation() { + String endpoint = "https://vault.example:8443"; + SecretClientBuilder verified = builder(endpoint, false, false); + RuntimeException rejected + = assertThrows(RuntimeException.class, () -> readPages(verified.buildClient().listPropertiesOfSecrets(), + verified.buildAsyncClient().listPropertiesOfSecrets(), endpoint + "/secrets")); + assertTrue(rejected.getMessage().contains("challenge resource")); + assertEquals(0, tokenRequests.get()); + assertEquals(1, sends.get()); + + SecretClientBuilder optedOut = builder(endpoint, false, true); + SecretClient client = optedOut.buildClient(); + SecretAsyncClient asyncClient = optedOut.buildAsyncClient(); + assertEquals(1, + readPages(client.listPropertiesOfSecrets(), asyncClient.listPropertiesOfSecrets(), endpoint + "/secrets")); + assertEquals(1, tokenRequests.get()); + int previousSends = sends.get(); + for (boolean disableVerification : new boolean[] { false, true }) { + String insecureEndpoint = "http://vault.example:8443"; + SecretClientBuilder insecure = builder(insecureEndpoint, false, disableVerification); + RuntimeException insecureRejected + = assertThrows(RuntimeException.class, () -> readPages(insecure.buildClient().listPropertiesOfSecrets(), + insecure.buildAsyncClient().listPropertiesOfSecrets(), insecureEndpoint + "/secrets")); + assertTrue(insecureRejected.getMessage().contains("HTTPS")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + assertThrows(IllegalArgumentException.class, () -> readPages(client.listPropertiesOfSecrets(), + asyncClient.listPropertiesOfSecrets(), "https://other.example:8443/secrets")); + assertEquals(1, tokenRequests.get()); + assertEquals(previousSends, sends.get()); + } + @SyncAsyncTest public void normalizedContinuationRetainsPathAndQuery() { SecretClientBuilder builder = builder("HTTPS://PAGING.VAULT.AZURE.NET:443", false, false); @@ -122,6 +228,25 @@ public void normalizedContinuationRetainsPathAndQuery() { } } + @SyncAsyncTest + public void customUnauthenticatedPipelineSupportsSameOriginHttp() { + SecretClientBuilder builder = new SecretClientBuilder().vaultUrl("http://localhost") + .pipeline(new HttpPipelineBuilder().httpClient(request -> { + sends.incrementAndGet(); + assertEquals("http", request.getUrl().getProtocol()); + return Mono.just(new MockHttpResponse(request, 200, + new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), + "{\"value\":[]}".getBytes(StandardCharsets.UTF_8))); + }).build()); + SecretClient client = builder.buildClient(); + SecretAsyncClient asyncClient = builder.buildAsyncClient(); + assertEquals(1, readPages(client.listPropertiesOfSecrets(), asyncClient.listPropertiesOfSecrets(), + "HTTP://LOCALHOST:80/secrets?skip=1")); + assertThrows(IllegalArgumentException.class, () -> readPages(client.listPropertiesOfSecrets(), + asyncClient.listPropertiesOfSecrets(), "https://localhost/secrets?skip=1")); + assertEquals(1, sends.get()); + } + private void assertRejectedContinuations(PagedIterable sync, PagedFlux async) { for (String nextLink : Arrays.asList("https://other.example/secrets", "https://other.vault.azure.net/secrets", "http://paging.vault.azure.net/secrets", ENDPOINT + ":8443/secrets", @@ -159,8 +284,10 @@ private SecretClientBuilder builder(String endpoint, boolean customPipeline, boo sends.incrementAndGet(); String authorization = request.getHeaders().getValue(HttpHeaderName.AUTHORIZATION); if (authorization == null) { - return new MockHttpResponse(request, 401, new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, - "Bearer authorization=\"https://login.example/tenant\", resource=\"https://vault.azure.net\"")); + return new MockHttpResponse(request, 401, + new HttpHeaders().set(HttpHeaderName.WWW_AUTHENTICATE, + "Bearer authorization=\"https://login.example/tenant\", resource=\"" + challengeResource.get() + + "\"")); } assertEquals("Bearer fake-key-vault-token", authorization); authorizedSends.incrementAndGet(); @@ -170,8 +297,10 @@ private SecretClientBuilder builder(String endpoint, boolean customPipeline, boo new HttpHeaders().set(HttpHeaderName.CONTENT_TYPE, "application/json"), body.getBytes(StandardCharsets.UTF_8)); }); - SecretClientBuilder builder - = new SecretClientBuilder().vaultUrl(endpoint).credential(credential).httpClient(httpClient); + SecretClientBuilder builder = new SecretClientBuilder().vaultUrl(endpoint) + .credential(credential) + .httpClient(httpClient) + .retryOptions(new RetryOptions(new FixedDelayOptions(0, Duration.ofMillis(1)))); if (disableVerification) { builder.disableChallengeResourceVerification(); } diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java index f2271f3088811..2932abd28e83a 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/SecretClientTestBase.java @@ -13,6 +13,8 @@ import com.azure.core.test.models.BodilessMatcher; import com.azure.core.test.models.CustomMatcher; import com.azure.core.test.models.TestProxyRequestMatcher; +import com.azure.core.test.models.TestProxySanitizer; +import com.azure.core.test.models.TestProxySanitizerType; import com.azure.core.test.utils.MockTokenCredential; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; @@ -24,6 +26,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.params.provider.Arguments; +import java.net.URI; import java.time.Duration; import java.time.OffsetDateTime; import java.time.ZoneOffset; @@ -88,6 +91,7 @@ SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, .httpClient(httpClient); if (interceptorManager.isPlaybackMode()) { + interceptorManager.addSanitizers(Collections.singletonList(playbackNextLinkSanitizer(endpoint))); return builder.retryOptions(PLAYBACK_RETRY_OPTIONS); } else { builder.retryOptions(LIVE_RETRY_OPTIONS); @@ -98,6 +102,12 @@ SecretClientBuilder getClientBuilder(HttpClient httpClient, String testTenantId, } } + static TestProxySanitizer playbackNextLinkSanitizer(String endpoint) { + // Only the origin used in the pinned recordings is translated; retain the complete path and query. + return new TestProxySanitizer("$.nextLink", "(?i)^https://REDACTED(?::443)?/", + URI.create(endpoint).resolve("/").toString(), TestProxySanitizerType.BODY_KEY); + } + @Test public abstract void setSecret(HttpClient httpClient, SecretServiceVersion serviceVersion); diff --git a/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidationTest.java b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidationTest.java new file mode 100644 index 0000000000000..1fb7a5d216d43 --- /dev/null +++ b/sdk/keyvault/azure-security-keyvault-secrets/src/test/java/com/azure/security/keyvault/secrets/implementation/KeyVaultEndpointValidationTest.java @@ -0,0 +1,62 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.security.keyvault.secrets.implementation; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class KeyVaultEndpointValidationTest { + @Test + public void acceptsSameOriginAbsoluteHttpUrlsWithoutChangingContinuation() { + // URI-level coverage only, not a guarantee of transport support for every host syntax. + String[][] origins = { + { "https://vault.azure.net", "HTTPS://VAULT.AZURE.NET:443" }, + { "https://vault.usgovcloudapi.net:443", "https://VAULT.USGOVCLOUDAPI.NET" }, + { "https://vault.azure.cn", "https://vault.azure.cn:443" }, + { "https://vault.managedhsm.azure.net", "https://VAULT.MANAGEDHSM.AZURE.NET:443" }, + { "https://arbitrary.example:8443", "HTTPS://ARBITRARY.EXAMPLE:8443" }, + { "https://localhost", "https://LOCALHOST:443" }, + { "https://127.0.0.1:8443", "https://127.0.0.1:8443" }, + { "https://[2001:db8::a]", "https://[2001:DB8::A]:443" }, + { "https://xn--bcher-kva.example.", "https://XN--BCHER-KVA.EXAMPLE.:443" }, + { "http://localhost", "HTTP://LOCALHOST:80" }, + { "http://localhost:8080", "http://LOCALHOST:8080" } }; + for (String[] origin : origins) { + String nextLink = origin[1] + "/path%2Fpart/../page?skip=a%2Bb%3D&value=%23&empty="; + assertEquals(nextLink, KeyVaultEndpointValidation.validateNextLink(nextLink, origin[0] + "/base/")); + assertEquals(KeyVaultEndpointValidation.getOrigin(origin[0]), + KeyVaultEndpointValidation.getOrigin(origin[1])); + } + } + + @Test + public void rejectsForeignOrMalformedOrigins() { + assertThrows(IllegalArgumentException.class, + () -> KeyVaultEndpointValidation.getOrigin("https://b\u00fccher.example")); + String endpoint = "https://vault.example"; + String[] continuations = { + "https://other.example/page", + "http://vault.example/page", + "https://vault.example:8443/page", + "https://vault.example.other.example/page", + "https://user@vault.example/page", + "https://vault.example@other.example/page", + "https://vault.example:invalid/page", + "https://vault.example:65536/page", + "https://vault.example:-2/page", + "https://vault.example/bad path", + "https://vault.example/page#fragment", + "https://vault.example/page?bad=%xy", + "/page", + "//vault.example/page", + "https:///page", + "file://vault.example/page" }; + for (String continuation : continuations) { + assertThrows(IllegalArgumentException.class, + () -> KeyVaultEndpointValidation.validateNextLink(continuation, endpoint), continuation); + } + } +}