-
Notifications
You must be signed in to change notification settings - Fork 57
[ChangeSafety] Phase 1: AcquirePolicyToken Support #449
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <Import Project="$(ProjectDir)..\Dependencies.Test.targets" /> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net8.0</TargetFramework> | ||
| <AssemblyName>Microsoft.Azure.PowerShell.Common.Test</AssemblyName> | ||
| <OutputPath>$(ProjectDir)..\..\artifacts\$(Configuration)</OutputPath> | ||
| <TreatWarningsAsErrors>true</TreatWarningsAsErrors> | ||
| <WarningsAsErrors /> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'"> | ||
| <DefineConstants>TRACE;DEBUG;NETSTANDARD</DefineConstants> | ||
| </PropertyGroup> | ||
|
|
||
| <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'"> | ||
| <DefineConstants>TRACE;RELEASE;NETSTANDARD</DefineConstants> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\Common\Common.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Compile Remove="Properties\AssemblyInfo.cs" /> | ||
| <EmbeddedResource Remove="Properties\AssemblyInfo.cs" /> | ||
| <None Remove="Properties\AssemblyInfo.cs" /> | ||
| <Content Remove="Properties\AssemblyInfo.cs" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,227 @@ | ||||||||
| // ---------------------------------------------------------------------------------- | ||||||||
| // | ||||||||
| // Copyright Microsoft Corporation | ||||||||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||||||||
| // you may not use this file except in compliance with the License. | ||||||||
| // You may obtain a copy of the License at | ||||||||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||||||||
| // Unless required by applicable law or agreed to in writing, software | ||||||||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||||||||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||||||||
| // See the License for the specific language governing permissions and | ||||||||
| // limitations under the License. | ||||||||
| // ---------------------------------------------------------------------------------- | ||||||||
|
|
||||||||
| using System; | ||||||||
| using System.Net.Http; | ||||||||
| using System.Threading; | ||||||||
| using System.Threading.Tasks; | ||||||||
| using System.Text; | ||||||||
| using System.Text.RegularExpressions; | ||||||||
| using System.Collections.Generic; | ||||||||
| using Newtonsoft.Json; | ||||||||
| using Newtonsoft.Json.Linq; | ||||||||
| using System.Net; | ||||||||
| using Microsoft.WindowsAzure.Commands.Utilities.Common; | ||||||||
|
|
||||||||
| namespace Microsoft.WindowsAzure.Commands.Common | ||||||||
| { | ||||||||
| /// <summary> | ||||||||
| /// Delegating handler to acquire an Azure Policy token for change safety feature and attach to outgoing request. | ||||||||
| /// Activated when user specifies -AcquirePolicyToken. (ChangeReference deferred to Phase 2.) | ||||||||
| /// </summary> | ||||||||
| public class AcquirePolicyTokenHandler : DelegatingHandler, ICloneable | ||||||||
| { | ||||||||
| private readonly AzurePSCmdlet _cmdlet; | ||||||||
| private const string TokenApiVersion = "2025-03-01"; | ||||||||
| private static readonly Regex SubscriptionIdRegex = new Regex(@"/subscriptions/([0-9a-fA-F-]{36})", RegexOptions.IgnoreCase | RegexOptions.Compiled); | ||||||||
| private static readonly HashSet<string> _allowedWriteMethods = new HashSet<string>(StringComparer.OrdinalIgnoreCase) | ||||||||
| { | ||||||||
| HttpMethod.Put.Method, | ||||||||
| HttpMethod.Post.Method, | ||||||||
| HttpMethod.Delete.Method, | ||||||||
| "PATCH" | ||||||||
| }; | ||||||||
| private const string LogPrefix = "[AcquirePolicyTokenHandler]"; | ||||||||
|
|
||||||||
| public AcquirePolicyTokenHandler(AzurePSCmdlet cmdlet) | ||||||||
| { | ||||||||
| _cmdlet = cmdlet; | ||||||||
| } | ||||||||
|
|
||||||||
| protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | ||||||||
| { | ||||||||
| EnqueueDebug($"Intercept {request.Method} {request.RequestUri}"); | ||||||||
|
|
||||||||
| bool allowedVerb = _allowedWriteMethods.Contains(request.Method.Method); | ||||||||
| if (!allowedVerb) | ||||||||
| { | ||||||||
| EnqueueDebug("Skip: verb not allowed for token acquisition."); | ||||||||
| return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); | ||||||||
| } | ||||||||
|
|
||||||||
| bool hasCmdlet = _cmdlet != null; | ||||||||
| bool userRequested = hasCmdlet && _cmdlet.ShouldAcquirePolicyToken; | ||||||||
| if (!userRequested) | ||||||||
| { | ||||||||
| EnqueueDebug("Skip: user did not request token (no -AcquirePolicyToken)."); | ||||||||
| return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); | ||||||||
| } | ||||||||
|
|
||||||||
| var isWhatIf = _cmdlet.MyInvocation?.BoundParameters?.ContainsKey("WhatIf") == true; | ||||||||
| if (isWhatIf) | ||||||||
| { | ||||||||
| EnqueueDebug("Skip: -WhatIf present (dry run)."); | ||||||||
| return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); | ||||||||
| } | ||||||||
|
|
||||||||
| try | ||||||||
| { | ||||||||
| var token = await AcquirePolicyTokenAsync(request, cancellationToken).ConfigureAwait(false); | ||||||||
|
|
||||||||
| //Debug token, as is | ||||||||
| // EnqueueDebug($"Token: {token}"); | ||||||||
|
|
||||||||
|
|
||||||||
| if (!string.IsNullOrEmpty(token)) | ||||||||
| { | ||||||||
| if (request.Headers.Contains("x-ms-policy-external-evaluations")) | ||||||||
| { | ||||||||
| request.Headers.Remove("x-ms-policy-external-evaluations"); | ||||||||
| } | ||||||||
| request.Headers.Add("x-ms-policy-external-evaluations", token); | ||||||||
| EnqueueDebug("Token acquired and header added."); | ||||||||
| } | ||||||||
| else | ||||||||
| { | ||||||||
| EnqueueDebug("No token returned (null/empty)."); | ||||||||
| } | ||||||||
| } | ||||||||
| catch (Exception ex) | ||||||||
| { | ||||||||
| EnqueueDebug($"Exception: {ex.GetType().Name}: {ex.Message}"); | ||||||||
| throw new InvalidOperationException($"Failed to acquire policy token: {ex.Message}", ex); | ||||||||
| } | ||||||||
|
|
||||||||
| return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); | ||||||||
| } | ||||||||
|
|
||||||||
| private async Task<string> AcquirePolicyTokenAsync(HttpRequestMessage originalRequest, CancellationToken cancellationToken) | ||||||||
| { | ||||||||
| var subscriptionId = ExtractSubscriptionId(originalRequest.RequestUri); | ||||||||
| if (string.IsNullOrEmpty(subscriptionId)) | ||||||||
| { | ||||||||
| EnqueueDebug("Failed: subscription id not found in URI."); | ||||||||
| throw new InvalidOperationException("Unable to determine subscription ID for policy token acquisition."); | ||||||||
| } | ||||||||
|
|
||||||||
| var authority = originalRequest.RequestUri.GetLeftPart(UriPartial.Authority); | ||||||||
| var relativePath = $"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/acquirePolicyToken?api-version={TokenApiVersion}"; | ||||||||
| var tokenUri = new Uri(authority + relativePath); | ||||||||
|
|
||||||||
| object contentObj = null; | ||||||||
| if (originalRequest.Content != null) | ||||||||
| { | ||||||||
|
||||||||
| { | |
| { | |
| await originalRequest.Content.LoadIntoBufferAsync().ConfigureAwait(false); |
notyashhh marked this conversation as resolved.
Show resolved
Hide resolved
Copilot
AI
Mar 24, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Creating a new HttpClient per request inside the handler can lead to socket exhaustion and bypasses any proxy/timeout/retry configuration applied via AzureSession.Instance.ClientFactory. Prefer reusing a shared HttpClient (or using the existing ClientFactory-created client/handler stack) and ensure responses are disposed promptly (e.g., dispose HttpResponseMessage) to release connections.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The XML doc says ChangeReference is deferred to Phase 2, but the handler already includes changeReference in the payload and ShouldAcquirePolicyToken triggers when ChangeReference is provided. Please update the comment to reflect current behavior (or adjust the implementation if ChangeReference truly must be deferred).