Repository navigation
[PROTOTYPE][Do Not Merge] External Evaluation (Invoke) policy for azure-core-management #49701
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
Weidong Xu (weidongxu-microsoft)
wants to merge
12
commits into
Azure:main
Choose a base branch
from
weidongxu-microsoft:core-mgmt-external-evaluation-policy
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
548252a
Add External Evaluation (Invoke) policy to azure-core-management (1st…
weidongxu-microsoft 9df5b12
Add copied storage management client as E2E test fixture
weidongxu-microsoft 9d1d534
Add end-to-end test for ExternalEvaluationPolicy and fix retry header…
weidongxu-microsoft ab59447
Re-surface original 403 as ManagementException when policy token acqu…
weidongxu-microsoft c84049b
Tighten E2E mock-service assertions on request URL, method, and exact…
weidongxu-microsoft b23ab96
Assert exact UTF-8 acquire request body instead of JSON-path matching
weidongxu-microsoft e7974c3
Add ExternalEvaluationPolicy via manager Configurable.withPolicy in E…
weidongxu-microsoft 373ad17
Rename E2E wrapper variable to policyTokenCredential
weidongxu-microsoft 8297be7
Rename PolicyTokenCredential to PolicyTokenProvider
weidongxu-microsoft 371bb1e
Broaden trigger to all non-GET methods and add header loop guard
weidongxu-microsoft 09c020d
Revise external evaluation policy flow
weidongxu-microsoft 7579645
Merge upstream main into external evaluation prototype
weidongxu-microsoft File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
401 changes: 401 additions & 0 deletions
401
...agement/src/main/java/com/azure/core/management/http/policy/ExternalEvaluationPolicy.java
Large diffs are not rendered by default.
Oops, something went wrong.
127 changes: 127 additions & 0 deletions
127
...n/java/com/azure/core/management/implementation/evaluation/MissingPolicyTokenDetails.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } | ||
| } |
7 changes: 7 additions & 0 deletions
7
...ement/src/main/java/com/azure/core/management/implementation/evaluation/package-info.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; |
163 changes: 163 additions & 0 deletions
163
...src/test/java/com/azure/core/management/http/policy/ExternalEvaluationPolicyE2ETests.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.