-
Notifications
You must be signed in to change notification settings - Fork 108
WIP: Update ContainerRegistry code to use ORAS.NET #1961
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
adityapatwardhan
wants to merge
12
commits into
master
Choose a base branch
from
MoveToOras
base: master
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
85e6b5e
Update ContainerRegistry code to use ORAS.NET
adityapatwardhan 23b282a
Fix build for changes to .NET 8
adityapatwardhan 0e5f405
Update build yml
adityapatwardhan a683bf7
Fix build
adityapatwardhan 55340f9
Fix threading issues
adityapatwardhan 0d82ebd
Fix runspace issues in threading
adityapatwardhan aeba1b7
Update error message
adityapatwardhan dbe86b1
Merge remote-tracking branch 'refs/remotes/upstream/master' into Move…
adityapatwardhan d15fdf7
Fix build issues
adityapatwardhan 890d2e9
Fix build - remove buffers
adityapatwardhan 1462a65
Remove unnecessary dependencies
adityapatwardhan a6c5b62
Remove unnecessary dependencies - 2
adityapatwardhan 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
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
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
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
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
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,167 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT License. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Management.Automation; | ||
| using System.Management.Automation.Runspaces; | ||
| using System.Net.Http; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.PowerShell.PSResourceGet.UtilClasses; | ||
| using OrasProject.Oras.Registry.Remote.Auth; | ||
|
|
||
| namespace Microsoft.PowerShell.PSResourceGet | ||
| { | ||
| /// <summary> | ||
| /// Implements the ORAS ICredentialProvider interface for PSResourceGet. | ||
| /// Handles three authentication pathways: | ||
| /// 1. Credentials from SecretManagement vault (CredentialInfo provided) | ||
| /// 2. Azure Identity via Utils.GetAzAccessToken (existing helper) | ||
| /// 3. Anonymous/unauthenticated access | ||
| /// </summary> | ||
| internal class PSResourceGetCredentialProvider : ICredentialProvider | ||
| { | ||
| private readonly PSRepositoryInfo _repository; | ||
| private readonly PSCmdlet _cmdletPassedIn; | ||
| private readonly Runspace _callerRunspace; | ||
| private readonly string _registryHost; | ||
| private readonly HttpClient _httpClient; | ||
| private Credential _cachedCredential; | ||
| private DateTimeOffset _tokenExpiry = DateTimeOffset.MinValue; | ||
|
|
||
| // Template for the ACR OAuth2 exchange endpoint | ||
| private const string OAuthExchangeUrlTemplate = "https://{0}/oauth2/exchange"; | ||
| private const string RefreshTokenRequestBodyTemplate = "grant_type=access_token&service={0}&tenant={1}&access_token={2}"; | ||
| private const string RefreshTokenRequestBodyNoTenantTemplate = "grant_type=access_token&service={0}&access_token={1}"; | ||
|
|
||
| internal PSResourceGetCredentialProvider(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, HttpClient httpClient = null) | ||
| { | ||
| _repository = repository; | ||
| _cmdletPassedIn = cmdletPassedIn; | ||
| _callerRunspace = Runspace.DefaultRunspace; | ||
| _registryHost = repository.Uri.Host; | ||
| _httpClient = httpClient ?? new HttpClient(); | ||
| _cachedCredential = new Credential(); | ||
| } | ||
|
|
||
| public async Task<Credential> ResolveCredentialAsync(string hostname, CancellationToken cancellationToken) | ||
| { | ||
| if (string.IsNullOrEmpty(hostname)) | ||
| { | ||
| throw new ArgumentException("Hostname cannot be null or empty.", nameof(hostname)); | ||
| } | ||
|
|
||
| // ORAS invokes this callback on a thread pool thread which has no | ||
| // PowerShell Runspace. Restore the caller's Runspace so that | ||
| // InvokeCommand.InvokeScript, WriteVerbose, WriteWarning and any | ||
| // nested PowerShell script invocations (SecretManagement, etc.) work. | ||
| var previousRunspace = Runspace.DefaultRunspace; | ||
| Runspace.DefaultRunspace = _callerRunspace; | ||
|
|
||
| try | ||
| { | ||
| return await ResolveCredentialCoreAsync(hostname, cancellationToken).ConfigureAwait(false); | ||
| } | ||
| finally | ||
| { | ||
| Runspace.DefaultRunspace = previousRunspace; | ||
| } | ||
| } | ||
|
|
||
| private async Task<Credential> ResolveCredentialCoreAsync(string hostname, CancellationToken cancellationToken) | ||
| { | ||
| // Return cached credential if still valid | ||
| if (!string.IsNullOrEmpty(_cachedCredential.RefreshToken) && DateTimeOffset.UtcNow < _tokenExpiry) | ||
| { | ||
| Utils.WriteVerboseOnCmdlet(_cmdletPassedIn, "Using cached ORAS credential."); | ||
| return _cachedCredential; | ||
| } | ||
|
|
||
| string aadAccessToken; | ||
| string tenantId; | ||
|
|
||
| var repositoryCredentialInfo = _repository.CredentialInfo; | ||
| if (repositoryCredentialInfo != null) | ||
| { | ||
| // Path 1: Credential from SecretsManagement vault | ||
| Utils.WriteVerboseOnCmdlet(_cmdletPassedIn, "Retrieving access token from SecretManagement vault."); | ||
| aadAccessToken = Utils.GetContainerRegistryAccessTokenFromSecretManagement( | ||
| _repository.Name, | ||
| repositoryCredentialInfo, | ||
| _cmdletPassedIn); | ||
|
|
||
| if (string.IsNullOrEmpty(aadAccessToken)) | ||
| { | ||
| Utils.WriteWarningOnCmdlet(_cmdletPassedIn, "Failed to retrieve access token from SecretManagement vault."); | ||
| return new Credential(); | ||
| } | ||
|
|
||
| tenantId = repositoryCredentialInfo.SecretName; | ||
| } | ||
| else | ||
| { | ||
| // Path 2: Azure Identity via existing Utils helper | ||
| Utils.WriteVerboseOnCmdlet(_cmdletPassedIn, "Acquiring AAD access token via Utils.GetAzAccessToken."); | ||
| aadAccessToken = Utils.GetAzAccessToken(_cmdletPassedIn); | ||
|
|
||
| if (string.IsNullOrEmpty(aadAccessToken)) | ||
| { | ||
| // If Azure Identity fails, return empty credential for anonymous access | ||
| Utils.WriteVerboseOnCmdlet(_cmdletPassedIn, "No AAD token available; attempting anonymous access."); | ||
| return new Credential(); | ||
| } | ||
|
|
||
| tenantId = null; | ||
| } | ||
|
|
||
| // Exchange AAD access token for ACR refresh token via OAuth2 exchange endpoint | ||
| Utils.WriteVerboseOnCmdlet(_cmdletPassedIn, "Exchanging AAD access token for ACR refresh token."); | ||
| try | ||
| { | ||
| string refreshToken = await ExchangeForAcrRefreshTokenAsync(aadAccessToken, tenantId, cancellationToken).ConfigureAwait(false); | ||
|
|
||
| if (string.IsNullOrEmpty(refreshToken)) | ||
| { | ||
| Utils.WriteWarningOnCmdlet(_cmdletPassedIn, "Failed to obtain ACR refresh token from exchange."); | ||
| return new Credential(); | ||
| } | ||
|
|
||
| _cachedCredential = new Credential(RefreshToken: refreshToken); | ||
| _tokenExpiry = DateTimeOffset.UtcNow.AddMinutes(55); // ACR tokens typically valid for ~60 min | ||
| return _cachedCredential; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| Utils.WriteWarningOnCmdlet(_cmdletPassedIn, $"Failed to exchange AAD token for ACR refresh token: {ex.Message}"); | ||
| return new Credential(); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Exchanges an AAD access token for an ACR refresh token via the OAuth2 exchange endpoint. | ||
| /// </summary> | ||
| private async Task<string> ExchangeForAcrRefreshTokenAsync(string aadAccessToken, string tenantId, CancellationToken cancellationToken) | ||
| { | ||
| string exchangeUrl = string.Format(OAuthExchangeUrlTemplate, _registryHost); | ||
| string requestBody = string.IsNullOrEmpty(tenantId) | ||
| ? string.Format(RefreshTokenRequestBodyNoTenantTemplate, _registryHost, aadAccessToken) | ||
| : string.Format(RefreshTokenRequestBodyTemplate, _registryHost, tenantId, aadAccessToken); | ||
|
|
||
| using var content = new StringContent(requestBody, System.Text.Encoding.UTF8, "application/x-www-form-urlencoded"); | ||
| using var response = await _httpClient.PostAsync(exchangeUrl, content, cancellationToken).ConfigureAwait(false); | ||
| response.EnsureSuccessStatusCode(); | ||
|
|
||
| string responseBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); | ||
| using var jsonDoc = JsonDocument.Parse(responseBody); | ||
|
|
||
| if (jsonDoc.RootElement.TryGetProperty("refresh_token", out JsonElement refreshTokenElement)) | ||
| { | ||
| return refreshTokenElement.GetString(); | ||
| } | ||
|
|
||
| return null; | ||
| } | ||
| } | ||
| } | ||
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
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.
Check warning
Code scanning / CodeQL
Information exposure through transmitted data Medium
Copilot Autofix
AI 1 day ago
In general, the right fix is not to stop sending the access token to the token-exchange service (that’s necessary) but to (1) ensure it is only ever transmitted over a secure channel to the expected host, and (2) make sure it is never reflected back to the user via error messages or logs. This aligns with the guideline “avoid transmitting passwords or exceptions to the user”: we continue to transmit the token to the auth service, but we prevent accidental disclosure elsewhere and explicitly constrain the transmission to HTTPS.
For this specific code, the best minimally invasive fix is:
exchangeUrlbefore sending the HTTP request inExchangeForAcrRefreshTokenAsync:exchangeUrlas aUri.https; if not, throw or return null with a safe warning, without ever sending the sensitiverequestBody.aadAccessTokenin the request body; we are only adding a guard to ensure that this sensitive value is not sent over an insecure protocol.All required changes are localized to
ExchangeForAcrRefreshTokenAsyncinsrc/code/PSResourceGetCredentialProvider.cs. No changes are needed inUtils.cs, and we can rely onSystem.Uri, which is already part of the BCL and requires no new imports.Concretely:
ExchangeForAcrRefreshTokenAsync, right afterstring exchangeUrl = ..., add code to create aUrifromexchangeUrland verifyuri.Scheme == Uri.UriSchemeHttps. If not, throw anInvalidOperationException(or returnnull) before constructingrequestBodyor sending it.