Skip to content

Commit c637fcf

Browse files
Fix PSResourceGet CI for ContainerRegistry (#1829)
1 parent e2a238b commit c637fcf

File tree

7 files changed

+56
-35
lines changed

7 files changed

+56
-35
lines changed

.ci/test.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,10 +107,12 @@ jobs:
107107
inputs:
108108
azureSubscription: PSResourceGetACR
109109
azurePowerShellVersion: LatestVersion
110+
pwsh: true
110111
ScriptType: InlineScript
111112
inline: |
112113
$modulePath = Join-Path -Path $env:AGENT_TEMPDIRECTORY -ChildPath 'TempModules'
113114
$env:PSModulePath = $modulePath + [System.IO.Path]::PathSeparator + $env:PSModulePath
115+
114116
Write-Verbose -Verbose "Importing build utilities (buildtools.psd1)"
115117
Import-Module -Name (Join-Path -Path '${{ parameters.buildDirectory }}' -ChildPath 'buildtools.psd1') -Force
116118
Invoke-ModuleTestsACR -Type Functional

global.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"sdk": {
3-
"version": "8.0.406"
3+
"version": "8.0.411"
44
}
55
}

src/code/ContainerRegistryServerAPICalls.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,8 @@ internal string GetContainerRegistryAccessToken(out ErrorRecord errRecord)
394394
else
395395
{
396396
bool isRepositoryUnauthenticated = IsContainerRegistryUnauthenticated(Repository.Uri.ToString(), out errRecord, out accessToken);
397+
_cmdletPassedIn.WriteDebug($"Is repository unauthenticated: {isRepositoryUnauthenticated}");
398+
397399
if (errRecord != null)
398400
{
399401
return null;
@@ -407,7 +409,7 @@ internal string GetContainerRegistryAccessToken(out ErrorRecord errRecord)
407409

408410
if (!isRepositoryUnauthenticated)
409411
{
410-
accessToken = Utils.GetAzAccessToken();
412+
accessToken = Utils.GetAzAccessToken(_cmdletPassedIn);
411413
if (string.IsNullOrEmpty(accessToken))
412414
{
413415
errRecord = new ErrorRecord(
@@ -488,6 +490,8 @@ internal bool IsContainerRegistryUnauthenticated(string containerRegistyUrl, out
488490
// get the anonymous access token
489491
var url = $"{realm}?service={service}{defaultScope}";
490492

493+
_cmdletPassedIn.WriteDebug($"Getting anonymous access token from the realm: {url}");
494+
491495
// we dont check the errorrecord here because we want to return false if we get a 401 and not throw an error
492496
var results = GetHttpResponseJObjectUsingContentHeaders(url, HttpMethod.Get, content, contentHeaders, out _);
493497

src/code/FindPSResource.cs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ namespace Microsoft.PowerShell.PSResourceGet.Cmdlets
2424
public sealed class FindPSResource : PSCmdlet
2525
{
2626
#region Members
27-
27+
2828
private const string NameParameterSet = "NameParameterSet";
2929
private const string CommandNameParameterSet = "CommandNameParameterSet";
3030
private const string DscResourceNameParameterSet = "DscResourceNameParameterSet";
@@ -39,7 +39,7 @@ public sealed class FindPSResource : PSCmdlet
3939
/// Specifies name of a resource or resources to find. Accepts wild card characters.
4040
/// </summary>
4141
[SupportsWildcards]
42-
[Parameter(Position = 0,
42+
[Parameter(Position = 0,
4343
ValueFromPipeline = true,
4444
ValueFromPipelineByPropertyName = true,
4545
ParameterSetName = NameParameterSet)]
@@ -167,7 +167,6 @@ protected override void ProcessRecord()
167167

168168
private void ProcessResourceNameParameterSet()
169169
{
170-
WriteDebug("In FindPSResource::ProcessResourceNameParameterSet()");
171170
// only cases where Name is allowed to not be specified is if Type or Tag parameters are
172171
if (!MyInvocation.BoundParameters.ContainsKey(nameof(Name)))
173172
{
@@ -178,7 +177,7 @@ private void ProcessResourceNameParameterSet()
178177
}
179178
else if (MyInvocation.BoundParameters.ContainsKey(nameof(Type)))
180179
{
181-
Name = new string[] {"*"};
180+
Name = new string[] { "*" };
182181
}
183182
else
184183
{
@@ -191,8 +190,8 @@ private void ProcessResourceNameParameterSet()
191190
}
192191

193192
WriteDebug("Filtering package name(s) on wildcards");
194-
Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries:false, out string[] errorMsgs, out bool nameContainsWildcard);
195-
193+
Name = Utils.ProcessNameWildcards(Name, removeWildcardEntries: false, out string[] errorMsgs, out bool nameContainsWildcard);
194+
196195
foreach (string error in errorMsgs)
197196
{
198197
WriteError(new ErrorRecord(
@@ -208,7 +207,7 @@ private void ProcessResourceNameParameterSet()
208207
{
209208
WriteDebug("Package name(s) could not be resolved");
210209
return;
211-
}
210+
}
212211

213212
// determine/parse out Version param
214213
VersionType versionType = VersionType.VersionRange;
@@ -232,7 +231,7 @@ private void ProcessResourceNameParameterSet()
232231
"IncorrectVersionFormat",
233232
ErrorCategory.InvalidArgument,
234233
this));
235-
234+
236235
return;
237236
}
238237
}
@@ -289,7 +288,7 @@ private void ProcessCommandOrDscParameterSet(bool isSearchingForCommands)
289288
WriteDebug("Command or DSCResource name(s) could not be resolved");
290289
return;
291290
}
292-
291+
293292
foreach (PSCommandResourceInfo cmdPkg in _findHelper.FindByCommandOrDscResource(
294293
isSearchingForCommands: isSearchingForCommands,
295294
prerelease: Prerelease,
@@ -325,7 +324,7 @@ private void ProcessTags()
325324
WriteDebug("Tags(s) could not be resolved");
326325
return;
327326
}
328-
327+
329328
foreach (PSResourceInfo tagPkg in _findHelper.FindByTag(
330329
type: Type,
331330
prerelease: Prerelease,

src/code/Microsoft.PowerShell.PSResourceGet.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
<PackageReference Include="System.Net.Http" Version="4.3.4" />
2525
<PackageReference Include="System.Text.Json" Version="8.0.5" />
2626
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
27-
<PackageReference Include="Azure.Identity" Version="1.11.4" />
27+
<PackageReference Include="Azure.Identity" Version="1.14.0" />
2828
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="6.0.5" />
2929
<Reference Include="System.Web" />
3030
</ItemGroup>

src/code/RegisterPSResourceRepository.cs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ class RegisterPSResourceRepository : PSCmdlet
102102
/// </summary>
103103
[Parameter]
104104
public SwitchParameter PassThru { get; set; }
105-
105+
106106
/// <summary>
107107
/// When specified, will overwrite information for any existing repository with the same name.
108108
/// </summary>
@@ -212,14 +212,14 @@ private PSRepositoryInfo PSGalleryParameterSetHelper(int repoPriority, bool repo
212212
WriteDebug("In RegisterPSResourceRepository::PSGalleryParameterSetHelper()");
213213
Uri psGalleryUri = new Uri(PSGalleryRepoUri);
214214
WriteDebug("Internal name and uri values for PSGallery are hardcoded and validated. Priority and trusted values, if passed in, also validated");
215-
var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName,
216-
psGalleryUri,
217-
repoPriority,
218-
repoTrusted,
215+
var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName,
216+
psGalleryUri,
217+
repoPriority,
218+
repoTrusted,
219219
apiVersion: null,
220-
repoCredentialInfo: null,
221-
Force,
222-
this,
220+
repoCredentialInfo: null,
221+
Force,
222+
this,
223223
out string errorMsg);
224224

225225
if (!string.IsNullOrEmpty(errorMsg))
@@ -313,7 +313,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo)
313313
"NullUriForRepositoriesParameterSetRegistration",
314314
ErrorCategory.InvalidArgument,
315315
this));
316-
316+
317317
return null;
318318
}
319319

@@ -337,10 +337,10 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo)
337337
return null;
338338
}
339339

340-
if (repo.ContainsKey("ApiVersion") &&
340+
if (repo.ContainsKey("ApiVersion") &&
341341
(repo["ApiVersion"] == null || String.IsNullOrEmpty(repo["ApiVersion"].ToString()) ||
342-
!(repo["ApiVersion"].ToString().Equals("Local", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("V2", StringComparison.OrdinalIgnoreCase) ||
343-
repo["ApiVersion"].ToString().Equals("V3", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("NugetServer", StringComparison.OrdinalIgnoreCase) ||
342+
!(repo["ApiVersion"].ToString().Equals("Local", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("V2", StringComparison.OrdinalIgnoreCase) ||
343+
repo["ApiVersion"].ToString().Equals("V3", StringComparison.OrdinalIgnoreCase) || repo["ApiVersion"].ToString().Equals("NugetServer", StringComparison.OrdinalIgnoreCase) ||
344344
repo["ApiVersion"].ToString().Equals("Unknown", StringComparison.OrdinalIgnoreCase))))
345345
{
346346
WriteError(new ErrorRecord(

src/code/Utils.cs

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -648,12 +648,11 @@ public static PSCredential GetRepositoryCredentialFromSecretManagement(
648648
}
649649
}
650650

651-
public static string GetAzAccessToken()
651+
public static string GetAzAccessToken(PSCmdlet cmdletPassedIn)
652652
{
653653
var credOptions = new DefaultAzureCredentialOptions
654654
{
655655
ExcludeEnvironmentCredential = true,
656-
ExcludeVisualStudioCodeCredential = true,
657656
ExcludeVisualStudioCredential = true,
658657
ExcludeWorkloadIdentityCredential = true,
659658
ExcludeManagedIdentityCredential = true, // ManagedIdentityCredential makes the experience slow
@@ -665,8 +664,25 @@ public static string GetAzAccessToken()
665664

666665
var dCred = new DefaultAzureCredential(credOptions);
667666
var tokenRequestContext = new TokenRequestContext(new string[] { "https://management.azure.com/.default" });
668-
var token = dCred.GetTokenAsync(tokenRequestContext).Result;
669-
return token.Token;
667+
668+
try
669+
{
670+
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
671+
{
672+
var token = dCred.GetTokenAsync(tokenRequestContext, cts.Token).GetAwaiter().GetResult();
673+
return token.Token;
674+
}
675+
}
676+
catch (OperationCanceledException)
677+
{
678+
cmdletPassedIn.WriteWarning("Timeout occurred while acquiring Azure access token.");
679+
return null;
680+
}
681+
catch (Exception ex)
682+
{
683+
cmdletPassedIn.WriteWarning($"Failed to acquire Azure access token: {ex.Message}");
684+
return null;
685+
}
670686
}
671687

672688
public static string GetContainerRegistryAccessTokenFromSecretManagement(
@@ -1874,9 +1890,9 @@ public static Hashtable GetMetadataFromNuspec(string nuspecFilePath, PSCmdlet cm
18741890
catch (Exception e)
18751891
{
18761892
errorRecord = new ErrorRecord(
1877-
exception: e,
1878-
"GetHashtableForNuspecFailure",
1879-
ErrorCategory.ReadError,
1893+
exception: e,
1894+
"GetHashtableForNuspecFailure",
1895+
ErrorCategory.ReadError,
18801896
cmdletPassedIn);
18811897
}
18821898

@@ -1895,9 +1911,9 @@ public static XmlDocument LoadXmlDocument(string filePath, PSCmdlet cmdletPassed
18951911
catch (Exception e)
18961912
{
18971913
errRecord = new ErrorRecord(
1898-
exception: e,
1899-
"LoadXmlDocumentFailure",
1900-
ErrorCategory.ReadError,
1914+
exception: e,
1915+
"LoadXmlDocumentFailure",
1916+
ErrorCategory.ReadError,
19011917
cmdletPassedIn);
19021918
}
19031919

0 commit comments

Comments
 (0)