Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .ci/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,12 @@ jobs:
inputs:
azureSubscription: PSResourceGetACR
azurePowerShellVersion: LatestVersion
pwsh: true
ScriptType: InlineScript
inline: |
$modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules'
$env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath

Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)"
Import-Module -Name (Join-Path -Path '${{ parameters.buildDirectory }}' -ChildPath 'buildtools.psd1') -Force
Invoke-ModuleTestsACR -Type Functional
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"sdk": {
"version": "8.0.406"
"version": "8.0.411"
}
}
6 changes: 5 additions & 1 deletion src/code/ContainerRegistryServerAPICalls.cs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,8 @@ internal string GetContainerRegistryAccessToken(out ErrorRecord errRecord)
else
{
bool isRepositoryUnauthenticated = IsContainerRegistryUnauthenticated(Repository.Uri.ToString(), out errRecord, out accessToken);
_cmdletPassedIn.WriteDebug($"Is repository unauthenticated: {isRepositoryUnauthenticated}");

if (errRecord != null)
{
return null;
Expand All @@ -407,7 +409,7 @@ internal string GetContainerRegistryAccessToken(out ErrorRecord errRecord)

if (!isRepositoryUnauthenticated)
{
accessToken = Utils.GetAzAccessToken();
accessToken = Utils.GetAzAccessToken(_cmdletPassedIn);
if (string.IsNullOrEmpty(accessToken))
{
errRecord = new ErrorRecord(
Expand Down Expand Up @@ -488,6 +490,8 @@ internal bool IsContainerRegistryUnauthenticated(string containerRegistyUrl, out
// get the anonymous access token
var url = $"{realm}?service={service}{defaultScope}";

_cmdletPassedIn.WriteDebug($"Getting anonymous access token from the realm: {url}");

// we dont check the errorrecord here because we want to return false if we get a 401 and not throw an error
var results = GetHttpResponseJObjectUsingContentHeaders(url, HttpMethod.Get, content, contentHeaders, out _);

Expand Down
19 changes: 9 additions & 10 deletions src/code/FindPSResource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
public sealed class FindPSResource : PSCmdlet
{
#region Members

private const string NameParameterSet = "NameParameterSet";
private const string CommandNameParameterSet = "CommandNameParameterSet";
private const string DscResourceNameParameterSet = "DscResourceNameParameterSet";
Expand All @@ -39,7 +39,7 @@ public sealed class FindPSResource : PSCmdlet
/// Specifies name of a resource or resources to find. Accepts wild card characters.
/// </summary>
[SupportsWildcards]
[Parameter(Position = 0,
[Parameter(Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true,
ParameterSetName = NameParameterSet)]
Expand Down Expand Up @@ -167,7 +167,6 @@ protected override void ProcessRecord()

private void ProcessResourceNameParameterSet()
{
WriteDebug("In FindPSResource::ProcessResourceNameParameterSet()");
// only cases where Name is allowed to not be specified is if Type or Tag parameters are
if (!MyInvocation.BoundParameters.ContainsKey(nameof(Name)))
{
Expand All @@ -178,7 +177,7 @@ private void ProcessResourceNameParameterSet()
}
else if (MyInvocation.BoundParameters.ContainsKey(nameof(Type)))
{
Name = new string[] {"*"};
Name = new string[] { "*" };
}
else
{
Expand All @@ -191,8 +190,8 @@ private void ProcessResourceNameParameterSet()
}

WriteDebug("Filtering package name(s) on wildcards");
Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries:false, out string[] errorMsgs, out bool nameContainsWildcard);
Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries: false, out string[] errorMsgs, out bool nameContainsWildcard);

foreach (string error in errorMsgs)
{
WriteError(new ErrorRecord(
Expand All @@ -208,7 +207,7 @@ private void ProcessResourceNameParameterSet()
{
WriteDebug("Package name(s) could not be resolved");
return;
}
}

// determine/parse out Version param
VersionType versionType = VersionType.VersionRange;
Expand All @@ -232,7 +231,7 @@ private void ProcessResourceNameParameterSet()
"IncorrectVersionFormat",
ErrorCategory.InvalidArgument,
this));

return;
}
}
Expand Down Expand Up @@ -289,7 +288,7 @@ private void ProcessCommandOrDscParameterSet(bool isSearchingForCommands)
WriteDebug("Command or DSCResource name(s) could not be resolved");
return;
}

foreach (PSCommandResourceInfo cmdPkg in _findHelper.FindByCommandOrDscResource(
isSearchingForCommands: isSearchingForCommands,
prerelease: Prerelease,
Expand Down Expand Up @@ -325,7 +324,7 @@ private void ProcessTags()
WriteDebug("Tags(s) could not be resolved");
return;
}

foreach (PSResourceInfo tagPkg in _findHelper.FindByTag(
type: Type,
prerelease: Prerelease,
Expand Down
2 changes: 1 addition & 1 deletion src/code/Microsoft.PowerShell.PSResourceGet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.Text.Json" Version="8.0.5" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Azure.Identity" Version="1.11.4" />
<PackageReference Include="Azure.Identity" Version="1.14.0" />
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="6.0.5" />
<Reference Include="System.Web" />
</ItemGroup>
Expand Down
24 changes: 12 additions & 12 deletions src/code/RegisterPSResourceRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ class RegisterPSResourceRepository : PSCmdlet
/// </summary>
[Parameter]
public SwitchParameter PassThru { get; set; }

/// <summary>
/// When specified, will overwrite information for any existing repository with the same name.
/// </summary>
Expand Down Expand Up @@ -212,14 +212,14 @@ private PSRepositoryInfo PSGalleryParameterSetHelper(int repoPriority, bool repo
WriteDebug("In RegisterPSResourceRepository::PSGalleryParameterSetHelper()");
Uri psGalleryUri = new Uri(PSGalleryRepoUri);
WriteDebug("Internal name and uri values for PSGallery are hardcoded and validated. Priority and trusted values, if passed in, also validated");
var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName,
psGalleryUri,
repoPriority,
repoTrusted,
var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName,
psGalleryUri,
repoPriority,
repoTrusted,
apiVersion: null,
repoCredentialInfo: null,
Force,
this,
repoCredentialInfo: null,
Force,
this,
out string errorMsg);

if (!string.IsNullOrEmpty(errorMsg))
Expand Down Expand Up @@ -313,7 +313,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo)
"NullUriForRepositoriesParameterSetRegistration",
ErrorCategory.InvalidArgument,
this));

return null;
}

Expand All @@ -337,10 +337,10 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo)
return null;
}

if (repo.ContainsKey("ApiVersion") &&
if (repo.ContainsKey("ApiVersion") &&
(repo["ApiVersion"] == null || String.IsNullOrEmpty(repo["ApiVersion"].ToString()) ||
!(repo["ApiVersion"].ToString().Equals("Local", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("V2", StringComparison.OrdinalIgnoreCase) ||
repo["ApiVersion"].ToString().Equals("V3", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("NugetServer", StringComparison.OrdinalIgnoreCase) ||
!(repo["ApiVersion"].ToString().Equals("Local", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("V2", StringComparison.OrdinalIgnoreCase) ||
repo["ApiVersion"].ToString().Equals("V3", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("NugetServer", StringComparison.OrdinalIgnoreCase) ||
repo["ApiVersion"].ToString().Equals("Unknown", StringComparison.OrdinalIgnoreCase))))
{
WriteError(new ErrorRecord(
Expand Down
36 changes: 26 additions & 10 deletions src/code/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -648,12 +648,11 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement(
}
}

public static string GetAzAccessToken()
public static string GetAzAccessToken(PSCmdlet cmdletPassedIn)
{
var credOptions = new DefaultAzureCredentialOptions
{
ExcludeEnvironmentCredential = true,
ExcludeVisualStudioCodeCredential = true,
ExcludeVisualStudioCredential = true,
ExcludeWorkloadIdentityCredential = true,
ExcludeManagedIdentityCredential = true, // ManagedIdentityCredential makes the experience slow
Expand All @@ -665,8 +664,25 @@ public static string GetAzAccessToken()

var dCred = new DefaultAzureCredential(credOptions);
var tokenRequestContext = new TokenRequestContext(new string[] { "https://management.azure.com/.default" });
var token = dCred.GetTokenAsync(tokenRequestContext).Result;
return token.Token;

try
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
{
var token = dCred.GetTokenAsync(tokenRequestContext, cts.Token).GetAwaiter().GetResult();
return token.Token;
}
}
catch (OperationCanceledException)
{
cmdletPassedIn.WriteWarning("Timeout occurred while acquiring Azure access token.");
return null;
}
catch (Exception ex)
{
cmdletPassedIn.WriteWarning($"Failed to acquire Azure access token: {ex.Message}");
return null;
}
}

public static string GetContainerRegistryAccessTokenFromSecretManagement(
Expand Down Expand Up @@ -1874,9 +1890,9 @@ public static Hashtable GetMetadataFromNuspec(string nuspecFilePath, PSCmdlet cm
catch (Exception e)
{
errorRecord = new ErrorRecord(
exception: e,
"GetHashtableForNuspecFailure",
ErrorCategory.ReadError,
exception: e,
"GetHashtableForNuspecFailure",
ErrorCategory.ReadError,
cmdletPassedIn);
}

Expand All @@ -1895,9 +1911,9 @@ public static XmlDocument LoadXmlDocument(string filePath, PSCmdlet cmdletPassed
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"LoadXmlDocumentFailure",
ErrorCategory.ReadError,
exception: e,
"LoadXmlDocumentFailure",
ErrorCategory.ReadError,
cmdletPassedIn);
}

Expand Down
Loading