diff --git a/.ci/ci.yml b/.ci/ci.yml index 9c75987a0..d3a186373 100644 --- a/.ci/ci.yml +++ b/.ci/ci.yml @@ -70,7 +70,7 @@ stages: Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force # - $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net472' + $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net10.0' displayName: Build Module - pwsh: | @@ -124,13 +124,6 @@ stages: displayName: PowerShell Core on Windows imageName: windows-latest - - template: test.yml - parameters: - jobName: TestPkgWinPS - displayName: Windows PowerShell on Windows - imageName: windows-latest - powershellExecutable: powershell - - template: test.yml parameters: jobName: TestPkgUbuntu diff --git a/.ci/ci_auto.yml b/.ci/ci_auto.yml index 440d4753f..74ab01c4c 100644 --- a/.ci/ci_auto.yml +++ b/.ci/ci_auto.yml @@ -39,6 +39,10 @@ stages: steps: + - task: UseDotNet@2 + inputs: + useGlobalJson: true + - pwsh: | Get-ChildItem -Path env: displayName: Capture environment for build @@ -68,8 +72,8 @@ stages: Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force # - # Build for net472 framework - $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net472' + # Build for net10.0 framework + $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net10.0' displayName: Build module - pwsh: | @@ -104,17 +108,17 @@ stages: $null = New-Item -Path $thirdPartySignSrcPath -ItemType Directory -Verbose } - # Net472 directory - $net472Path = Join-Path -Path $thirdPartySignSrcPath -ChildPath "net472" - if (! (Test-Path -Path $net472Path)) { - $null = New-Item -Path $net472Path -ItemType Directory -Verbose + # dependency directory + $depsPath = Join-Path -Path $thirdPartySignSrcPath -ChildPath "dependencies" + if (! (Test-Path -Path $depsPath)) { + $null = New-Item -Path $depsPath -ItemType Directory -Verbose } - Get-ChildItem -Path (Join-Path -Path $srcPath -ChildPath "net472") -Filter '*.dll' | Foreach-Object { - if ($_.Name -ne 'PSResourceGet.dll') { + Get-ChildItem -Path (Join-Path -Path $srcPath -ChildPath "dependencies") -Filter '*.dll' | Foreach-Object { + if ($_.Name -ne 'Microsoft.PowerShell.PSResourceGet.dll') { $sig = Get-AuthenticodeSignature -FilePath $_.FullName if ($sig.Status -ne 'Valid' -or $sig.SignerCertificate.Subject -notlike '*Microsoft*' -or $sig.SignerCertificate.Issuer -notlike '*Microsoft Code Signing PCA*') { # Copy for third party signing - Copy-Item -Path $_.FullName -Dest $net472Path -Force -Verbose + Copy-Item -Path $_.FullName -Dest $depsPath -Force -Verbose } } } @@ -160,17 +164,17 @@ stages: # Copy LICENSE Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "LICENSE") -Dest $signOutPath - # Net472 directory - $net472SignedOutPath = Join-Path -Path $signOutPath -ChildPath "net472" - if (! (Test-Path -Path $net472SignedOutPath)) { - $null = New-Item -Path $net472SignedOutPath -ItemType Directory -Verbose + # dependency directory + $depsSignedOutPath = Join-Path -Path $signOutPath -ChildPath "dependencies" + if (! (Test-Path -Path $depsSignedOutPath)) { + $null = New-Item -Path $depsSignedOutPath -ItemType Directory -Verbose } - Get-ChildItem -Path (Join-Path -Path $srcPath -ChildPath "net472") -Filter '*.dll' | Foreach-Object { - if ($_.Name -ne 'PSResourceGet.dll') { + Get-ChildItem -Path (Join-Path -Path $srcPath -ChildPath "dependencies") -Filter '*.dll' | Foreach-Object { + if ($_.Name -ne 'Microsoft.PowerShell.PSResourceGet.dll') { $sig = Get-AuthenticodeSignature -FilePath $_.FullName if ($sig.Status -eq 'Valid' -and ($sig.SignerCertificate.Subject -like '*Microsoft*' -and $sig.SignerCertificate.Issuer -like '*Microsoft Code Signing PCA*')) { # Copy already signed files directly to output - Copy-Item -Path $_.FullName -Dest $net472SignedOutPath -Force -Verbose + Copy-Item -Path $_.FullName -Dest $depsSignedOutPath -Force -Verbose } } } @@ -190,14 +194,11 @@ stages: if (! (Test-Path -Path $createdSignSrcPath)) { $null = New-Item -Path $createdSignSrcPath -ItemType Directory -Verbose } - Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "PSResourceGet.psd1") -Dest $createdSignSrcPath -Force -Verbose + Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "Microsoft.PowerShell.PSResourceGet.psd1") -Dest $createdSignSrcPath -Force -Verbose + Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "Microsoft.PowerShell.PSResourceGet.psm1") -Dest $createdSignSrcPath -Force -Verbose Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "PSGet.Format.ps1xml") -Dest $createdSignSrcPath -Force -Verbose - $net472Path = Join-Path -Path $createdSignSrcPath -ChildPath "net472" - if (! (Test-Path -Path $net472Path)) { - $null = New-Item -Path $net472Path -ItemType Directory -Verbose - } - Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "net472\PSResourceGet.dll") -Dest $net472Path -Force -Verbose + Copy-Item -Path (Join-Path -Path $srcPath -ChildPath "Microsoft.PowerShell.PSResourceGet.dll") -Dest $createdSignSrcPath -Force -Verbose # Set signing src path variable $vstsCommandString = "vso[task.setvariable variable=signSrcPath]${createdSignSrcPath}" @@ -294,11 +295,11 @@ stages: - checkout: ComplianceRepo clean: true - download: current - artifact: 'PSResourceGet' + artifact: 'Microsoft.PowerShell.PSResourceGet' - template: assembly-module-compliance.yml@ComplianceRepo parameters: # binskim - AnalyzeTarget: '$(Pipeline.Workspace)/PSResourceGet/net472/PSResourceGet.dll' + AnalyzeTarget: '$(Pipeline.Workspace)/Microsoft.PowerShell.PSResourceGet/Microsoft.PowerShell.PSResourceGet.dll' AnalyzeSymPath: 'SRV*' # component-governance sourceScanPath: '$(Build.SourcesDirectory)' @@ -322,13 +323,6 @@ stages: displayName: PowerShell Core on Windows imageName: windows-latest - - template: test.yml - parameters: - jobName: TestPkgWinPS - displayName: Windows PowerShell on Windows - imageName: windows-latest - powershellExecutable: powershell - - template: test.yml parameters: jobName: TestPkgUbuntu diff --git a/.ci/ci_release.yml b/.ci/ci_release.yml index 429bf7cf3..f45d24307 100644 --- a/.ci/ci_release.yml +++ b/.ci/ci_release.yml @@ -29,6 +29,10 @@ stages: - ImageOverride -equals PSMMS2019-Secure steps: + - task: UseDotNet@2 + inputs: + useGlobalJson: true + - pwsh: | Get-ChildItem -Path env: Get-ChildItem -Path . -Recurse -Directory @@ -59,8 +63,8 @@ stages: Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)" Import-Module -Name $(Build.SourcesDirectory)/buildtools.psd1 -Force # - # Build for net472 framework - $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net472' + # Build for net10.0 framework + $(Build.SourcesDirectory)/build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net10.0' displayName: Build and publish artifact - pwsh: | @@ -398,13 +402,6 @@ stages: displayName: PowerShell Core on Windows imageName: windows-latest - - template: test.yml - parameters: - jobName: TestPkgWinPS - displayName: Windows PowerShell on Windows - imageName: windows-latest - powershellExecutable: powershell - - template: test.yml parameters: jobName: TestPkgUbuntu diff --git a/.ci/test.yml b/.ci/test.yml index 5a8548ee7..40a335668 100644 --- a/.ci/test.yml +++ b/.ci/test.yml @@ -14,6 +14,12 @@ jobs: variables: - group: InstallDSC steps: + - pwsh: | + if ($PSVersionTable.PSVersion -lt [version]'7.6' -or [Environment]::Version.Major -lt 10) { + throw "Tests require PowerShell 7.6 or newer running on .NET 10 or newer." + } + displayName: Verify PowerShell and .NET runtime requirements + - ${{ parameters.powershellExecutable }}: | Install-Module -Name 'Microsoft.PowerShell.SecretManagement' -force -SkipPublisherCheck -AllowClobber Install-Module -Name 'Microsoft.PowerShell.SecretStore' -force -SkipPublisherCheck -AllowClobber diff --git a/.pipelines/PSResourceGet-Official.yml b/.pipelines/PSResourceGet-Official.yml index 9e24395ee..6cb7002f2 100644 --- a/.pipelines/PSResourceGet-Official.yml +++ b/.pipelines/PSResourceGet-Official.yml @@ -130,7 +130,7 @@ extends: # this is installing .NET - pwsh: | Set-Location "$(repoRoot)" - try { ./build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net472'} catch { throw $_ } + try { ./build.ps1 -Build -Clean -BuildConfiguration Release -BuildFramework 'net10.0'} catch { throw $_ } displayName: Execute build env: ob_restore_phase: true # Set ob_restore_phase to run this step before '🔒 Setup Signing' step. diff --git a/README.md b/README.md index a0ca6c443..2b6e3c089 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/PowerShell/PSResourceGet/blob/master/LICENSE) [![Documentation - PSResourceGet](https://img.shields.io/badge/Documentation-PowerShellGet-blue.svg)](https://learn.microsoft.com/powershell/module/microsoft.powershell.psresourceget) [![PowerShell Gallery - PSResourceGet](https://img.shields.io/badge/PowerShell%20Gallery-PSResourceGet-blue.svg)](https://www.powershellgallery.com/packages/Microsoft.PowerShell.PSResourceGet) -[![Minimum Supported PowerShell Version](https://img.shields.io/badge/PowerShell-5.0-blue.svg)](https://github.com/PowerShell/PSResourceGet) +[![Minimum Supported PowerShell Version](https://img.shields.io/badge/PowerShell-7.6-blue.svg)](https://github.com/PowerShell/PSResourceGet) ## Important Notes @@ -27,7 +27,7 @@ PSResourceGet is a PowerShell module with commands for discovering, installing, ## Requirements -* PowerShell 5.0 or higher. +* PowerShell 7.6 or higher running on .NET 10. Windows PowerShell is not supported by this build. ## Install the PSResourceGet module @@ -54,8 +54,8 @@ Please use the [PowerShell Gallery](https://www.powershellgallery.com) to get th Note: Please ensure you have the exact version of the .NET SDK installed. The current version can be found in the [global.json](https://github.com/PowerShell/PSResourceGet/blob/master/global.json) and installed from the [.NET website](https://dotnet.microsoft.com/en-us/download). ```powershell - # Build for the net472 framework - PS C:\Repos\PSResourceGet> .\build.ps1 -Clean -Build -BuildConfiguration Debug -BuildFramework net472 + # Build for the net10.0 framework + PS C:\Repos\PSResourceGet> .\build.ps1 -Clean -Build -BuildConfiguration Debug -BuildFramework net10.0 ``` ### Run functional tests @@ -72,13 +72,9 @@ Note: Please ensure you have the exact version of the .NET SDK installed. The c ### Import the built module into a new PowerShell session ```powershell -# If running PowerShell 6+ +# Run in a fresh PowerShell 7.6+ session C:\> pwsh -C:\> Import-Module C:\Repos\PSResourceGet\out\PSResourceGet - -# If running Windows PowerShell -c:\> PowerShell -C:\> Import-Module C:\Repos\PSResourceGet\out\PSResourceGet\PSResourceGet.psd1 +C:\> Import-Module C:\Repos\PSResourceGet\out\Microsoft.PowerShell.PSResourceGet\Microsoft.PowerShell.PSResourceGet.psd1 ``` ## Module Support Lifecycle Microsoft.PowerShell.PSResourceGet follows the support lifecycle of the version of PowerShell that it ships in. diff --git a/build.ps1 b/build.ps1 index 68de8f552..e04bf8717 100644 --- a/build.ps1 +++ b/build.ps1 @@ -23,8 +23,8 @@ param ( [ValidateSet("Debug", "Release")] [string] $BuildConfiguration = "Debug", - [ValidateSet("net472")] - [string] $BuildFramework = "net472" + [ValidateSet("net10.0")] + [string] $BuildFramework = "net10.0" ) Import-Module -Name "$PSScriptRoot/buildtools.psd1" -Force diff --git a/doBuild.ps1 b/doBuild.ps1 index cc3edcbbb..2ce2576cc 100644 --- a/doBuild.ps1 +++ b/doBuild.ps1 @@ -95,7 +95,8 @@ function DoBuild 'Azure.Core' 'Azure.Identity' 'Microsoft.Bcl.AsyncInterfaces' - 'Microsoft.Bcl.Cryptography' + 'Microsoft.Extensions.Caching.Abstractions' + 'Microsoft.Extensions.Caching.Memory' 'Microsoft.Extensions.Configuration.Abstractions' 'Microsoft.Extensions.DependencyInjection.Abstractions' 'Microsoft.Extensions.Diagnostics.Abstractions' @@ -120,24 +121,11 @@ function DoBuild 'NuGet.ProjectModel' 'NuGet.Protocol' 'NuGet.Versioning' - 'System.Buffers' - 'System.Collections.Immutable' + 'OrasProject.Oras' 'System.ClientModel' - 'System.Diagnostics.DiagnosticSource' - 'System.Formats.Asn1' - 'System.IO.FileSystem.AccessControl' - 'System.IO.Pipelines' 'System.Memory.Data' - 'System.Memory' - 'System.Numerics.Vectors' - 'System.Runtime.CompilerServices.Unsafe' - 'System.Security.AccessControl' 'System.Security.Cryptography.Pkcs' 'System.Security.Cryptography.ProtectedData' - 'System.Security.Principal.Windows' - 'System.Text.Encodings.Web' - 'System.Text.Json' - 'System.Threading.Tasks.Extensions' ) $buildSuccess = $true diff --git a/src/Microsoft.PowerShell.PSResourceGet.psd1 b/src/Microsoft.PowerShell.PSResourceGet.psd1 index 4c8994e7b..67ab23269 100644 --- a/src/Microsoft.PowerShell.PSResourceGet.psd1 +++ b/src/Microsoft.PowerShell.PSResourceGet.psd1 @@ -5,15 +5,13 @@ RootModule = './Microsoft.PowerShell.PSResourceGet.dll' NestedModules = @('./Microsoft.PowerShell.PSResourceGet.psm1') ModuleVersion = '1.3.1' - CompatiblePSEditions = @('Core', 'Desktop') + CompatiblePSEditions = @('Core') GUID = 'e4e0bda1-0703-44a5-b70d-8fe704cd0643' Author = 'Microsoft Corporation' CompanyName = 'Microsoft Corporation' Copyright = '(c) Microsoft Corporation. All rights reserved.' Description = 'PowerShell module with commands for discovering, installing, updating and publishing the PowerShell artifacts like Modules, Scripts, and DSC Resources.' - PowerShellVersion = '5.1' - DotNetFrameworkVersion = '2.0' - CLRVersion = '4.0.0' + PowerShellVersion = '7.6' FormatsToProcess = 'PSGet.Format.ps1xml' CmdletsToExport = @( 'Compress-PSResource', @@ -52,7 +50,6 @@ PSData = @{ # Prerelease = '' Tags = @('PackageManagement', - 'PSEdition_Desktop', 'PSEdition_Core', 'Linux', 'Mac', diff --git a/src/code/ContainerRegistryServerAPICalls.cs b/src/code/ContainerRegistryServerAPICalls.cs index 31ceced4b..d5c27751c 100644 --- a/src/code/ContainerRegistryServerAPICalls.cs +++ b/src/code/ContainerRegistryServerAPICalls.cs @@ -5,23 +5,28 @@ using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Management.Automation; using System.Net; using System.Net.Http; -using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using System.Text.Json; -using System.Text.RegularExpressions; +using System.Threading; using System.Threading.Tasks; +using Microsoft.Extensions.Caching.Memory; using Microsoft.PowerShell.PSResourceGet.Cmdlets; using Microsoft.PowerShell.PSResourceGet.UtilClasses; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using NuGet.Versioning; +using OrasProject.Oras; +using OrasProject.Oras.Content; +using OrasProject.Oras.Oci; +using OrasProject.Oras.Registry; +using OrasProject.Oras.Registry.Remote; +using OrasProject.Oras.Registry.Remote.Auth; +using OrasRegistry = OrasProject.Oras.Registry.Remote.Registry; +using OrasRepository = OrasProject.Oras.Registry.Remote.Repository; namespace Microsoft.PowerShell.PSResourceGet { @@ -34,29 +39,15 @@ internal class ContainerRegistryServerAPICalls : ServerApiCall public override PSRepositoryInfo Repository { get; set; } public String Registry { get; set; } private readonly PSCmdlet _cmdletPassedIn; - private HttpClient _sessionClient { get; set; } private static readonly Hashtable[] emptyHashResponses = new Hashtable[] { }; private static FindResponseType containerRegistryFindResponseType = FindResponseType.ResponseString; private static readonly FindResults emptyResponseResults = new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: containerRegistryFindResponseType); - const string containerRegistryRefreshTokenTemplate = "grant_type=access_token&service={0}&tenant={1}&access_token={2}"; // 0 - registry, 1 - tenant, 2 - access token - const string containerRegistryAccessTokenTemplate = "grant_type=refresh_token&service={0}&scope=repository:*:*&scope=registry:catalog:*&refresh_token={1}"; // 0 - registry, 1 - refresh token - const string containerRegistryOAuthExchangeUrlTemplate = "https://{0}/oauth2/exchange"; // 0 - registry - const string containerRegistryOAuthTokenUrlTemplate = "https://{0}/oauth2/token"; // 0 - registry - const string containerRegistryManifestUrlTemplate = "https://{0}/v2/{1}/manifests/{2}"; // 0 - registry, 1 - repo(modulename), 2 - tag(version) - const string containerRegistryBlobDownloadUrlTemplate = "https://{0}/v2/{1}/blobs/{2}"; // 0 - registry, 1 - repo(modulename), 2 - layer digest - const string containerRegistryFindImageVersionUrlTemplate = "https://{0}/v2/{1}/tags/list"; // 0 - registry, 1 - repo(modulename) - const string containerRegistryStartUploadTemplate = "https://{0}/v2/{1}/blobs/uploads/"; // 0 - registry, 1 - packagename - const string containerRegistryEndUploadTemplate = "https://{0}{1}&digest=sha256:{2}"; // 0 - registry, 1 - location, 2 - digest - const string defaultScope = "&scope=repository:*:*&scope=registry:catalog:*"; - const string catalogScope = "&scope=registry:catalog:*"; - const string grantTypeTemplate = "grant_type=access_token&service={0}{1}"; // 0 - registry, 1 - scope - const string authUrlTemplate = "{0}?service={1}{2}"; // 0 - realm, 1 - service, 2 - scope - const string emptyConfigContent = "{}"; - - const string containerRegistryRepositoryListTemplate = "https://{0}/v2/_catalog"; // 0 - registry - - private string _cachedContainterRegistryToken = null; + // ORAS SDK objects + private readonly HttpClient _httpClient; + private readonly IClient _orasClient; + private readonly PSResourceGetCredentialProvider _credentialProvider; + private readonly IMemoryCache _memoryCache; #endregion @@ -67,16 +58,14 @@ public ContainerRegistryServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmd Repository = repository; Registry = Repository.Uri.Host; _cmdletPassedIn = cmdletPassedIn; - HttpClientHandler handler = new HttpClientHandler() - { - Credentials = networkCredential - }; - _cachedContainterRegistryToken = null; + _httpClient = new HttpClient(); + _httpClient.Timeout = TimeSpan.FromMinutes(10); + _httpClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgentString); - _sessionClient = new HttpClient(handler); - _sessionClient.Timeout = TimeSpan.FromMinutes(10); - _sessionClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgentString); + _credentialProvider = new PSResourceGetCredentialProvider(repository, cmdletPassedIn); + _memoryCache = new MemoryCache(new MemoryCacheOptions()); + _orasClient = new Client(_httpClient, _credentialProvider, new Cache(_memoryCache)); } #endregion @@ -394,7 +383,13 @@ public override Stream InstallPackage(string packageName, string packageVersion, } string packageNameForInstall = PrependMARPrefix(packageName); - results = InstallVersion(packageNameForInstall, packageVersion, out errRecord); + ConcurrentQueue errorMsgs = new ConcurrentQueue(); + ConcurrentQueue warningMsgs = new ConcurrentQueue(); + ConcurrentQueue debugMsgs = new ConcurrentQueue(); + ConcurrentQueue verboseMsgs = new ConcurrentQueue(); + results = InstallVersion(packageNameForInstall, packageVersion, out errRecord, debugMsgs, verboseMsgs); + DrainCredentialMessages(warningMsgs, verboseMsgs); + Utils.WriteOutConcurrentQueue(_cmdletPassedIn, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); return results; } @@ -422,7 +417,12 @@ public override Task InstallPackageAsync(string packageName, string pack } string packageNameForInstall = PrependMARPrefix(packageName); - results = InstallVersionAsync(packageNameForInstall, packageVersion, errorMsgs, debugMsgs, verboseMsgs); + results = InstallVersion(packageNameForInstall, packageVersion, out ErrorRecord errRecord, debugMsgs, verboseMsgs); + DrainCredentialMessages(warningMsgs, verboseMsgs); + if (errRecord != null) + { + errorMsgs.Enqueue(errRecord); + } return Task.FromResult(results); } @@ -433,530 +433,234 @@ public override Task InstallPackageAsync(string packageName, string pack private Stream InstallVersion( string packageName, string packageVersion, - out ErrorRecord errRecord) + out ErrorRecord errRecord, + ConcurrentQueue debugMsgs = null, + ConcurrentQueue verboseMsgs = null) { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::InstallVersion()"); + debugMsgs ??= new ConcurrentQueue(); + verboseMsgs ??= new ConcurrentQueue(); + debugMsgs.Enqueue("In ContainerRegistryServerAPICalls::InstallVersion()"); errRecord = null; string packageNameLowercase = packageName.ToLower(); - string accessToken = string.Empty; - string tenantID = string.Empty; - ConcurrentQueue errorMsgs = new ConcurrentQueue(); - ConcurrentQueue warningMsgs = new ConcurrentQueue(); - ConcurrentQueue debugMsgs = new ConcurrentQueue(); - ConcurrentQueue verboseMsgs = new ConcurrentQueue(); - string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + try { - Directory.CreateDirectory(tempPath); - } - catch (Exception e) - { - errRecord = new ErrorRecord( - exception: e, - "InstallVersionTempDirCreationError", - ErrorCategory.InvalidResult, - _cmdletPassedIn); + // Create ORAS repository for the specific package + var repo = CreateOrasRepository(packageNameLowercase); - return null; - } + verboseMsgs.Enqueue($"Fetching manifest for {packageNameLowercase} - {packageVersion}"); - string containerRegistryAccessToken = GetContainerRegistryAccessToken(needCatalogAccess: false, isPushOperation: false, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - Utils.WriteOutConcurrentQueue(_cmdletPassedIn, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null) - { - return null; - } + // Fetch the manifest by version tag + var (manifestDescriptor, manifestStream) = repo.FetchAsync(packageVersion).GetAwaiter().GetResult(); + byte[] manifestBytes; + using (manifestStream) + { + manifestBytes = manifestStream.ReadAllAsync(manifestDescriptor).GetAwaiter().GetResult(); + } - _cmdletPassedIn.WriteVerbose($"Getting manifest for {packageNameLowercase} - {packageVersion}"); - var manifest = GetContainerRegistryRepositoryManifest(packageNameLowercase, packageVersion, containerRegistryAccessToken, out errRecord); - if (errRecord != null) - { - return null; - } - string digest = GetDigestFromManifest(manifest, out errRecord); - if (errRecord != null) - { - return null; - } + // Parse the manifest to get the layer descriptor (contains the nupkg blob) + var manifest = System.Text.Json.JsonSerializer.Deserialize(manifestBytes); + if (manifest == null || manifest.Layers == null || manifest.Layers.Count == 0) + { + errRecord = new ErrorRecord( + exception: new InvalidOperationException($"Manifest for {packageNameLowercase} version {packageVersion} has no layers."), + "ManifestNoLayersError", + ErrorCategory.InvalidResult, + _cmdletPassedIn); + return null; + } - _cmdletPassedIn.WriteVerbose($"Downloading blob for {packageNameLowercase} - {packageVersion}"); - HttpContent responseContent; - try - { - responseContent = GetContainerRegistryBlobAsync(packageNameLowercase, digest, containerRegistryAccessToken).Result; + // The first layer contains the nupkg + var nupkgLayer = manifest.Layers[0]; + verboseMsgs.Enqueue($"Downloading blob for {packageNameLowercase} - {packageVersion} (digest: {nupkgLayer.Digest})"); + + // Fetch the blob content + using var blobStream = repo.FetchAsync(nupkgLayer).GetAwaiter().GetResult(); + var resultStream = new MemoryStream(); + blobStream.CopyTo(resultStream); + resultStream.Position = 0; + return resultStream; } catch (Exception e) { errRecord = new ErrorRecord( exception: e, - "InstallVersionGetContainerRegistryBlobAsyncError", + "InstallVersionOrasError", ErrorCategory.InvalidResult, _cmdletPassedIn); return null; } - - return responseContent.ReadAsStreamAsync().Result; } - /// - /// Installs a package with version specified using concurrent queues for output instead of cmdlet streams. - /// Used by the async install path to avoid cross-thread cmdlet stream writes. - /// - private Stream InstallVersionAsync( - string packageName, - string packageVersion, - ConcurrentQueue errorMsgs, - ConcurrentQueue debugMsgs, - ConcurrentQueue verboseMsgs) - { - debugMsgs.Enqueue("In ContainerRegistryServerAPICalls::InstallVersionAsync()"); - string packageNameLowercase = packageName.ToLower(); - string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); - try - { - Directory.CreateDirectory(tempPath); - } - catch (Exception e) - { - errorMsgs.Enqueue(new ErrorRecord( - exception: e, - "InstallVersionTempDirCreationError", - ErrorCategory.InvalidResult, - _cmdletPassedIn)); + #endregion - return null; - } + #region ORAS Helper Methods - string containerRegistryAccessToken = GetContainerRegistryAccessToken(needCatalogAccess: false, isPushOperation: false, out ErrorRecord errRecord, errorMsgs, warningMsgs: null, debugMsgs, verboseMsgs); - if (errRecord != null) + private void DrainCredentialMessages(ConcurrentQueue warningMsgs, ConcurrentQueue verboseMsgs) + { + while (_credentialProvider.WarningMsgs.TryDequeue(out string warning)) { - errorMsgs.Enqueue(errRecord); - return null; + warningMsgs.Enqueue(warning); } - verboseMsgs.Enqueue($"Getting manifest for {packageNameLowercase} - {packageVersion}"); - var manifest = GetContainerRegistryRepositoryManifest(packageNameLowercase, packageVersion, containerRegistryAccessToken, out errRecord, debugMsgs); - if (errRecord != null) - { - errorMsgs.Enqueue(errRecord); - return null; - } - string digest = GetDigestFromManifest(manifest, out errRecord, debugMsgs); - if (errRecord != null) + while (_credentialProvider.VerboseMsgs.TryDequeue(out string verbose)) { - errorMsgs.Enqueue(errRecord); - return null; + verboseMsgs.Enqueue(verbose); } + } - verboseMsgs.Enqueue($"Downloading blob for {packageNameLowercase} - {packageVersion}"); - HttpContent responseContent; - try - { - responseContent = GetContainerRegistryBlobAsync(packageNameLowercase, digest, containerRegistryAccessToken, debugMsgs).Result; - } - catch (Exception e) + /// + /// Creates an ORAS Repository instance for the given package name. + /// + private OrasRepository CreateOrasRepository(string packageName) + { + string reference = $"{Registry}/{packageName}"; + return new OrasRepository(new RepositoryOptions { - errorMsgs.Enqueue(new ErrorRecord( - exception: e, - "InstallVersionGetContainerRegistryBlobAsyncError", - ErrorCategory.InvalidResult, - _cmdletPassedIn)); - - return null; - } - - return responseContent.ReadAsStreamAsync().Result; + Reference = Reference.Parse(reference), + Client = _orasClient, + }); } - #endregion - - #region Authentication and Token Methods + /// + /// Creates an ORAS Registry instance for catalog operations. + /// + private OrasRegistry CreateOrasRegistry() + { + return new OrasRegistry(Registry, _orasClient); + } /// - /// Gets the access token for the container registry by following the below logic: - /// If a credential is provided when registering the repository, retrieve the token from SecretsManagement. - /// If no credential provided at registration then, check if the ACR endpoint can be accessed without a token. If not, try using Azure.Identity to get the az access token, then ACR refresh token and then ACR access token. - /// Note: Access token can be empty if the repository is unauthenticated - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. + /// Lists all tags for a given package using ORAS. /// - internal string GetContainerRegistryAccessToken(bool needCatalogAccess, bool isPushOperation, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null, ConcurrentQueue informationMsgs = null) + internal List ListImageTags(string packageName, out ErrorRecord errRecord, ConcurrentQueue debugMsgs = null) { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetContainerRegistryAccessToken()"); - string accessToken = string.Empty; - string containerRegistryAccessToken = string.Empty; - string tenantID = string.Empty; + debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::ListImageTags()"); errRecord = null; + var tags = new List(); - if (!string.IsNullOrEmpty(_cachedContainterRegistryToken)) - { - verboseMsgs?.Enqueue("Using cached container registry access token."); - return _cachedContainterRegistryToken; - } - - var repositoryCredentialInfo = Repository.CredentialInfo; - if (repositoryCredentialInfo != null) - { - accessToken = Utils.GetContainerRegistryAccessTokenFromSecretManagement( - Repository.Name, - repositoryCredentialInfo, - _cmdletPassedIn); - - verboseMsgs?.Enqueue("Access token retrieved."); - - tenantID = repositoryCredentialInfo.SecretName; - } - else + try { - // A container registry repository is determined to be unauthenticated if it allows anonymous pull access. However, push operations always require authentication. - bool isRepositoryUnauthenticated = isPushOperation ? false : IsContainerRegistryUnauthenticated(Repository.Uri.ToString(), needCatalogAccess, out errRecord, out accessToken, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - verboseMsgs?.Enqueue($"Value of isRepositoryUnauthenticated: {isRepositoryUnauthenticated}"); - var informationRecord = new InformationRecord($"Value of isRepositoryUnauthenticated: {isRepositoryUnauthenticated}", "PSResourceGet"); - informationRecord.Tags.Add("PSRGContainerRegistryUnauthenticatedCheck"); - informationMsgs?.Enqueue(informationRecord); - - debugMsgs?.Enqueue($"Is repository unauthenticated: {isRepositoryUnauthenticated}"); - - if (errRecord != null) - { - return null; - } - - if (!string.IsNullOrEmpty(accessToken)) - { - verboseMsgs?.Enqueue("Anonymous access token retrieved."); - return accessToken; - } - - if (!isRepositoryUnauthenticated) + var repo = CreateOrasRepository(packageName); + var tagsEnumerable = repo.ListTagsAsync(""); + // Collect all tags synchronously + var enumerator = tagsEnumerable.GetAsyncEnumerator(); + try { - accessToken = Utils.GetAzAccessToken(_cmdletPassedIn); - if (string.IsNullOrEmpty(accessToken)) + while (enumerator.MoveNextAsync().AsTask().GetAwaiter().GetResult()) { - errRecord = new ErrorRecord( - new InvalidOperationException("Failed to get access token from Azure."), - "AzAccessTokenFailure", - ErrorCategory.AuthenticationError, - this); - - return null; + tags.Add(enumerator.Current); } } - else + finally { - verboseMsgs?.Enqueue("Repository is unauthenticated"); - return null; + enumerator.DisposeAsync().AsTask().GetAwaiter().GetResult(); } } - - var containerRegistryRefreshToken = GetContainerRegistryRefreshToken(tenantID, accessToken, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null) - { - return null; - } - - containerRegistryAccessToken = GetContainerRegistryAccessTokenByRefreshToken(containerRegistryRefreshToken, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null) + catch (Exception e) { - return null; + errRecord = new ErrorRecord( + exception: e, + "ResourceNotFound", + ErrorCategory.InvalidResult, + _cmdletPassedIn); } - verboseMsgs?.Enqueue("Container registry access token retrieved."); - _cachedContainterRegistryToken = containerRegistryAccessToken; - - return containerRegistryAccessToken; + return tags; } /// - /// Checks if container registry repository is unauthenticated. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. + /// Lists all repositories in the registry using ORAS. /// - internal bool IsContainerRegistryUnauthenticated(string containerRegistryUrl, bool needCatalogAccess, out ErrorRecord errRecord, out string anonymousAccessToken, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) + internal List ListAllRepositories(out ErrorRecord errRecord) { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::IsContainerRegistryUnauthenticated()"); + _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::ListAllRepositories()"); errRecord = null; - anonymousAccessToken = string.Empty; - string endpoint = $"{containerRegistryUrl}/v2/"; - HttpResponseMessage response; + var repositories = new List(); + try { - response = _sessionClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, endpoint)).Result; - - if (response.StatusCode == HttpStatusCode.Unauthorized) + var registry = CreateOrasRegistry(); + var repoEnumerable = registry.ListRepositoriesAsync(""); + var enumerator = repoEnumerable.GetAsyncEnumerator(); + try { - // check if there is a auth challenge header - if (response.Headers.WwwAuthenticate.Count() > 0) + while (enumerator.MoveNextAsync().AsTask().GetAwaiter().GetResult()) { - var authHeader = response.Headers.WwwAuthenticate.First(); - if (authHeader.Scheme == "Bearer") - { - // check if there is a realm - if (authHeader.Parameter.Contains("realm")) - { - // get the realm - var realm = authHeader.Parameter.Split(',')?.Where(x => x.Contains("realm"))?.FirstOrDefault()?.Split('=')[1]?.Trim('"'); - // get the service - var service = authHeader.Parameter.Split(',')?.Where(x => x.Contains("service"))?.FirstOrDefault()?.Split('=')[1]?.Trim('"'); - - if (string.IsNullOrEmpty(realm) || string.IsNullOrEmpty(service)) - { - errRecord = new ErrorRecord( - new InvalidOperationException("Failed to get realm or service from the auth challenge header."), - "RegistryUnauthenticationCheckError", - ErrorCategory.InvalidResult, - this); - - return false; - } - - string content = needCatalogAccess ? String.Format(grantTypeTemplate, service, catalogScope) : String.Format(grantTypeTemplate, service, defaultScope); - - var contentHeaders = new Collection> { new KeyValuePair("Content-Type", "application/x-www-form-urlencoded") }; - - string url = needCatalogAccess ? String.Format(authUrlTemplate, realm, service, catalogScope) : String.Format(authUrlTemplate, realm, service, defaultScope); - - debugMsgs?.Enqueue($"Getting anonymous access token from the realm: {url}"); - - // we don't check the error record here because we want to return false if we get a 401 and not throw an error - debugMsgs?.Enqueue($"Getting anonymous access token from the realm: {url}"); - ErrorRecord errRecordTemp = null; - - var results = GetHttpResponseJObjectUsingContentHeaders(url, HttpMethod.Get, content, contentHeaders, out errRecordTemp, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - - if (results == null) - { - debugMsgs?.Enqueue("Failed to get access token from the realm. results is null."); - debugMsgs?.Enqueue($"ErrorRecord: {errRecordTemp}"); - return false; - } - - if (results["access_token"] == null) - { - debugMsgs?.Enqueue($"Failed to get access token from the realm. access_token is null. results: {results}"); - return false; - } - - anonymousAccessToken = results["access_token"].ToString(); - return true; - } - } + repositories.Add(enumerator.Current); } } - } - catch (HttpRequestException hre) - { - errRecord = new ErrorRecord( - hre, - "RegistryAnonymousAcquireError", - ErrorCategory.ConnectionError, - this); - - return false; + finally + { + enumerator.DisposeAsync().AsTask().GetAwaiter().GetResult(); + } } catch (Exception e) { errRecord = new ErrorRecord( - e, - "RegistryUnauthenticationCheckError", + exception: e, + "ListAllRepositoriesOrasError", ErrorCategory.InvalidResult, - this); - - return false; - } - - return (response.StatusCode == HttpStatusCode.OK); - } - - /// - /// Given the access token retrieved from credentials, gets the refresh token. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal string GetContainerRegistryRefreshToken(string tenant, string accessToken, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetContainerRegistryRefreshToken()"); - string content = string.Format(containerRegistryRefreshTokenTemplate, Registry, tenant, accessToken); - var contentHeaders = new Collection> { new KeyValuePair("Content-Type", "application/x-www-form-urlencoded") }; - string exchangeUrl = string.Format(containerRegistryOAuthExchangeUrlTemplate, Registry); - var results = GetHttpResponseJObjectUsingContentHeaders(exchangeUrl, HttpMethod.Post, content, contentHeaders, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null || results == null || results["refresh_token"] == null) - { - return string.Empty; + _cmdletPassedIn); } - - return results["refresh_token"].ToString(); - } - - /// - /// Given the refresh token, gets the new access token with appropriate scope access permissions. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal string GetContainerRegistryAccessTokenByRefreshToken(string refreshToken, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetContainerRegistryAccessTokenByRefreshToken()"); - string content = string.Format(containerRegistryAccessTokenTemplate, Registry, refreshToken); - var contentHeaders = new Collection> { new KeyValuePair("Content-Type", "application/x-www-form-urlencoded") }; - string tokenUrl = string.Format(containerRegistryOAuthTokenUrlTemplate, Registry); - var results = GetHttpResponseJObjectUsingContentHeaders(tokenUrl, HttpMethod.Post, content, contentHeaders, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null || results == null || results["access_token"] == null) + finally { - return string.Empty; + Utils.WriteOutConcurrentQueue(_cmdletPassedIn, new ConcurrentQueue(), _credentialProvider.WarningMsgs, new ConcurrentQueue(), _credentialProvider.VerboseMsgs); } - return results["access_token"].ToString(); + return repositories; } - #endregion - - #region Private Methods - /// - /// Parses package manifest JObject to find digest entry, which is the SHA needed to identify and get the package. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. + /// Fetches the manifest for a specific package version and parses it. + /// Returns the manifest as a parsed OCI Manifest object. /// - private string GetDigestFromManifest(JObject manifest, out ErrorRecord errRecord, ConcurrentQueue debugMsgs = null) + internal Manifest FetchManifest(string packageName, string version, out ErrorRecord errRecord, ConcurrentQueue debugMsgs = null) { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetDigestFromManifest()"); + debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::FetchManifest()"); errRecord = null; - string digest = String.Empty; - if (manifest == null) + try { - errRecord = new ErrorRecord( - exception: new ArgumentNullException("Manifest (passed in to determine digest) is null."), - "ManifestNullError", - ErrorCategory.InvalidArgument, - _cmdletPassedIn); + var repo = CreateOrasRepository(packageName); + var (descriptor, stream) = repo.FetchAsync(version).GetAwaiter().GetResult(); + byte[] manifestBytes; + using (stream) + { + manifestBytes = stream.ReadAllAsync(descriptor).GetAwaiter().GetResult(); + } - return digest; + var manifest = System.Text.Json.JsonSerializer.Deserialize(manifestBytes); + return manifest; } - - JToken layers = manifest["layers"]; - if (layers == null || !layers.HasValues) + catch (Exception e) { errRecord = new ErrorRecord( - exception: new ArgumentNullException("Manifest 'layers' property (passed in to determine digest) is null or does not have values."), - "ManifestLayersNullOrEmptyError", - ErrorCategory.InvalidArgument, + exception: e, + "FetchManifestOrasError", + ErrorCategory.InvalidResult, _cmdletPassedIn); - return digest; - } - - foreach (JObject item in layers) - { - if (item.ContainsKey("digest")) - { - digest = item.GetValue("digest").ToString(); - break; - } + return null; } - - return digest; - } - - /// - /// Gets the manifest for a package (ie repository in container registry terms) from the repository (ie registry in container registry terms) - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal JObject GetContainerRegistryRepositoryManifest(string packageName, string version, string containerRegistryAccessToken, out ErrorRecord errRecord, ConcurrentQueue debugMsgs = null) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetContainerRegistryRepositoryManifest()"); - // example of manifestUrl: https://psgetregistry.azurecr.io/hello-world:3.0.0 - string manifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, version); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - return GetHttpResponseJObjectUsingDefaultHeaders(manifestUrl, HttpMethod.Get, defaultHeaders, out errRecord, debugMsgs: debugMsgs); - } - - /// - /// Get the blob for the package (ie repository in container registry terms) from the repository (ie registry in container registry terms) - /// Used when installing the package - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal async Task GetContainerRegistryBlobAsync(string packageName, string digest, string containerRegistryAccessToken, ConcurrentQueue debugMsgs = null) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetContainerRegistryBlobAsync()"); - string blobUrl = string.Format(containerRegistryBlobDownloadUrlTemplate, Registry, packageName, digest); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - return await GetHttpContentResponseJObject(blobUrl, defaultHeaders, debugMsgs); - } - - /// - /// Gets the image tags associated with the package (i.e repository in container registry terms), where the tag corresponds to the package's versions. - /// If the package version is specified search for that specific tag for the image, if the package version is "*" search for all tags for the image. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal JObject FindContainerRegistryImageTags(string packageName, string version, string containerRegistryAccessToken, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) - { - /* - { - "name": "", - "tags": [ - "", - "", - "" - ] - } - */ - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::FindContainerRegistryImageTags()"); - string resolvedVersion = string.Equals(version, "*", StringComparison.OrdinalIgnoreCase) ? null : $"/{version}"; - string findImageUrl = string.Format(containerRegistryFindImageVersionUrlTemplate, Registry, packageName); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - return GetHttpResponseJObjectUsingDefaultHeaders(findImageUrl, HttpMethod.Get, defaultHeaders, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - } - - /// - /// Helper method to find all packages on container registry - /// - /// - /// - /// - internal JObject FindAllRepositories(string containerRegistryAccessToken, out ErrorRecord errRecord) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindAllRepositories()"); - string repositoryListUrl = string.Format(containerRegistryRepositoryListTemplate, Registry); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - return GetHttpResponseJObjectUsingDefaultHeaders(repositoryListUrl, HttpMethod.Get, defaultHeaders, out errRecord, usePagination: true); } /// - /// Get metadata for a package version. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. + /// Get metadata for a package version by fetching its manifest and reading annotations. /// - internal Hashtable GetContainerRegistryMetadata(string packageName, string exactTagVersion, string containerRegistryAccessToken, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) + internal Hashtable GetContainerRegistryMetadata(string packageName, string exactTagVersion, out ErrorRecord errRecord, ConcurrentQueue debugMsgs = null) { debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetContainerRegistryMetadata()"); Hashtable requiredVersionResponse = new(); - JObject foundTags = FindContainerRegistryManifest(packageName, exactTagVersion, containerRegistryAccessToken, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); + var manifest = FetchManifest(packageName, exactTagVersion, out errRecord, debugMsgs); if (errRecord != null) { return requiredVersionResponse; } - /* - Response returned looks something like: - { - "schemaVersion": 2, - "config": { - "mediaType": "application/vnd.unknown.config.v1+json", - "digest": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "size": 0 - }, - "layers": [ - { - "mediaType": "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip'", - "digest": "sha256:7c55c7b66cb075628660d8249cc4866f16e34741c246a42ed97fb23ccd4ea956", - "size": 3533, - "annotations": { - "org.opencontainers.image.title": "test_module.1.0.0.nupkg", - "metadata": "{\"GUID\":\"45219bf4-10a4-4242-92d6-9bfcf79878fd\",\"FunctionsToExport\":[],\"CompanyName\":\"Anam\",\"CmdletsToExport\":[],\"VariablesToExport\":\"*\",\"Author\":\"Anam Navied\",\"ModuleVersion\":\"1.0.0\",\"Copyright\":\"(c) Anam Navied. All rights reserved.\",\"PrivateData\":{\"PSData\":{\"Tags\":[\"Test\",\"CommandsAndResource\",\"Tag2\"]}},\"RequiredModules\":[],\"Description\":\"This is a test module, for PSGallery team internal testing. Do not take a dependency on this package. This version contains tags for the package.\",\"AliasesToExport\":[]}" - } - } - ] - } - */ - - ContainerRegistryInfo serverPkgInfo = GetMetadataProperty(foundTags, packageName, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); + ContainerRegistryInfo serverPkgInfo = GetMetadataProperty(manifest, packageName, out errRecord, debugMsgs); if (errRecord != null) { return requiredVersionResponse; @@ -1039,31 +743,15 @@ internal Hashtable GetContainerRegistryMetadata(string packageName, string exact } /// - /// Get the manifest associated with the package version. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal JObject FindContainerRegistryManifest(string packageName, string version, string containerRegistryAccessToken, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::FindContainerRegistryManifest()"); - var createManifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, version); - debugMsgs?.Enqueue($"GET manifest url: {createManifestUrl}"); - - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - return GetHttpResponseJObjectUsingDefaultHeaders(createManifestUrl, HttpMethod.Get, defaultHeaders, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - } - - /// - /// Get metadata for the package by parsing its manifest. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. + /// Get metadata for the package by parsing its OCI manifest annotations. /// - internal ContainerRegistryInfo GetMetadataProperty(JObject foundTags, string packageName, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) + internal ContainerRegistryInfo GetMetadataProperty(Manifest manifest, string packageName, out ErrorRecord errRecord, ConcurrentQueue debugMsgs = null) { debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetMetadataProperty()"); errRecord = null; ContainerRegistryInfo serverPkgInfo = null; - JToken layers = foundTags["layers"]; - if (layers == null || layers[0] == null) + if (manifest == null || manifest.Layers == null || manifest.Layers.Count == 0 || manifest.Layers[0] == null) { errRecord = new ErrorRecord( new InvalidOrEmptyResponse($"Response does not contain 'layers' element in manifest for package '{packageName}' in '{Repository.Name}'."), @@ -1074,7 +762,7 @@ internal ContainerRegistryInfo GetMetadataProperty(JObject foundTags, string pac return serverPkgInfo; } - JToken annotations = layers[0]["annotations"]; + var annotations = manifest.Layers[0].Annotations; if (annotations == null) { errRecord = new ErrorRecord( @@ -1087,11 +775,10 @@ internal ContainerRegistryInfo GetMetadataProperty(JObject foundTags, string pac } // Check for package name - JToken pkgTitleJToken = annotations["org.opencontainers.image.title"]; - if (pkgTitleJToken == null) + if (!annotations.TryGetValue("org.opencontainers.image.title", out string metadataPkgName) || string.IsNullOrWhiteSpace(metadataPkgName)) { errRecord = new ErrorRecord( - new InvalidOrEmptyResponse($"Response does not contain 'org.opencontainers.image.title' element for package '{packageName}' in '{Repository.Name}'."), + new InvalidOrEmptyResponse($"Response does not contain or has empty 'org.opencontainers.image.title' element for package '{packageName}' in '{Repository.Name}'."), "GetMetadataPropertyOCITitleError", ErrorCategory.InvalidData, this); @@ -1099,21 +786,8 @@ internal ContainerRegistryInfo GetMetadataProperty(JObject foundTags, string pac return serverPkgInfo; } - string metadataPkgName = pkgTitleJToken.ToString(); - if (string.IsNullOrWhiteSpace(metadataPkgName)) - { - errRecord = new ErrorRecord( - new InvalidOrEmptyResponse($"Response element 'org.opencontainers.image.title' is empty for package '{packageName}' in '{Repository.Name}'."), - "GetMetadataPropertyOCITitleEmptyError", - ErrorCategory.InvalidData, - this); - - return serverPkgInfo; - } - // Check for package metadata - JToken pkgMetadataJToken = annotations["metadata"]; - if (pkgMetadataJToken == null) + if (!annotations.TryGetValue("metadata", out string metadata) || metadata == null) { errRecord = new ErrorRecord( new InvalidOrEmptyResponse($"Response does not contain 'metadata' element in manifest for package '{packageName}' in '{Repository.Name}'."), @@ -1124,408 +798,20 @@ internal ContainerRegistryInfo GetMetadataProperty(JObject foundTags, string pac return serverPkgInfo; } - string metadata = pkgMetadataJToken.ToString(); - // Check for package artifact type - JToken resourceTypeJToken = annotations["resourceType"]; - var resourceType = resourceTypeJToken != null ? resourceTypeJToken.ToString() : "None"; + annotations.TryGetValue("resourceType", out string resourceType); + resourceType = resourceType ?? "None"; return new ContainerRegistryInfo(metadataPkgName, metadata, resourceType); } + #endregion + + #region Publish Methods + /// - /// Upload manifest for the package, used for publishing. - /// - internal async Task UploadManifest(string packageName, string packageVersion, string configPath, bool isManifest, string containerRegistryAccessToken) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::UploadManifest()"); - try - { - var createManifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, packageVersion); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - return await PutRequestAsync(createManifestUrl, configPath, isManifest, defaultHeaders); - } - catch (HttpRequestException e) - { - throw new HttpRequestException("Error occurred while trying to create manifest: " + e.Message); - } - } - - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - internal async Task GetHttpContentResponseJObject(string url, Collection> defaultHeaders, ConcurrentQueue debugMsgs = null) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetHttpContentResponseJObject()"); - try - { - HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); - SetDefaultHeaders(defaultHeaders); - return await SendContentRequestAsync(request); - } - catch (HttpRequestException e) - { - throw new HttpRequestException("Error occurred while trying to retrieve response: " + e.Message); - } - } - - /// - /// Get response object when using default headers in the request. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal JObject GetHttpResponseJObjectUsingDefaultHeaders(string url, HttpMethod method, Collection> defaultHeaders, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null, bool usePagination = false) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetHttpResponseJObjectUsingDefaultHeaders()"); - try - { - errRecord = null; - HttpRequestMessage request = new HttpRequestMessage(method, url); - SetDefaultHeaders(defaultHeaders); - - var response = usePagination ? SendRequestAsyncWithPagination(request) : SendRequestAsync(request); - return response.GetAwaiter().GetResult(); - } - catch (ResourceNotFoundException e) - { - errRecord = new ErrorRecord( - exception: e, - "ResourceNotFound", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - catch (UnauthorizedException e) - { - errRecord = new ErrorRecord( - exception: e, - "UnauthorizedRequest", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - catch (HttpRequestException e) - { - errRecord = new ErrorRecord( - exception: e, - "HttpRequestCallFailure", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - catch (Exception e) - { - errRecord = new ErrorRecord( - exception: e, - "HttpRequestCallFailure", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - - return null; - } - - /// - /// Get response object when using content headers in the request. - /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. - /// - internal JObject GetHttpResponseJObjectUsingContentHeaders(string url, HttpMethod method, string content, Collection> contentHeaders, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) - { - debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetHttpResponseJObjectUsingContentHeaders()"); - errRecord = null; - try - { - HttpRequestMessage request = new HttpRequestMessage(method, url); - - // HTTP GET does not expect a body / content. - if (method != HttpMethod.Get) - { - - if (string.IsNullOrEmpty(content)) - { - errRecord = new ErrorRecord( - exception: new ArgumentNullException($"Content is null or empty and cannot be used to make a request as its content headers."), - "RequestContentHeadersNullOrEmpty", - ErrorCategory.InvalidData, - _cmdletPassedIn); - - return null; - } - - // codeql[cs/sensitive-data-transmission] This is expected PSResourceGet behavior to create the content of the request which is only transmitted to the server, not the user. This information is also not exposed back to the user via error or verbose messaging. - request.Content = new StringContent(content); - request.Content.Headers.Clear(); - if (contentHeaders != null) - { - foreach (var header in contentHeaders) - { - request.Content.Headers.Add(header.Key, header.Value); - } - } - } - - return SendRequestAsync(request).GetAwaiter().GetResult(); - } - catch (ResourceNotFoundException e) - { - errRecord = new ErrorRecord( - exception: e, - "ResourceNotFound", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - catch (UnauthorizedException e) - { - errRecord = new ErrorRecord( - exception: e, - "UnauthorizedRequest", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - catch (HttpRequestException e) - { - errRecord = new ErrorRecord( - exception: e, - "HttpRequestCallFailure", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - catch (Exception e) - { - errRecord = new ErrorRecord( - exception: e, - "HttpRequestCallFailure", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - } - - return null; - } - - /// - /// Get response headers. - /// - internal async Task GetHttpResponseHeader(string url, HttpMethod method, Collection> defaultHeaders) - { - try - { - HttpRequestMessage request = new HttpRequestMessage(method, url); - SetDefaultHeaders(defaultHeaders); - return await SendRequestHeaderAsync(request); - } - catch (HttpRequestException e) - { - throw new HttpRequestException("Error occurred while trying to retrieve response header: " + e.Message); - } - } - - /// - /// Set default headers for HttpClient. - /// - private void SetDefaultHeaders(Collection> defaultHeaders) - { - _sessionClient.DefaultRequestHeaders.Clear(); - if (defaultHeaders != null) - { - foreach (var header in defaultHeaders) - { - if (string.Equals(header.Key, "Authorization", StringComparison.OrdinalIgnoreCase)) - { - _sessionClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", header.Value); - } - else if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase)) - { - _sessionClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(header.Value)); - } - else - { - _sessionClient.DefaultRequestHeaders.Add(header.Key, header.Value); - } - } - } - } - - /// - /// Sends request for content. - /// - private async Task SendContentRequestAsync(HttpRequestMessage message) - { - try - { - HttpResponseMessage response = await _sessionClient.SendAsync(message); - response.EnsureSuccessStatusCode(); - return response.Content; - } - catch (Exception e) - { - throw new SendRequestException($"Error occurred while sending request to Container Registry server for content with: {e.GetType()} '{e.Message}'", e); - } - } - - /// - /// Sends HTTP request. - /// - private async Task SendRequestAsync(HttpRequestMessage message) - { - HttpResponseMessage response; - try - { - response = await _sessionClient.SendAsync(message); - } - catch (Exception e) - { - throw new SendRequestException($"Error occurred while sending request to Container Registry server with: {e.GetType()} '{e.Message}'", e); - } - - switch (response.StatusCode) - { - case HttpStatusCode.OK: - break; - - case HttpStatusCode.Unauthorized: - throw new UnauthorizedException($"Response returned status code: {response.ReasonPhrase}."); - - case HttpStatusCode.NotFound: - throw new ResourceNotFoundException($"Response returned status code package: {response.ReasonPhrase}."); - - default: - throw new Exception($"Response returned error with status code {response.StatusCode}: {response.ReasonPhrase}."); - } - - return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync()); - } - - private async Task SendRequestAsyncWithPagination(HttpRequestMessage initialMessage) - { - HttpResponseMessage response; - string nextUrl = initialMessage.RequestUri.ToString(); - string urlBase = initialMessage.RequestUri.Scheme + "://" + initialMessage.RequestUri.Host; - JObject finalResult = new JObject(); - JArray allRepositories = new JArray(); - - do - { - var message = new HttpRequestMessage(HttpMethod.Get, nextUrl); - try - { - response = await _sessionClient.SendAsync(message); - } - catch (Exception e) - { - throw new SendRequestException($"Error occurred while sending request to Container Registry server with: {e.GetType()} '{e.Message}'", e); - } - - switch (response.StatusCode) - { - case HttpStatusCode.OK: - break; - case HttpStatusCode.Unauthorized: - throw new UnauthorizedException($"Response returned status code: {response.ReasonPhrase}."); - case HttpStatusCode.NotFound: - throw new ResourceNotFoundException($"Response returned status code package: {response.ReasonPhrase}."); - default: - throw new Exception($"Response returned error with status code {response.StatusCode}: {response.ReasonPhrase}."); - } - - var content = await response.Content.ReadAsStringAsync(); - var json = JObject.Parse(content); - var repositories = json["repositories"] as JArray; - if (repositories != null) - { - allRepositories.Merge(repositories); - } - - // Check for Link header to continue pagination - if (response.Headers.TryGetValues("Link", out var linkHeaders)) - { - var linkHeader = string.Join(",", linkHeaders); - var match = Regex.Match(linkHeader, @"<([^>]+)>;\s*rel=""next"""); - var nextUrlPart = match.Success ? match.Groups[1].Value : null; - if (!string.IsNullOrEmpty(nextUrlPart)) - { - nextUrl = urlBase + nextUrlPart; - } - else - { - nextUrl = null; - } - } - else - { - nextUrl = null; - } - - } while (!string.IsNullOrEmpty(nextUrl)); - - finalResult["repositories"] = allRepositories; - return finalResult; - } - - /// - /// Send request to get response headers. - /// - private async Task SendRequestHeaderAsync(HttpRequestMessage message) - { - try - { - HttpResponseMessage response = await _sessionClient.SendAsync(message); - response.EnsureSuccessStatusCode(); - return response.Headers; - } - catch (HttpRequestException e) - { - throw new HttpRequestException("Error occurred while trying to retrieve response: " + e.Message); - } - } - - /// - /// Sends a PUT request, used for publishing to container registry. - /// - private async Task PutRequestAsync(string url, string filePath, bool isManifest, Collection> contentHeaders) - { - try - { - SetDefaultHeaders(contentHeaders); - - FileInfo fileInfo = new FileInfo(filePath); - using (FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read)) - { - HttpContent httpContent = new StreamContent(fileStream); - if (isManifest) - { - httpContent.Headers.Add("Content-Type", "application/vnd.oci.image.manifest.v1+json"); - } - else - { - httpContent.Headers.Add("Content-Type", "application/octet-stream"); - } - - return await _sessionClient.PutAsync(url, httpContent); - } - } - catch (Exception e) - { - throw new SendRequestException($"Error occurred while uploading module to ContainerRegistry: {e.GetType()} '{e.Message}'", e); - } - } - - /// - /// Get the default headers associated with the access token. - /// - private static Collection> GetDefaultHeaders(string containerRegistryAccessToken) - { - var defaultHeaders = new Collection>(); - - if (!string.IsNullOrEmpty(containerRegistryAccessToken)) - { - defaultHeaders.Add(new KeyValuePair("Authorization", containerRegistryAccessToken)); - } - - defaultHeaders.Add(new KeyValuePair("Accept", "application/vnd.oci.image.manifest.v1+json")); - - return defaultHeaders; - } - - #endregion - - #region Publish Methods - /// - /// Helper method that publishes a package to the container registry. - /// This gets called from Publish-PSResource. + /// Helper method that publishes a package to the container registry. + /// This gets called from Publish-PSResource. /// internal bool PushNupkgContainerRegistry( string outputNupkgDir, @@ -1540,371 +826,92 @@ internal bool PushNupkgContainerRegistry( out ErrorRecord errRecord) { _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::PushNupkgContainerRegistry()"); + errRecord = null; // if isNupkgPathSpecified, then we need to publish the original .nupkg file, as it may be signed - string fullNupkgFile = isNupkgPathSpecified ? originalNupkgPath : System.IO.Path.Combine(outputNupkgDir, packageName + "." + packageVersion.ToNormalizedString() + ".nupkg"); + string fullNupkgFile = isNupkgPathSpecified ? originalNupkgPath : System.IO.Path.Combine(outputNupkgDir, packageName + "." + packageVersion.ToNormalizedString() + ".nupkg"); string pkgNameForUpload = string.IsNullOrEmpty(modulePrefix) ? packageName : modulePrefix + "/" + packageName; string packageNameLowercase = pkgNameForUpload.ToLower(); - // Get access token (includes refresh tokens) - _cmdletPassedIn.WriteVerbose($"Get access token for container registry server."); - ConcurrentQueue errorMsgs = new ConcurrentQueue(); - ConcurrentQueue warningMsgs = new ConcurrentQueue(); - ConcurrentQueue debugMsgs = new ConcurrentQueue(); - ConcurrentQueue verboseMsgs = new ConcurrentQueue(); - ConcurrentQueue informationMsgs = new ConcurrentQueue(); - var containerRegistryAccessToken = GetContainerRegistryAccessToken(needCatalogAccess: false, isPushOperation: true, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs, informationMsgs); - Utils.WriteOutConcurrentQueue(_cmdletPassedIn, errorMsgs, warningMsgs, debugMsgs, verboseMsgs, informationMsgs); - if (errRecord != null) - { - return false; - } - - // Upload .nupkg - _cmdletPassedIn.WriteVerbose($"Upload .nupkg file: {fullNupkgFile}"); - string nupkgDigest = UploadNupkgFile(packageNameLowercase, containerRegistryAccessToken, fullNupkgFile, out errRecord); - if (errRecord != null) - { - return false; - } - - // Create config file - var configFilePath = System.IO.Path.Combine(outputNupkgDir, Guid.NewGuid().ToString() + ".json"); - _cmdletPassedIn.WriteVerbose($"Create config file at path: {configFilePath}"); - string configDigest = CreateConfigFile(configFilePath, out errRecord); - if (errRecord != null) - { - return false; - } - - UploadConfigFile(configFilePath, configDigest, packageNameLowercase, containerRegistryAccessToken, out errRecord); - if (errRecord != null) + if (Repository.CredentialInfo == null) { - return false; - } - - _cmdletPassedIn.WriteVerbose("Create package version metadata as JSON string"); - // Create module metadata string - string metadataJson = CreateMetadataContent(resourceType, parsedMetadataHash, out errRecord); - if (errRecord != null) - { - return false; + // Publishing requires authentication even when the registry permits anonymous pulls. + _cmdletPassedIn.WriteInformation( + "Value of isRepositoryUnauthenticated: False", + new[] { "PSRGContainerRegistryUnauthenticatedCheck" }); } - // Create and upload manifest - TryCreateAndUploadManifest(fullNupkgFile, nupkgDigest, configDigest, packageName, modulePrefix, resourceType, metadataJson, configFilePath, packageVersion, containerRegistryAccessToken, out errRecord); - if (errRecord != null) - { - return false; - } - - return true; - } - - /// - /// Upload the nupkg file, by creating a digest for it and uploading as blob. - /// Note: ContainerRegistry registries will only accept a name that is all lowercase. - /// - private string UploadNupkgFile(string packageNameLowercase, string containerRegistryAccessToken, string fullNupkgFile, out ErrorRecord errRecord) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::UploadNupkgFile()"); - _cmdletPassedIn.WriteVerbose("Start uploading blob"); - string nupkgDigest = string.Empty; - errRecord = null; - string moduleLocation; try { - moduleLocation = GetStartUploadBlobLocation(packageNameLowercase, containerRegistryAccessToken).Result; - } - catch (Exception startUploadException) - { - errRecord = new ErrorRecord( - startUploadException, - "StartUploadBlobLocationError", - ErrorCategory.InvalidResult, - _cmdletPassedIn); + var repo = CreateOrasRepository(packageNameLowercase); - return nupkgDigest; - } + // Read the nupkg file bytes + _cmdletPassedIn.WriteVerbose($"Reading .nupkg file: {fullNupkgFile}"); + byte[] nupkgBytes = File.ReadAllBytes(fullNupkgFile); - _cmdletPassedIn.WriteVerbose("Computing digest for .nupkg file"); - nupkgDigest = CreateDigest(fullNupkgFile, out errRecord); - if (errRecord != null) - { - return nupkgDigest; - } - - _cmdletPassedIn.WriteVerbose("Finish uploading blob"); - try - { - var responseNupkg = EndUploadBlob(moduleLocation, fullNupkgFile, nupkgDigest, isManifest: false, containerRegistryAccessToken).Result; - bool uploadSuccessful = responseNupkg.IsSuccessStatusCode; - - if (!uploadSuccessful) + // Create metadata JSON string + _cmdletPassedIn.WriteVerbose("Create package version metadata as JSON string"); + string metadataJson = CreateMetadataContent(resourceType, parsedMetadataHash, out errRecord); + if (errRecord != null) { - errRecord = new ErrorRecord( - new UploadBlobException("Uploading of blob for publish failed."), - "EndUploadBlobError", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - - return nupkgDigest; + return false; } - } - catch (Exception endUploadException) - { - errRecord = new ErrorRecord( - endUploadException, - "EndUploadBlobError", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - - return nupkgDigest; - } - - return nupkgDigest; - } - /// - /// Uploads the config file referenced by the package manifest. - /// - private void UploadConfigFile(string configFilePath, string configDigest, string pkgNameLower, string containerRegistryAccessToken, out ErrorRecord errRecord) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::UploadConfigFile()"); - errRecord = null; - - try - { - _cmdletPassedIn.WriteVerbose("Start uploading the config file"); - string configLocation = GetStartUploadBlobLocation(pkgNameLower, containerRegistryAccessToken).Result; + var fileName = System.IO.Path.GetFileName(fullNupkgFile); - _cmdletPassedIn.WriteVerbose("Finish uploading the config file"); - var configResponse = EndUploadBlob(configLocation, configFilePath, configDigest, false, containerRegistryAccessToken).Result; - bool uploadSuccessful = configResponse.IsSuccessStatusCode; - - if (!uploadSuccessful) + // Create layer descriptor for the nupkg with annotations + var nupkgDescriptor = Descriptor.Create(nupkgBytes, OrasProject.Oras.Oci.MediaType.ImageLayerGzip); + nupkgDescriptor.Annotations = new Dictionary { - errRecord = new ErrorRecord( - new UploadBlobException($"Error occurred while uploading blob, response code was: {configResponse.StatusCode} with reason {configResponse.ReasonPhrase}"), - "UploadConfigFileError", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - - return; - } - } - catch (Exception e) - { - errRecord = new ErrorRecord( - e, - "UploadConfigFileError", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - - return; - } - } - - /// - /// Create config file associated with the package (i.e repository in container registry terms) as is needed for the package's manifest config layer - /// - private string CreateConfigFile(string configFilePath, out ErrorRecord errRecord) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::CreateConfigFile()"); - string configFileDigest = string.Empty; - _cmdletPassedIn.WriteVerbose("Create the config file"); - try - { - File.WriteAllText(configFilePath, emptyConfigContent); - - _cmdletPassedIn.WriteVerbose("Computing digest for config"); - configFileDigest = CreateDigest(configFilePath, out errRecord); - if (errRecord != null) + ["org.opencontainers.image.title"] = packageName, + ["org.opencontainers.image.description"] = fileName, + ["metadata"] = metadataJson, + ["resourceType"] = resourceType.ToString() + }; + + // Push the nupkg layer + _cmdletPassedIn.WriteVerbose($"Pushing .nupkg blob for {packageNameLowercase}"); + repo.PushAsync(nupkgDescriptor, new MemoryStream(nupkgBytes)).GetAwaiter().GetResult(); + + // Create config descriptor + byte[] configBytes = Encoding.UTF8.GetBytes("{}"); + var configDescriptor = Descriptor.Create(configBytes, OrasProject.Oras.Oci.MediaType.ImageConfig); + using (var configStream = new MemoryStream(configBytes)) { - return configFileDigest; + repo.PushAsync(configDescriptor, configStream).GetAwaiter().GetResult(); } - } - catch (Exception e) - { - errRecord = new ErrorRecord( - e, - "CreateConfigFileError", - ErrorCategory.InvalidResult, - _cmdletPassedIn); - - return configFileDigest; - } - - return configFileDigest; - } - /// - /// Create the manifest for the package and upload it - /// - private bool TryCreateAndUploadManifest(string fullNupkgFile, - string nupkgDigest, - string configDigest, - string packageName, - string modulePrefix, - ResourceType resourceType, - string metadataJson, - string configFilePath, - NuGetVersion pkgVersion, - string containerRegistryAccessToken, - out ErrorRecord errRecord) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::TryCreateAndUploadManifest()"); - errRecord = null; - - string pkgNameForUpload = string.IsNullOrEmpty(modulePrefix) ? packageName : modulePrefix + "/" + packageName; - string packageNameLowercase = pkgNameForUpload.ToLower(); + // Pack and push the manifest using Packer + _cmdletPassedIn.WriteVerbose("Packing and pushing manifest"); + var packOptions = new PackManifestOptions + { + Config = configDescriptor, + Layers = new List { nupkgDescriptor } + }; - FileInfo nupkgFile = new FileInfo(fullNupkgFile); - var fileSize = nupkgFile.Length; - var fileName = System.IO.Path.GetFileName(fullNupkgFile); - string fileContent = CreateManifestContent(nupkgDigest, configDigest, fileSize, fileName, packageName, resourceType, metadataJson); - File.WriteAllText(configFilePath, fileContent); + var manifestDescriptor = Packer.PackManifestAsync(repo, Packer.ManifestVersion.Version1_1, "", packOptions).GetAwaiter().GetResult(); - _cmdletPassedIn.WriteVerbose("Create the manifest layer"); - bool manifestCreated = false; - try - { - HttpResponseMessage manifestResponse = UploadManifest(packageNameLowercase, pkgVersion.OriginalVersion, configFilePath, true, containerRegistryAccessToken).Result; - manifestCreated = manifestResponse.IsSuccessStatusCode; + // Tag the manifest with the version + _cmdletPassedIn.WriteVerbose($"Tagging manifest with version: {packageVersion.OriginalVersion}"); + repo.TagAsync(manifestDescriptor, packageVersion.OriginalVersion).GetAwaiter().GetResult(); } catch (Exception e) { errRecord = new ErrorRecord( - new UploadBlobException($"Error occurred while uploading package manifest to ContainerRegistry: {e.GetType()} '{e.Message}'", e), - "PackageManifestUploadError", + new UploadBlobException($"Error occurred while publishing package to ContainerRegistry: {e.GetType()} '{e.Message}'", e), + "PackagePublishOrasError", ErrorCategory.InvalidResult, _cmdletPassedIn); - return manifestCreated; - } - - return manifestCreated; - } - - /// - /// Create the content for the manifest for the packge. - /// - private string CreateManifestContent( - string nupkgDigest, - string configDigest, - long nupkgFileSize, - string fileName, - string packageName, - ResourceType resourceType, - string metadata) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::CreateManifestContent()"); - StringBuilder stringBuilder = new StringBuilder(); - StringWriter stringWriter = new StringWriter(stringBuilder); - JsonTextWriter jsonWriter = new JsonTextWriter(stringWriter); - - jsonWriter.Formatting = Newtonsoft.Json.Formatting.Indented; - - // start of manifest JSON object - jsonWriter.WriteStartObject(); - - jsonWriter.WritePropertyName("schemaVersion"); - jsonWriter.WriteValue(2); - jsonWriter.WritePropertyName("mediaType"); - jsonWriter.WriteValue("application/vnd.oci.image.manifest.v1+json"); - - jsonWriter.WritePropertyName("config"); - jsonWriter.WriteStartObject(); - jsonWriter.WritePropertyName("mediaType"); - jsonWriter.WriteValue("application/vnd.oci.image.config.v1+json"); - jsonWriter.WritePropertyName("digest"); - jsonWriter.WriteValue($"sha256:{configDigest}"); - jsonWriter.WritePropertyName("size"); - jsonWriter.WriteValue(Encoding.UTF8.GetByteCount(emptyConfigContent)); - jsonWriter.WriteEndObject(); - - jsonWriter.WritePropertyName("layers"); - jsonWriter.WriteStartArray(); - - jsonWriter.WriteStartObject(); - jsonWriter.WritePropertyName("mediaType"); - jsonWriter.WriteValue("application/vnd.oci.image.layer.v1.tar+gzip"); - jsonWriter.WritePropertyName("digest"); - jsonWriter.WriteValue($"sha256:{nupkgDigest}"); - jsonWriter.WritePropertyName("size"); - jsonWriter.WriteValue(nupkgFileSize); - jsonWriter.WritePropertyName("annotations"); - jsonWriter.WriteStartObject(); - jsonWriter.WritePropertyName("org.opencontainers.image.title"); - jsonWriter.WriteValue(packageName); - jsonWriter.WritePropertyName("org.opencontainers.image.description"); - jsonWriter.WriteValue(fileName); - jsonWriter.WritePropertyName("metadata"); - jsonWriter.WriteValue(metadata); - jsonWriter.WritePropertyName("resourceType"); - jsonWriter.WriteValue(resourceType.ToString()); - jsonWriter.WriteEndObject(); // end of annotations object - - jsonWriter.WriteEndObject(); // end of 'layers' entry object - - jsonWriter.WriteEndArray(); // end of 'layers' array - jsonWriter.WriteEndObject(); // end of manifest JSON object - - return stringWriter.ToString(); - } - - /// - /// Create SHA256 digest that will be associated with .nupkg, config file or empty file. - /// - private string CreateDigest(string fileName, out ErrorRecord errRecord) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::CreateDigest()"); - errRecord = null; - string digest = string.Empty; - FileInfo fileInfo = new FileInfo(fileName); - SHA256 mySHA256 = SHA256.Create(); - - using (FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read)) - { - try - { - // Create a fileStream for the file. - // Be sure it's positioned to the beginning of the stream. - fileStream.Position = 0; - // Compute the hash of the fileStream. - byte[] hashValue = mySHA256.ComputeHash(fileStream); - StringBuilder stringBuilder = new StringBuilder(); - foreach (byte b in hashValue) - { - stringBuilder.AppendFormat("{0:x2}", b); - } - - digest = stringBuilder.ToString(); - } - catch (IOException ex) - { - errRecord = new ErrorRecord(ex, $"IOException for .nupkg file: {ex.Message}", ErrorCategory.InvalidOperation, null); - return digest; - } - catch (UnauthorizedAccessException ex) - { - errRecord = new ErrorRecord(ex, $"UnauthorizedAccessException for .nupkg file: {ex.Message}", ErrorCategory.PermissionDenied, null); - return digest; - } - catch (Exception ex) - { - errRecord = new ErrorRecord(ex, $"Exception when creating digest: {ex.Message}", ErrorCategory.PermissionDenied, null); - return digest; - } + return false; } - - if (String.IsNullOrEmpty(digest)) + finally { - errRecord = new ErrorRecord(new ArgumentNullException("Digest created was null or empty."), "DigestNullOrEmptyError.", ErrorCategory.InvalidResult, null); + Utils.WriteOutConcurrentQueue(_cmdletPassedIn, new ConcurrentQueue(), _credentialProvider.WarningMsgs, new ConcurrentQueue(), _credentialProvider.VerboseMsgs); } - return digest; + return true; } /// @@ -1951,42 +958,6 @@ private string CreateMetadataContent(ResourceType resourceType, Hashtable parsed return jsonString; } - /// - /// Get start location when uploading blob, used during publish. - /// - internal async Task GetStartUploadBlobLocation(string packageName, string containerRegistryAccessToken) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetStartUploadBlobLocation()"); - try - { - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - var startUploadUrl = string.Format(containerRegistryStartUploadTemplate, Registry, packageName); - return (await GetHttpResponseHeader(startUploadUrl, HttpMethod.Post, defaultHeaders)).Location.ToString(); - } - catch (Exception e) - { - throw new UploadBlobException($"Error occurred while starting to upload the blob location used for publishing to ContainerRegistry: {e.GetType()} '{e.Message}'", e); - } - } - - /// - /// Upload blob, used for publishing - /// - internal async Task EndUploadBlob(string location, string filePath, string digest, bool isManifest, string containerRegistryAccessToken) - { - _cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::EndUploadBlob()"); - try - { - var endUploadUrl = string.Format(containerRegistryEndUploadTemplate, Registry, location, digest); - var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken); - return await PutRequestAsync(endUploadUrl, filePath, isManifest, defaultHeaders); - } - catch (Exception e) - { - throw new UploadBlobException($"Error occurred while uploading module to ContainerRegistry: {e.GetType()} '{e.Message}'", e); - } - } - #endregion #region Find Helper Methods @@ -1998,26 +969,18 @@ internal async Task EndUploadBlob(string location, string f private Hashtable[] FindPackagesWithVersionHelper(string packageName, VersionType versionType, VersionRange versionRange, NuGetVersion requiredVersion, bool includePrerelease, bool getOnlyLatest, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) { debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::FindPackagesWithVersionHelper()"); - string accessToken = string.Empty; - string tenantID = string.Empty; - string registryUrl = Repository.Uri.ToString(); string packageNameLowercase = packageName.ToLower(); string packageNameForFind = PrependMARPrefix(packageNameLowercase); - string containerRegistryAccessToken = GetContainerRegistryAccessToken(needCatalogAccess: false, isPushOperation: false, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null) - { - return emptyHashResponses; - } - var foundTags = FindContainerRegistryImageTags(packageNameForFind, "*", containerRegistryAccessToken, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null || foundTags == null) + var allVersionsList = ListImageTags(packageNameForFind, out errRecord, debugMsgs); + DrainCredentialMessages(warningMsgs, verboseMsgs); + if (errRecord != null || allVersionsList == null) { return emptyHashResponses; } List latestVersionResponse = new List(); - List allVersionsList = foundTags["tags"].ToList(); SortedDictionary sortedQualifyingPkgs = GetPackagesWithRequiredVersion(allVersionsList, versionType, versionRange, requiredVersion, packageNameForFind, includePrerelease, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); if (errRecord != null && sortedQualifyingPkgs?.Count == 0) @@ -2031,7 +994,8 @@ private Hashtable[] FindPackagesWithVersionHelper(string packageName, VersionTyp foreach (var pkgVersionTag in pkgsInDescendingOrder) { string exactTagVersion = pkgVersionTag.Value.ToString(); - Hashtable metadata = GetContainerRegistryMetadata(packageNameForFind, exactTagVersion, containerRegistryAccessToken, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); + Hashtable metadata = GetContainerRegistryMetadata(packageNameForFind, exactTagVersion, out errRecord, debugMsgs); + DrainCredentialMessages(warningMsgs, verboseMsgs); if (errRecord != null || metadata.Count == 0) { return emptyHashResponses; @@ -2052,17 +1016,15 @@ private Hashtable[] FindPackagesWithVersionHelper(string packageName, VersionTyp /// Helper method used for find scenarios that resolves versions required from all versions found. /// Note: ConcurrentQueues default to null because the method calls both concurrent methods and synchronous methods. Synchronous methods may not have queues to pass in. /// - private SortedDictionary GetPackagesWithRequiredVersion(List allPkgVersions, VersionType versionType, VersionRange versionRange, NuGetVersion specificVersion, string packageName, bool includePrerelease, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) + private SortedDictionary GetPackagesWithRequiredVersion(List allPkgVersions, VersionType versionType, VersionRange versionRange, NuGetVersion specificVersion, string packageName, bool includePrerelease, out ErrorRecord errRecord, ConcurrentQueue errorMsgs = null, ConcurrentQueue warningMsgs = null, ConcurrentQueue debugMsgs = null, ConcurrentQueue verboseMsgs = null) { debugMsgs?.Enqueue("In ContainerRegistryServerAPICalls::GetPackagesWithRequiredVersion()"); errRecord = null; - // we need NuGetVersion to sort versions by order, and string pkgVersionString (which is the exact tag from the server) to call GetContainerRegistryMetadata() later with exact version tag. SortedDictionary sortedPkgs = new SortedDictionary(VersionComparer.Default); bool isSpecificVersionSearch = versionType == VersionType.SpecificVersion; - foreach (var pkgVersionTagInfo in allPkgVersions) + foreach (var pkgVersionString in allPkgVersions) { - string pkgVersionString = pkgVersionTagInfo.ToString(); // determine if the package version that is a repository tag is a valid NuGetVersion if (!NuGetVersion.TryParse(pkgVersionString, out NuGetVersion pkgVersion)) { @@ -2121,14 +1083,8 @@ private FindResults FindPackages(string packageName, bool includePrerelease, out ConcurrentQueue warningMsgs = new ConcurrentQueue(); ConcurrentQueue debugMsgs = new ConcurrentQueue(); ConcurrentQueue verboseMsgs = new ConcurrentQueue(); - string containerRegistryAccessToken = GetContainerRegistryAccessToken(needCatalogAccess: true, isPushOperation: false, out errRecord, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - Utils.WriteOutConcurrentQueue(_cmdletPassedIn, errorMsgs, warningMsgs, debugMsgs, verboseMsgs); - if (errRecord != null) - { - return emptyResponseResults; - } - var pkgResult = FindAllRepositories(containerRegistryAccessToken, out errRecord); + var repositoryNames = ListAllRepositories(out errRecord); if (errRecord != null) { return emptyResponseResults; @@ -2138,10 +1094,8 @@ private FindResults FindPackages(string packageName, bool includePrerelease, out var isMAR = Repository.IsMARRepository(); // Convert the list of repositories to a list of hashtables - foreach (var repository in pkgResult["repositories"].ToList()) + foreach (var repositoryName in repositoryNames) { - string repositoryName = repository.ToString(); - if (isMAR && !repositoryName.StartsWith(PSRepositoryInfo.MARPrefix)) { continue; diff --git a/src/code/FindHelper.cs b/src/code/FindHelper.cs index b9eb4b62a..293cbabce 100644 --- a/src/code/FindHelper.cs +++ b/src/code/FindHelper.cs @@ -207,7 +207,11 @@ public IEnumerable FindByResourceName( { PSRepositoryInfo currentRepository = repositoriesToSearch[i]; - bool isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + bool isAllowed = true; + if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows)) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + } if (!isAllowed) { @@ -395,7 +399,12 @@ public IEnumerable FindByCommandOrDscResource( { PSRepositoryInfo currentRepository = repositoriesToSearch[i]; - bool isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + bool isAllowed = true; + + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + } if (!isAllowed) { @@ -602,7 +611,12 @@ public IEnumerable FindByTag( { PSRepositoryInfo currentRepository = repositoriesToSearch[i]; - bool isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + + bool isAllowed = true; + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + } if (!isAllowed) { @@ -735,7 +749,7 @@ private IEnumerable SearchByNames(ServerApiCall currentServer, R _cmdletPassedIn.WriteDebug("No version specified, package name is '*'"); // Example: Find-PSResource -Name "*" - // Note: Just for resources from V2 servers, specifically PSGallery, if the resource is unlisted and was requested non-explicitly + // Note: Just for resources from V2 servers, specifically PSGallery, if the resource is unlisted and was requested non-explicitly // (i.e requested name has wildcard) the resource should not be returned and ResponseUtil.ConvertToPSResourceResult() call needs to be informed of this. // In all other cases, return the resource regardless of whether it was requested explicitly or not. bool isResourceRequestedWithWildcard = isV2Resource; @@ -785,7 +799,7 @@ private IEnumerable SearchByNames(ServerApiCall currentServer, R // Example: Find-PSResource -Name "Az*" -Tag "Storage" _cmdletPassedIn.WriteDebug("No version specified, package name contains a wildcard."); - // Note: Just for resources from V2 servers, specifically PSGallery, if the resource is unlisted and was requested non-explicitly + // Note: Just for resources from V2 servers, specifically PSGallery, if the resource is unlisted and was requested non-explicitly // (i.e requested name has wildcard) the resource should not be returned and ResponseUtil.ConvertToPSResourceResult() call needs to be informed of this. // In all other cases, return the resource regardless of whether it was requested explicitly or not. bool isResourceRequestedWithWildcard = isV2Resource; diff --git a/src/code/GroupPolicyRepositoryEnforcement.cs b/src/code/GroupPolicyRepositoryEnforcement.cs index ac4f7ee98..8d0be2f64 100644 --- a/src/code/GroupPolicyRepositoryEnforcement.cs +++ b/src/code/GroupPolicyRepositoryEnforcement.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Runtime.Versioning; using Microsoft.PowerShell.PSResourceGet.UtilClasses; using Microsoft.Win32; @@ -14,6 +15,7 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets /// /// This class is used to enforce group policy for repositories. /// + [SupportedOSPlatform("windows")] public class GroupPolicyRepositoryEnforcement { const string userRoot = "HKEY_CURRENT_USER"; @@ -29,6 +31,7 @@ private GroupPolicyRepositoryEnforcement() /// /// /// True if the group policy is enabled, false otherwise. + [SupportedOSPlatform("windows")] public static bool IsGroupPolicyEnabled() { if (Environment.OSVersion.Platform != PlatformID.Win32NT) @@ -57,6 +60,7 @@ public static bool IsGroupPolicyEnabled() /// /// Array of allowed URIs. /// Thrown when the group policy is not enabled. + [SupportedOSPlatform("windows")] public static Uri[]? GetAllowedRepositoryURIs() { if (Environment.OSVersion.Platform != PlatformID.Win32NT) @@ -92,6 +96,7 @@ public static bool IsGroupPolicyEnabled() } } + [SupportedOSPlatform("windows")] internal static bool IsRepositoryAllowed(Uri repositoryUri) { bool isAllowed = false; @@ -113,6 +118,7 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) return isAllowed; } + [SupportedOSPlatform("windows")] private static List>? ReadGPFromRegistry() { List> allowedRepositories = new List>(); @@ -169,7 +175,13 @@ internal static bool IsRepositoryAllowed(Uri repositoryUri) throw new InvalidOperationException("Invalid registry value."); } - string valueString = value.ToString(); + string? valueString = value.ToString(); + + if (string.IsNullOrEmpty(valueString)) + { + throw new InvalidOperationException("Invalid registry value."); + } + var kvRegValue = ConvertRegValue(valueString); allowedRepositories.Add(kvRegValue); } diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index f235696f4..a83f4e5e6 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -278,7 +278,12 @@ private List ProcessRepositories( { PSRepositoryInfo currentRepository = listOfRepositories[i]; - bool isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + bool isAllowed = true; + + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(currentRepository.Uri); + } if (!isAllowed) { diff --git a/src/code/Microsoft.PowerShell.PSResourceGet.csproj b/src/code/Microsoft.PowerShell.PSResourceGet.csproj index 0e02d1ab9..331206e24 100644 --- a/src/code/Microsoft.PowerShell.PSResourceGet.csproj +++ b/src/code/Microsoft.PowerShell.PSResourceGet.csproj @@ -8,12 +8,13 @@ 1.1.0.1 1.1.0.1 1.1.0.1 - net472 - 9.0 + net10.0 + 12.0 true + @@ -21,13 +22,11 @@ - - - + - - - + + + diff --git a/src/code/ModuleInitAndCleanup.cs b/src/code/ModuleInitAndCleanup.cs index 40b1ad182..2f2ca7c0a 100644 --- a/src/code/ModuleInitAndCleanup.cs +++ b/src/code/ModuleInitAndCleanup.cs @@ -21,7 +21,6 @@ public class UnsafeAssemblyHandler : IModuleAssemblyInitializer, IModuleAssembly "System.Threading.Tasks.Extensions", "System.Runtime.CompilerServices.Unsafe", "System.Memory", - "System.Diagnostics.DiagnosticSource", "System.Text.Json", "System.Security.Cryptography.ProtectedData" }; diff --git a/src/code/PSResourceGetCredentialProvider.cs b/src/code/PSResourceGetCredentialProvider.cs new file mode 100644 index 000000000..2abaf4eb4 --- /dev/null +++ b/src/code/PSResourceGetCredentialProvider.cs @@ -0,0 +1,169 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Collections.Concurrent; +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 +{ + /// + /// 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 + /// + 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; + internal ConcurrentQueue WarningMsgs { get; } = new ConcurrentQueue(); + internal ConcurrentQueue VerboseMsgs { get; } = new ConcurrentQueue(); + + // 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 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 for nested + // PowerShell script invocations (SecretManagement, etc.). + var previousRunspace = Runspace.DefaultRunspace; + Runspace.DefaultRunspace = _callerRunspace; + + try + { + return await ResolveCredentialCoreAsync(hostname, cancellationToken).ConfigureAwait(false); + } + finally + { + Runspace.DefaultRunspace = previousRunspace; + } + } + + private async Task ResolveCredentialCoreAsync(string hostname, CancellationToken cancellationToken) + { + // Return cached credential if still valid + if (!string.IsNullOrEmpty(_cachedCredential.RefreshToken) && DateTimeOffset.UtcNow < _tokenExpiry) + { + VerboseMsgs.Enqueue("Using cached ORAS credential."); + return _cachedCredential; + } + + string aadAccessToken; + string tenantId; + + var repositoryCredentialInfo = _repository.CredentialInfo; + if (repositoryCredentialInfo != null) + { + // Path 1: Credential from SecretsManagement vault + VerboseMsgs.Enqueue("Retrieving access token from SecretManagement vault."); + aadAccessToken = Utils.GetContainerRegistryAccessTokenFromSecretManagement( + _repository.Name, + repositoryCredentialInfo, + _cmdletPassedIn); + + if (string.IsNullOrEmpty(aadAccessToken)) + { + WarningMsgs.Enqueue("Failed to retrieve access token from SecretManagement vault."); + return new Credential(); + } + + tenantId = repositoryCredentialInfo.SecretName; + } + else + { + // Path 2: Azure Identity via existing Utils helper + VerboseMsgs.Enqueue("Acquiring AAD access token via Utils.GetAzAccessToken."); + aadAccessToken = Utils.GetAzAccessToken(_cmdletPassedIn, WarningMsgs); + + if (string.IsNullOrEmpty(aadAccessToken)) + { + // If Azure Identity fails, return empty credential for anonymous access + VerboseMsgs.Enqueue("No AAD token available; attempting anonymous access."); + return new Credential(); + } + + tenantId = null; + } + + // Exchange AAD access token for ACR refresh token via OAuth2 exchange endpoint + VerboseMsgs.Enqueue("Exchanging AAD access token for ACR refresh token."); + try + { + string refreshToken = await ExchangeForAcrRefreshTokenAsync(aadAccessToken, tenantId, cancellationToken).ConfigureAwait(false); + + if (string.IsNullOrEmpty(refreshToken)) + { + WarningMsgs.Enqueue("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) + { + WarningMsgs.Enqueue($"Failed to exchange AAD token for ACR refresh token: {ex.Message}"); + return new Credential(); + } + } + + /// + /// Exchanges an AAD access token for an ACR refresh token via the OAuth2 exchange endpoint. + /// + private async Task 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; + } + } +} diff --git a/src/code/PublishHelper.cs b/src/code/PublishHelper.cs index 9456609b6..c12bd0cc3 100644 --- a/src/code/PublishHelper.cs +++ b/src/code/PublishHelper.cs @@ -358,7 +358,12 @@ internal void PushResource(string Repository, string modulePrefix, bool SkipDepe return; } - bool isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repository.Uri); + bool isAllowed = true; + + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repository.Uri); + } if (!isAllowed) { diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index 97e78f94d..9fda2dfb6 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -10,6 +10,7 @@ using System.Xml; using System.Xml.Linq; using Microsoft.PowerShell.PSResourceGet.Cmdlets; +using NuGet.Protocol.Core.Types; using static Microsoft.PowerShell.PSResourceGet.UtilClasses.PSRepositoryInfo; namespace Microsoft.PowerShell.PSResourceGet.UtilClasses @@ -316,7 +317,12 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit throw new PSInvalidOperationException(String.Format("Adding to repository store failed: {0}", e.Message)); } - bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repoUri) : true; + bool isAllowed = true; + + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repoUri) : true; + } return new PSRepositoryInfo(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, repoCredentialProvider, apiVersion, isAllowed); } @@ -475,10 +481,13 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio node.Attribute(PSCredentialInfo.SecretNameAttribute).Value); } - if (GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled()) + if (OperatingSystem.IsWindows()) { - var allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs(); + if (GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled()) + { + var allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs(); + } } // Update CredentialProvider if necessary @@ -496,7 +505,12 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio } } - bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; + bool isAllowed = true; + + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; + } updatedRepo = new PSRepositoryInfo(repoName, thisUrl, @@ -592,7 +606,12 @@ public static List Remove(string[] repoNames, out string[] err string attributeUrlUriName = urlAttributeExists ? "Url" : "Uri"; Uri repoUri = new Uri(node.Attribute(attributeUrlUriName).Value); - bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repoUri) : true; + bool isAllowed = true; + + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repoUri) : true; + } removedRepos.Add( new PSRepositoryInfo(repo, @@ -732,7 +751,11 @@ public static List Read(string[] repoNames, out string[] error continue; } - bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; + bool isAllowed = true; + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; + } PSRepositoryInfo currentRepoItem = new PSRepositoryInfo(repo.Attribute("Name").Value, thisUrl, @@ -845,7 +868,12 @@ public static List Read(string[] repoNames, out string[] error continue; } - bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; + bool isAllowed = true; + + if (OperatingSystem.IsWindows()) + { + isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true; + } PSRepositoryInfo currentRepoItem = new PSRepositoryInfo(node.Attribute("Name").Value, thisUrl, diff --git a/src/code/UpdateModuleManifest.cs b/src/code/UpdateModuleManifest.cs index aa8d38e88..3c9093aec 100644 --- a/src/code/UpdateModuleManifest.cs +++ b/src/code/UpdateModuleManifest.cs @@ -604,7 +604,7 @@ private void CreateModuleManifestHelper(Hashtable parsedMetadata, string resolve parsedMetadata["Prerelease"] = Prerelease; } - if (RequireLicenseAcceptance != null && RequireLicenseAcceptance.IsPresent) + if (RequireLicenseAcceptance.IsPresent) { parsedMetadata["RequireLicenseAcceptance"] = RequireLicenseAcceptance; } @@ -953,7 +953,7 @@ private void CreateModuleManifestForWinPSHelper(Hashtable parsedMetadata, string prerelease = Prerelease; } - if (RequireLicenseAcceptance != null && RequireLicenseAcceptance.IsPresent) + if (RequireLicenseAcceptance.IsPresent) { requireLicenseAcceptance = RequireLicenseAcceptance; } diff --git a/src/code/Utils.cs b/src/code/Utils.cs index d8d4555ac..63edece17 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -797,7 +797,7 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement( } } - public static string GetAzAccessToken(PSCmdlet cmdletPassedIn) + public static string GetAzAccessToken(PSCmdlet cmdletPassedIn, ConcurrentQueue warningMsgs = null) { var credOptions = new DefaultAzureCredentialOptions { @@ -824,12 +824,26 @@ public static string GetAzAccessToken(PSCmdlet cmdletPassedIn) } catch (OperationCanceledException) { - cmdletPassedIn.WriteWarning("Timeout occurred while acquiring Azure access token."); + if (warningMsgs != null) + { + warningMsgs.Enqueue("Timeout occurred while acquiring Azure access token."); + } + else + { + cmdletPassedIn.WriteWarning("Timeout occurred while acquiring Azure access token."); + } return null; } catch (Exception ex) { - cmdletPassedIn.WriteWarning($"Failed to acquire Azure access token: {ex.Message}"); + if (warningMsgs != null) + { + warningMsgs.Enqueue($"Failed to acquire Azure access token: {ex.Message}"); + } + else + { + cmdletPassedIn.WriteWarning($"Failed to acquire Azure access token: {ex.Message}"); + } return null; } } @@ -1705,7 +1719,7 @@ public static bool ValidateModuleManifest(string moduleManifestPath, out string return false; } } - + // Check for any errors from Test-ModuleManifest if (pwsh.HadErrors) { @@ -1738,6 +1752,22 @@ public static void WriteVerboseOnCmdlet( catch { } } + public static void WriteWarningOnCmdlet( + PSCmdlet cmdlet, + string message) + { + try + { + cmdlet.InvokeCommand.InvokeScript( + script: $"param ([string] $message) Write-Warning -Message $message", + useNewScope: true, + writeToPipeline: System.Management.Automation.Runspaces.PipelineResultTypes.None, + input: null, + args: new object[] { message }); + } + catch { } + } + /// /// Convert a json string into a hashtable object. /// This uses custom script to perform the PSObject -> Hashtable @@ -1967,7 +1997,9 @@ public static void DeleteDirectoryWithRestore(string dirPath) } catch (Exception e) { - throw e; + throw new PSInvalidOperationException( + $"An error occurred while attempting to delete the directory at path {dirPath} with restore. Error: {e.Message}", + e); } finally { @@ -1998,7 +2030,7 @@ public static void DeleteDirectory(string dirPath) { if (!Directory.Exists(dirPath)) { - throw new Exception($"Path '{dirPath}' that was attempting to be deleted does not exist."); + throw new PSInvalidOperationException($"Path '{dirPath}' that was attempting to be deleted does not exist."); } // Remove read only file attributes first @@ -2035,10 +2067,10 @@ public static void DeleteDirectory(string dirPath) if (ex.Message.Contains("The directory is not empty") && psVersion.StartsWith("5")) { // there is a known bug with WindowsPowerShell and OneDrive based module paths, where .NET Directory.Delete() will throw a 'The directory is not empty.' error. - throw new Exception(string.Format("Cannot uninstall module with OneDrive based path on Windows PowerShell due to .NET issue. Try installing and uninstalling using PowerShell 7+ if using OneDrive."), ex); + throw new PSInvalidOperationException("Cannot uninstall module with OneDrive based path on Windows PowerShell due to .NET issue. Try installing and uninstalling using PowerShell 7+ if using OneDrive.", ex); } - throw new Exception(string.Format("Access denied to path while deleting path {0}", dirPath), ex); + throw new PSInvalidOperationException(string.Format("Access denied to path while deleting path {0}", dirPath), ex); } else { diff --git a/test/PublishPSResourceTests/ContainerRegistryConfig.Tests.ps1 b/test/PublishPSResourceTests/ContainerRegistryConfig.Tests.ps1 index 0cc418d6f..307c460b6 100644 --- a/test/PublishPSResourceTests/ContainerRegistryConfig.Tests.ps1 +++ b/test/PublishPSResourceTests/ContainerRegistryConfig.Tests.ps1 @@ -3,162 +3,232 @@ Import-Module "$PSScriptRoot\..\PSGetTestUtils.psm1" -Force -Describe 'Container registry config blob' -Tags 'CI' { +Describe 'Container registry ORAS transport' -Tags 'CI' { BeforeAll { Add-Type -AssemblyName System.Net.Http $references = @( [System.Net.Http.HttpClient].Assembly.Location [System.Net.HttpStatusCode].Assembly.Location + [Security.Cryptography.SHA256].Assembly.Location ) Add-Type -ReferencedAssemblies $references -TypeDefinition @' using System; using System.Net; using System.Net.Http; +using System.Security.Cryptography; +using System.Text; using System.Threading; using System.Threading.Tasks; public class ConfigBlobUploadHandler : HttpMessageHandler { + public static object InvokeOnWorker(object api, string methodName, object[] arguments) + { + return Task.Run(async () => + { + var task = (Task)api.GetType().GetMethod(methodName).Invoke(api, arguments); + await task.ConfigureAwait(false); + return task.GetType().GetProperty("Result").GetValue(task); + }).GetAwaiter().GetResult(); + } + public byte[] UploadedContent { get; private set; } public byte[] UploadedManifest { get; private set; } + public byte[] UploadedPackage { get; private set; } public Uri UploadUri { get; private set; } public HttpStatusCode UploadStatusCode = HttpStatusCode.Created; protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + string path = request.RequestUri.AbsolutePath; + if (request.Method == HttpMethod.Head) + { + return new HttpResponseMessage(HttpStatusCode.NotFound); + } + + if (request.Method == HttpMethod.Get) + { + if (path.EndsWith("/tags/list")) + { + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent("{\"name\":\"test\",\"tags\":[\"1.0.0\"]}") + }; + } + + byte[] bytes = path.Contains("/manifests/") ? UploadedManifest : UploadedPackage; + if (bytes == null) + { + return new HttpResponseMessage(HttpStatusCode.NotFound); + } + + var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(bytes) }; + response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue( + path.Contains("/manifests/") ? "application/vnd.oci.image.manifest.v1+json" : "application/octet-stream"); + response.Headers.Add("Docker-Content-Digest", "sha256:" + Convert.ToHexString(SHA256.HashData(bytes)).ToLowerInvariant()); + return response; + } + if (request.Method == HttpMethod.Post) { var response = new HttpResponseMessage(HttpStatusCode.Accepted); - response.Headers.Location = new Uri("/v2/test/blobs/uploads/id?upload=1", UriKind.Relative); + response.Headers.Location = new Uri("https://registry.example/v2/test/blobs/uploads/id?upload=1"); return response; } var content = await request.Content.ReadAsByteArrayAsync(); - if (request.RequestUri.AbsolutePath.Contains("/manifests/")) + if (path.Contains("/manifests/")) { UploadedManifest = content; } - else + else if (Encoding.UTF8.GetString(content) == "{}") { UploadedContent = content; UploadUri = request.RequestUri; } + else + { + UploadedPackage = content; + } return new HttpResponseMessage(UploadStatusCode); } } '@ - function Invoke-ContainerRegistryMethod { + function New-ContainerRegistryApi { [CmdletBinding()] - param($MethodName, [object[]] $MethodArguments, $Handler) + param($Handler) $type = [Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource].Assembly.GetType('Microsoft.PowerShell.PSResourceGet.ContainerRegistryServerAPICalls') $repository = [Microsoft.PowerShell.PSResourceGet.UtilClasses.PSRepositoryInfo]::new( 'Test', [uri]'https://registry.example', 50, $true, $null, 'None', 'ContainerRegistry', $true) $api = [Activator]::CreateInstance($type, @($repository, $PSCmdlet, $null, 'test')) $flags = [Reflection.BindingFlags]'Instance,NonPublic' - $clientProperty = $type.GetProperty('_sessionClient', $flags) - try { - if ($Handler) { - $clientProperty.GetValue($api).Dispose() - $clientProperty.SetValue($api, [System.Net.Http.HttpClient]::new($Handler)) - $type.GetField('_cachedContainterRegistryToken', $flags).SetValue($api, 'test-token') - } + $clientField = $type.GetField('_orasClient', $flags) + $oldClient = $clientField.GetValue($api) + $client = [System.Net.Http.HttpClient]::new($Handler) + $replacement = [Activator]::CreateInstance($oldClient.GetType(), @($client, $oldClient.CredentialProvider, $oldClient.Cache)) + $clientField.SetValue($api, $replacement) + $type.GetField('_httpClient', $flags).GetValue($api).Dispose() + $type.GetField('_httpClient', $flags).SetValue($api, $client) + return $api + } - for ($i = 0; $i -lt $MethodArguments.Length; $i++) { - if ($null -ne $MethodArguments[$i]) { - $MethodArguments[$i] = $MethodArguments[$i].PSObject.BaseObject - } - } + function Invoke-ContainerRegistryMethod { + [CmdletBinding()] + param($MethodName, [object[]] $MethodArguments) - $type.GetMethod($MethodName, $flags).Invoke($api, $MethodArguments) + $api.GetType().GetField('_cmdletPassedIn', [Reflection.BindingFlags]'Instance,NonPublic').SetValue($api, $PSCmdlet) + for ($i = 0; $i -lt $MethodArguments.Length; $i++) { + if ($null -ne $MethodArguments[$i]) { + $MethodArguments[$i] = $MethodArguments[$i].PSObject.BaseObject + } } - finally { - $clientProperty.GetValue($api).Dispose() + + if ($MethodName.EndsWith('Async')) { + return [ConfigBlobUploadHandler]::InvokeOnWorker($api, $MethodName, $MethodArguments) } + + $api.GetType().GetMethod($MethodName, [Reflection.BindingFlags]'Instance,Public,NonPublic').Invoke($api, $MethodArguments) } } BeforeEach { - $configPath = Join-Path $TestDrive "$([guid]::NewGuid()).json" - $configArguments = @($configPath, $null) - $configDigest = Invoke-ContainerRegistryMethod 'CreateConfigFile' $configArguments + $handler = [ConfigBlobUploadHandler]::new() + $api = New-ContainerRegistryApi $handler + $outputDirectory = Join-Path $TestDrive ([guid]::NewGuid().ToString()) + $null = New-Item $outputDirectory -ItemType Directory + $packagePath = Join-Path $outputDirectory 'test.1.0.0.nupkg' + [IO.File]::WriteAllText($packagePath, 'package') + $configPath = Join-Path $outputDirectory 'config.json' + [IO.File]::WriteAllText($configPath, '{"module":true}') + $method = $api.GetType().GetMethod('PushNupkgContainerRegistry', [Reflection.BindingFlags]'Instance,NonPublic') + $version = [Activator]::CreateInstance($method.GetParameters()[3].ParameterType, @('1.0.0')) + $publishArguments = @( + $outputDirectory, 'test', $null, $version, + [Microsoft.PowerShell.PSResourceGet.UtilClasses.ResourceType]::Module, + @{ ModuleVersion = '1.0.0' }, @{}, $false, $null, $null) } - It 'Creates a config containing exactly an empty JSON object and hashes those bytes' { - $configArguments[1] | Should -BeNullOrEmpty - $content = [IO.File]::ReadAllBytes($configPath) - $content.Length | Should -Be 2 - [Text.Encoding]::UTF8.GetString($content) | Should -BeExactly '{}' - $configDigest | Should -BeExactly (Get-FileHash $configPath -Algorithm SHA256).Hash.ToLowerInvariant() + AfterEach { + $api.GetType().GetField('_httpClient', [Reflection.BindingFlags]'Instance,NonPublic').GetValue($api).Dispose() } - It 'Describes the config bytes in the manifest without changing the package layer' { - $manifestArguments = @( - 'packageDigest', $configDigest, [long]123, 'test.nupkg', 'test', - [Microsoft.PowerShell.PSResourceGet.UtilClasses.ResourceType]::Module, '{}') - $manifest = Invoke-ContainerRegistryMethod 'CreateManifestContent' $manifestArguments | ConvertFrom-Json - + It 'Publishes matching empty JSON config bytes and manifest without overwriting module content' { + Invoke-ContainerRegistryMethod 'PushNupkgContainerRegistry' $publishArguments | Should -Be $true + $publishArguments[9] | Should -BeNullOrEmpty + $handler.UploadedContent.Length | Should -Be 2 + [Text.Encoding]::UTF8.GetString($handler.UploadedContent) | Should -BeExactly '{}' + $expectedDigest = 'sha256:' + [Convert]::ToHexString([Security.Cryptography.SHA256]::HashData($handler.UploadedContent)).ToLowerInvariant() + [uri]::UnescapeDataString($handler.UploadUri.Query) | Should -Match "digest=$expectedDigest" + $manifest = [Text.Encoding]::UTF8.GetString($handler.UploadedManifest) | ConvertFrom-Json $manifest.config.mediaType | Should -BeExactly 'application/vnd.oci.image.config.v1+json' - $manifest.config.digest | Should -BeExactly "sha256:$configDigest" - $manifest.config.size | Should -Be (Get-Item $configPath).Length + $manifest.config.digest | Should -BeExactly $expectedDigest + $manifest.config.size | Should -Be 2 $manifest.layers.Count | Should -Be 1 - $manifest.layers[0].digest | Should -BeExactly 'sha256:packageDigest' - $manifest.layers[0].size | Should -Be 123 + $manifest.layers[0].size | Should -Be (Get-Item $packagePath).Length + [Text.Encoding]::UTF8.GetString($handler.UploadedPackage) | Should -BeExactly 'package' + [IO.File]::ReadAllText($configPath) | Should -BeExactly '{"module":true}' } - It 'Uploads the config JSON with its matching digest' { - $handler = [ConfigBlobUploadHandler]::new() - $uploadArguments = @($configPath, $configDigest, 'test', 'test-token', $null) - Invoke-ContainerRegistryMethod 'UploadConfigFile' $uploadArguments $handler - - $uploadArguments[4] | Should -BeNullOrEmpty - $handler.UploadedContent.Length | Should -Be 2 - [Text.Encoding]::UTF8.GetString($handler.UploadedContent) | Should -BeExactly '{}' - $handler.UploadUri.Query | Should -Match "digest=sha256:$configDigest" + It 'Reports a failed ORAS upload' { + $handler.UploadStatusCode = [System.Net.HttpStatusCode]::BadRequest + Invoke-ContainerRegistryMethod 'PushNupkgContainerRegistry' $publishArguments | Should -Be $false + $publishArguments[9].FullyQualifiedErrorId | Should -BeExactly 'PackagePublishOrasError' } - It 'Reports a failed config upload' { - $handler = [ConfigBlobUploadHandler]::new() - $handler.UploadStatusCode = [System.Net.HttpStatusCode]::BadRequest - $uploadArguments = @($configPath, $configDigest, 'test', 'test-token', $null) - Invoke-ContainerRegistryMethod 'UploadConfigFile' $uploadArguments $handler + It 'Preserves the publish authentication information record for Azure authentication' { + Invoke-ContainerRegistryMethod 'PushNupkgContainerRegistry' $publishArguments -InformationVariable registryInformation | Should -Be $true - $uploadArguments[4].FullyQualifiedErrorId | Should -BeExactly 'UploadConfigFileError' + $registryInformation | Should -HaveCount 1 + $registryInformation[0].Tags | Should -Be 'PSRGContainerRegistryUnauthenticatedCheck' + $registryInformation[0].MessageData | Should -BeExactly 'Value of isRepositoryUnauthenticated: False' } - It 'Publishes matching config bytes and manifest when the module already contains config.json' { - $outputDirectory = Join-Path $TestDrive 'nupkg' - $null = New-Item $outputDirectory -ItemType Directory - $existingConfigPath = Join-Path $outputDirectory 'config.json' - $existingConfigContent = '{"module":true}' - [IO.File]::WriteAllText($existingConfigPath, $existingConfigContent) - [IO.File]::WriteAllText((Join-Path $outputDirectory 'test.1.0.0.nupkg'), 'package') + It 'Finds a package through each concurrent find path' -TestCases @( + @{ MethodName = 'FindNameAsync' } + @{ MethodName = 'FindVersionAsync' } + @{ MethodName = 'FindVersionGlobbingAsync' } + ) { + param($MethodName) + Invoke-ContainerRegistryMethod 'PushNupkgContainerRegistry' $publishArguments | Should -Be $true + $errors = [Collections.Concurrent.ConcurrentQueue[Management.Automation.ErrorRecord]]::new() + $warnings = [Collections.Concurrent.ConcurrentQueue[string]]::new() + $debug = [Collections.Concurrent.ConcurrentQueue[string]]::new() + $verbose = [Collections.Concurrent.ConcurrentQueue[string]]::new() + $resourceType = [Microsoft.PowerShell.PSResourceGet.UtilClasses.ResourceType]::Module + $arguments = switch ($MethodName) { + 'FindNameAsync' { @('test', $false, $resourceType) } + 'FindVersionAsync' { @('test', '1.0.0', $resourceType) } + 'FindVersionGlobbingAsync' { + $rangeType = $api.GetType().GetMethod($MethodName).GetParameters()[1].ParameterType + $range = $rangeType.GetField('All', [Reflection.BindingFlags]'Static,Public').GetValue($null) + @('test', $range, $false, $resourceType, $false) + } + } + $arguments += @($errors, $warnings, $debug, $verbose) + $result = Invoke-ContainerRegistryMethod $MethodName $arguments + $errors.Count | Should -Be 0 + $result.GetType().GetProperty('HashtableResponse').GetValue($result).Count | Should -Be 1 + $debug.Count | Should -BeGreaterThan 0 + } - $handler = [ConfigBlobUploadHandler]::new() - $type = [Microsoft.PowerShell.PSResourceGet.Cmdlets.PublishPSResource].Assembly.GetType('Microsoft.PowerShell.PSResourceGet.ContainerRegistryServerAPICalls') - $versionType = $type.GetMethod('PushNupkgContainerRegistry', [Reflection.BindingFlags]'Instance,NonPublic').GetParameters()[3].ParameterType - $version = [Activator]::CreateInstance($versionType, @('1.0.0')) - $publishArguments = @( - $outputDirectory, 'test', $null, $version, - [Microsoft.PowerShell.PSResourceGet.UtilClasses.ResourceType]::Module, - @{ ModuleVersion = '1.0.0' }, @{}, $false, $null, $null) - Push-Location $TestDrive + It 'Downloads the ORAS package through the concurrent install path' { + Invoke-ContainerRegistryMethod 'PushNupkgContainerRegistry' $publishArguments | Should -Be $true + $errors = [Collections.Concurrent.ConcurrentQueue[Management.Automation.ErrorRecord]]::new() + $warnings = [Collections.Concurrent.ConcurrentQueue[string]]::new() + $debug = [Collections.Concurrent.ConcurrentQueue[string]]::new() + $verbose = [Collections.Concurrent.ConcurrentQueue[string]]::new() + $arguments = @('test', '1.0.0', $false, $errors, $warnings, $debug, $verbose) + $stream = Invoke-ContainerRegistryMethod 'InstallPackageAsync' $arguments try { - $published = Invoke-ContainerRegistryMethod 'PushNupkgContainerRegistry' $publishArguments $handler + $errors.Count | Should -Be 0 + [Text.Encoding]::UTF8.GetString($stream.ToArray()) | Should -BeExactly 'package' + $verbose.Count | Should -BeGreaterThan 0 } finally { - Pop-Location + $stream.Dispose() } - - $published | Should -Be $true - $publishArguments[9] | Should -BeNullOrEmpty - [Text.Encoding]::UTF8.GetString($handler.UploadedContent) | Should -BeExactly '{}' - $handler.UploadUri.Query | Should -Match "digest=sha256:$configDigest" - $manifest = [Text.Encoding]::UTF8.GetString($handler.UploadedManifest) | ConvertFrom-Json - $manifest.config.digest | Should -BeExactly "sha256:$configDigest" - $manifest.config.size | Should -Be $handler.UploadedContent.Length - [IO.File]::ReadAllText($existingConfigPath) | Should -BeExactly $existingConfigContent } } diff --git a/test/Test-PSGalleryOutage.ps1 b/test/Test-PSGalleryOutage.ps1 index e0713df39..4aaff370c 100644 --- a/test/Test-PSGalleryOutage.ps1 +++ b/test/Test-PSGalleryOutage.ps1 @@ -15,8 +15,8 @@ The PowerShell Gallery may be experiencing an issue. Check https://aka.ms/psgallery for the current service status. For any other status code (for example 404, which can legitimately mean "not found"), the errors should NOT include it. - This is a manual test (not run by CI). Build the module first, then run from an elevated PowerShell 7 session: - ./build.ps1 -Clean -Build -BuildConfiguration Debug -BuildFramework net472 + This is a manual test (not run by CI). Build the module first, then run from an elevated PowerShell 7.6+ session: + ./build.ps1 -Clean -Build -BuildConfiguration Debug -BuildFramework net10.0 ./test/Test-PSGalleryOutage.ps1 -StatusCode 503 ./test/Test-PSGalleryOutage.ps1 -StatusCode 500 -Mode DownloadOnly -UpdateName ./test/Test-PSGalleryOutage.ps1 -StatusCode 404 diff --git a/test/perf/benchmarks/README.md b/test/perf/benchmarks/README.md index 10c4e7835..fa12337ec 100644 --- a/test/perf/benchmarks/README.md +++ b/test/perf/benchmarks/README.md @@ -1,32 +1,32 @@ -## Micro Benchmarks - -This folder contains micro benchmarks that test the performance of PSResourceGet. - -### Quick Start - -You can run the benchmarks directly using `dotnet run` in this directory: -1. To run the benchmarks in Interactive Mode, where you will be asked which benchmark(s) to run: - ``` - dotnet run -c Release -f net6.0 - ``` - -2. To list all available benchmarks ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Listing-the-Benchmarks)): - ``` - dotnet run -c Release -f net6.0 --list [flat/tree] - ``` - -3. To filter the benchmarks using a glob pattern applied to `namespace.typeName.methodName` ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Filtering-the-Benchmarks)]): - ``` - dotnet run -c Release -f net6.0 --filter *script* --list flat - ``` - -4. To profile the benchmarked code and produce an ETW Trace file ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Profiling)) - ``` - dotnet run -c Release -f net6.0 --filter *script* --profiler ETW - ``` - -## References - -- [Getting started with BenchmarkDotNet](https://benchmarkdotnet.org/articles/guides/getting-started.html) -- [Micro-benchmark Design Guidelines](https://github.com/dotnet/performance/blob/main/docs/microbenchmark-design-guidelines.md) +## Micro Benchmarks + +This folder contains micro benchmarks that test the performance of PSResourceGet. + +### Quick Start + +Use the .NET 10 SDK pinned in the repository's `global.json`. You can run the benchmarks directly using `dotnet run` in this directory: +1. To run the benchmarks in Interactive Mode, where you will be asked which benchmark(s) to run: + ``` + dotnet run -c Release -f net10.0 + ``` + +2. To list all available benchmarks ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Listing-the-Benchmarks)): + ``` + dotnet run -c Release -f net10.0 --list [flat/tree] + ``` + +3. To filter the benchmarks using a glob pattern applied to `namespace.typeName.methodName` ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Filtering-the-Benchmarks)]): + ``` + dotnet run -c Release -f net10.0 --filter *script* --list flat + ``` + +4. To profile the benchmarked code and produce an ETW Trace file ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Profiling)) + ``` + dotnet run -c Release -f net10.0 --filter *script* --profiler ETW + ``` + +## References + +- [Getting started with BenchmarkDotNet](https://benchmarkdotnet.org/articles/guides/getting-started.html) +- [Micro-benchmark Design Guidelines](https://github.com/dotnet/performance/blob/main/docs/microbenchmark-design-guidelines.md) - [Adam SITNIK: Powerful benchmarking in .NET](https://www.youtube.com/watch?v=pdcrSG4tOLI&t=351s) \ No newline at end of file diff --git a/test/perf/benchmarks/benchmarks.csproj b/test/perf/benchmarks/benchmarks.csproj index d34e3f9b2..04a2d47ac 100644 --- a/test/perf/benchmarks/benchmarks.csproj +++ b/test/perf/benchmarks/benchmarks.csproj @@ -1,6 +1,6 @@ - net6.0 + net10.0 Exe @@ -14,12 +14,14 @@ - + - - - + + + + +