Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sdk/core/azure-core-management/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

### Features Added

- Added `ExternalEvaluationPolicy` to support the Azure Policy external evaluation ("Invoke") flow. When every
blocking policy violation requires a policy token, the policy acquires one through the client pipeline and retries
the operation.
Comment thread
weidongxu-microsoft marked this conversation as resolved.
Resolved

### Breaking Changes

### Bugs Fixed
Expand Down
12 changes: 12 additions & 0 deletions sdk/core/azure-core-management/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,12 @@
<jacoco.min.branchcoverage>0.21</jacoco.min.branchcoverage>
<jacoco.min.linecoverage>0.24</jacoco.min.linecoverage>
<javaModulesSurefireArgLine>
--add-reads com.azure.core.management=com.azure.http.netty
--add-reads com.azure.core.management=io.netty.handler
--add-reads com.azure.core.management=reactor.netty.http
--add-opens com.azure.core.management/com.azure.core.management.implementation.polling=ALL-UNNAMED
--add-opens com.azure.core.management/com.azure.resourcemanager.storage.models=com.azure.core,com.azure.json
--add-opens com.azure.core.management/com.azure.resourcemanager.storage.fluent.models=com.azure.core,com.azure.json
</javaModulesSurefireArgLine>

<!-- Enables fail on deprecated API usage. -->
Expand Down Expand Up @@ -112,5 +117,12 @@
<version>1.27.0-beta.21</version> <!-- {x-version-update;com.azure:azure-core-test;current} -->
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8-standalone</artifactId>
<version>2.35.2</version> <!-- {x-version-update;com.github.tomakehurst:wiremock-jre8-standalone;external_dependency} -->
<scope>test</scope>
</dependency>

</dependencies>
</project>

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.management.implementation.evaluation;

import com.azure.core.util.logging.ClientLogger;
import com.azure.json.JsonProviders;
import com.azure.json.JsonReader;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
* Internal representation of the external evaluation details returned in a policy-denied response.
*/
public final class MissingPolicyTokenDetails {
private static final ClientLogger LOGGER = new ClientLogger(MissingPolicyTokenDetails.class);

private static final String ERROR = "error";
private static final String CODE = "code";
private static final String REQUEST_DISALLOWED_BY_POLICY = "RequestDisallowedByPolicy";
private static final String ADDITIONAL_INFO = "additionalInfo";
private static final String TYPE = "type";
private static final String POLICY_VIOLATION = "PolicyViolation";
private static final String INFO = "info";
private static final String EVALUATION_DETAILS = "evaluationDetails";
private static final String MISSING_POLICY_TOKEN_DETAILS = "missingPolicyTokenDetails";
private static final String SHOULD_DENY = "shouldDeny";
private static final String IS_CHANGE_REFERENCE_REQUIRED = "isChangeReferenceRequired";

private final boolean changeReferenceRequired;

private MissingPolicyTokenDetails(boolean changeReferenceRequired) {
this.changeReferenceRequired = changeReferenceRequired;
}

/**
* Whether the service requires a change-safety reference to acquire the policy token.
*
* @return whether a change reference is required.
*/
public boolean isChangeReferenceRequired() {
return changeReferenceRequired;
}

/**
* Parses an actionable external evaluation response.
* <p>
* A response is actionable only when it is a {@code RequestDisallowedByPolicy} error containing at least one
* {@code PolicyViolation}, and every policy violation contains
* {@code evaluationDetails.missingPolicyTokenDetails.shouldDeny=true}.
*
* @param body the raw response body.
* @return the aggregated details, or {@code null} when token acquisition should not be attempted.
*/
@SuppressWarnings("unchecked")
public static MissingPolicyTokenDetails parse(byte[] body) {
if (body == null || body.length == 0) {
return null;
}

try (JsonReader jsonReader = JsonProviders.createReader(body)) {
Object rootValue = jsonReader.readUntyped();
if (!(rootValue instanceof Map)) {
return null;
}

Object errorValue = ((Map<String, Object>) rootValue).get(ERROR);
if (!(errorValue instanceof Map)) {
return null;
}
Map<String, Object> error = (Map<String, Object>) errorValue;
if (!REQUEST_DISALLOWED_BY_POLICY.equalsIgnoreCase(asString(error.get(CODE)))) {
return null;
}

Object additionalInfoValue = error.get(ADDITIONAL_INFO);
if (!(additionalInfoValue instanceof List)) {
return null;
}

boolean foundPolicyViolation = false;
boolean changeReferenceRequired = false;
for (Object additionalInfoEntry : (List<Object>) additionalInfoValue) {
if (!(additionalInfoEntry instanceof Map)) {
continue;
}

Map<String, Object> additionalInfo = (Map<String, Object>) additionalInfoEntry;
if (!POLICY_VIOLATION.equalsIgnoreCase(asString(additionalInfo.get(TYPE)))) {
continue;
}

foundPolicyViolation = true;
Map<String, Object> missingTokenDetails = getMissingTokenDetails(additionalInfo.get(INFO));
if (missingTokenDetails == null || !Boolean.TRUE.equals(missingTokenDetails.get(SHOULD_DENY))) {
return null;
}
changeReferenceRequired |= Boolean.TRUE.equals(missingTokenDetails.get(IS_CHANGE_REFERENCE_REQUIRED));
}

return foundPolicyViolation ? new MissingPolicyTokenDetails(changeReferenceRequired) : null;
} catch (IOException | RuntimeException ex) {
LOGGER.verbose("Failed to parse the policy violation details from the response body.", ex);
return null;
}
}

@SuppressWarnings("unchecked")
private static Map<String, Object> getMissingTokenDetails(Object infoValue) {
if (!(infoValue instanceof Map)) {
return null;
}
Object evaluationDetailsValue = ((Map<String, Object>) infoValue).get(EVALUATION_DETAILS);
if (!(evaluationDetailsValue instanceof Map)) {
return null;
}
Object missingTokenDetailsValue
= ((Map<String, Object>) evaluationDetailsValue).get(MISSING_POLICY_TOKEN_DETAILS);
return missingTokenDetailsValue instanceof Map ? (Map<String, Object>) missingTokenDetailsValue : null;
}

private static String asString(Object value) {
return value instanceof String ? (String) value : null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

/**
* Package containing internal implementation types for the Azure Policy external evaluation ("Invoke") flow.
*/
package com.azure.core.management.implementation.evaluation;
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.core.management.http.policy;

import com.azure.core.credential.AccessToken;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.HttpClient;
import com.azure.core.http.netty.NettyAsyncHttpClientBuilder;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.resourcemanager.storage.StorageManager;
import com.azure.resourcemanager.storage.fluent.models.StorageAccountInner;
import com.azure.resourcemanager.storage.models.Kind;
import com.azure.resourcemanager.storage.models.Sku;
import com.azure.resourcemanager.storage.models.SkuName;
import com.azure.resourcemanager.storage.models.StorageAccountCreateParameters;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;

import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.Map;

import static com.github.tomakehurst.wiremock.client.WireMock.absent;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.matching;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.postRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.put;
import static com.github.tomakehurst.wiremock.client.WireMock.putRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.wireMockConfig;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

/**
* End-to-end test for {@link ExternalEvaluationPolicy} that exercises the full external evaluation ("Invoke") flow
* against a real generated Storage management client, with Azure Resource Manager faked by WireMock.
*/
public class ExternalEvaluationPolicyE2ETests {
private static final String SUBSCRIPTION_ID = "00000000-0000-0000-0000-000000000000";
private static final String RESOURCE_GROUP = "rg";
private static final String ACCOUNT_NAME = "acct";
private static final String POLICY_TOKEN_VALUE = "PoP eyJhbGciOiJSUzI1NiJ9.policy-token-value";
private static final String EE_HEADER = "x-ms-policy-external-evaluations";

private static final String STORAGE_PATH = "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP
+ "/providers/Microsoft.Storage/storageAccounts/" + ACCOUNT_NAME;
private static final String ACQUIRE_PATH = "/subscriptions/" + SUBSCRIPTION_ID + "/resourceGroups/" + RESOURCE_GROUP
+ "/providers/Microsoft.Authorization/acquirePolicyToken";

private static final String DENY_BODY = "{\"error\":{\"code\":\"RequestDisallowedByPolicy\","
+ "\"message\":\"Resource was disallowed by policy.\",\"additionalInfo\":[{\"type\":\"PolicyViolation\","
+ "\"info\":{\"evaluationDetails\":{\"missingPolicyTokenDetails\":{\"shouldDeny\":true,"
+ "\"endpointKind\":\"AzureResourceGraph\",\"isChangeReferenceRequired\":false}}}}]}}";

private static final String STORAGE_BODY = "{\"id\":\"" + STORAGE_PATH + "\",\"name\":\"" + ACCOUNT_NAME + "\","
+ "\"type\":\"Microsoft.Storage/storageAccounts\",\"location\":\"eastus\","
+ "\"properties\":{\"provisioningState\":\"Succeeded\"}}";

private static final String ACQUIRE_BODY = "{\"result\":\"Succeeded\",\"token\":\"" + POLICY_TOKEN_VALUE + "\","
+ "\"tokenId\":\"11111111-1111-1111-1111-111111111111\"}";

// The exact JSON body the Storage create operation serializes for the parameters built below. The External
// Evaluation flow requires the retried request body to be byte-for-byte identical to the original, so the mock
// service asserts on this exact string for both the denied and the retried PUT.
private static final String EXPECTED_REQUEST_BODY
= "{\"sku\":{\"name\":\"Standard_LRS\"},\"kind\":\"StorageV2\",\"location\":\"eastus\"}";

private static final String API_VERSION = "2026-04-01";

@Test
public void endToEndAcquireAndRetry() throws Exception {
// The manager's Configurable pipeline adds a BearerTokenAuthenticationPolicy, which requires HTTPS, so the
// mock service is served over TLS and the clients trust its self-signed certificate.
WireMockServer server = new WireMockServer(wireMockConfig().dynamicHttpsPort());
server.start();
try {
String endpoint = "https://localhost:" + server.httpsPort();
HttpClient httpClient = trustAllHttpClient();

// The exact UTF-8 acquire request body includes the guarded request body verbatim.
String expectedAcquireBody = "{\"operation\":{\"uri\":\"" + endpoint + STORAGE_PATH + "?api-version="
+ API_VERSION + "\",\"httpMethod\":\"PUT\",\"content\":" + EXPECTED_REQUEST_BODY + "}}";

// Guarded operation is denied when the external evaluation header is absent. The mock service asserts the
// method (PUT), the exact URL path, and the exact request body.
server.stubFor(put(urlPathEqualTo(STORAGE_PATH)).withHeader(EE_HEADER, absent())
.withRequestBody(equalTo(EXPECTED_REQUEST_BODY))
.willReturn(
aResponse().withStatus(403).withHeader("Content-Type", "application/json").withBody(DENY_BODY)));

// Guarded operation succeeds once the acquired policy token is applied. The retried request must carry the
// token header and a byte-for-byte identical body, so the mock service asserts on the exact body again.
server.stubFor(put(urlPathEqualTo(STORAGE_PATH)).withHeader(EE_HEADER, matching(".+"))
.withRequestBody(equalTo(EXPECTED_REQUEST_BODY))
.willReturn(
aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(STORAGE_BODY)));

// The acquirePolicyToken API issues the token. The mock service asserts the exact UTF-8 request body: the
// operation echoed to it must match the guarded request byte-for-byte (uri, method, and content).
server.stubFor(post(urlPathEqualTo(ACQUIRE_PATH)).withQueryParam("api-version", equalTo("2026-07-01"))
.withRequestBody(equalTo(expectedAcquireBody))
.willReturn(
aResponse().withStatus(200).withHeader("Content-Type", "application/json").withBody(ACQUIRE_BODY)));

Map<String, String> endpoints = new HashMap<>();
endpoints.put(AzureEnvironment.Endpoint.MANAGEMENT.identifier(), endpoint);
endpoints.put(AzureEnvironment.Endpoint.RESOURCE_MANAGER.identifier(), endpoint);
endpoints.put(AzureEnvironment.Endpoint.ACTIVE_DIRECTORY.identifier(), endpoint);
AzureProfile profile = new AzureProfile("tenant", SUBSCRIPTION_ID, new AzureEnvironment(endpoints));

// The guarded client opts in by adding the policy to its pipeline. A dummy credential is enough because
// the mock service does not assert on the Authorization header.
TokenCredential credential
= request -> Mono.just(new AccessToken("dummy-token", OffsetDateTime.now().plusHours(1)));
StorageManager storageManager = StorageManager.configure()
.withHttpClient(httpClient)
.withPolicy(new ExternalEvaluationPolicy())
.authenticate(credential, profile);

StorageAccountInner result = storageManager.serviceClient()
.getResourceProviders()
.create(RESOURCE_GROUP, ACCOUNT_NAME,
new StorageAccountCreateParameters().withSku(new Sku().withName(SkuName.STANDARD_LRS))
.withKind(Kind.STORAGE_V2)
.withLocation("eastus"));

assertNotNull(result);
assertEquals(ACCOUNT_NAME, result.name());
// The guarded operation is sent twice against the exact URL and method, each carrying the exact same body:
// once denied (no token header) and once retried with the acquired token.
server.verify(2,
putRequestedFor(urlPathEqualTo(STORAGE_PATH)).withRequestBody(equalTo(EXPECTED_REQUEST_BODY)));
server.verify(1, putRequestedFor(urlPathEqualTo(STORAGE_PATH)).withHeader(EE_HEADER, absent())
.withRequestBody(equalTo(EXPECTED_REQUEST_BODY)));
server.verify(1,
putRequestedFor(urlPathEqualTo(STORAGE_PATH)).withHeader(EE_HEADER, equalTo(POLICY_TOKEN_VALUE))
.withRequestBody(equalTo(EXPECTED_REQUEST_BODY)));
// The token is acquired exactly once, with the operation echoing the guarded request verbatim.
server.verify(1,
postRequestedFor(urlPathEqualTo(ACQUIRE_PATH)).withQueryParam("api-version", equalTo("2026-07-01"))
.withRequestBody(equalTo(expectedAcquireBody)));
} finally {
server.stop();
}
}

// Builds a Netty HTTP client that trusts any certificate, so the clients can talk to the self-signed HTTPS mock.
private static HttpClient trustAllHttpClient() throws Exception {
SslContext sslContext
= SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
reactor.netty.http.client.HttpClient reactorClient
= reactor.netty.http.client.HttpClient.create().secure(spec -> spec.sslContext(sslContext));
return new NettyAsyncHttpClientBuilder(reactorClient).build();
}
}
Loading
Loading