-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathUtils.cs
2048 lines (1771 loc) · 82.8 KB
/
Utils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Net;
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using NuGet.Versioning;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Language;
using System.Management.Automation.Runspaces;
using System.Runtime.InteropServices;
using Microsoft.PowerShell.Commands;
using Microsoft.PowerShell.PSResourceGet.Cmdlets;
using System.Net.Http;
using System.Globalization;
using System.Security;
using Azure.Core;
using Azure.Identity;
namespace Microsoft.PowerShell.PSResourceGet.UtilClasses
{
#region Utils
internal static class Utils
{
#region Enums
public enum MetadataFileType
{
ModuleManifest,
ScriptFile,
Nuspec,
None
}
# endregion
#region String fields
public static readonly string[] EmptyStrArray = Array.Empty<string>();
public static readonly char[] WhitespaceSeparator = new char[]{' '};
public const string PSDataFileExt = ".psd1";
public const string PSScriptFileExt = ".ps1";
private const string ConvertJsonToHashtableScript = @"
param (
[string] $json
)
function ConvertToHash
{
param (
[pscustomobject] $object
)
$output = @{}
$object | Microsoft.PowerShell.Utility\Get-Member -MemberType NoteProperty | ForEach-Object {
$name = $_.Name
$value = $object.($name)
if ($value -is [object[]])
{
$array = @()
$value | ForEach-Object {
$array += (ConvertToHash $_)
}
$output.($name) = $array
}
elseif ($value -is [pscustomobject])
{
$output.($name) = (ConvertToHash $value)
}
else
{
$output.($name) = $value
}
}
$output
}
$customObject = Microsoft.PowerShell.Utility\ConvertFrom-Json -InputObject $json
return ConvertToHash $customObject
";
#endregion
#region Path fields
private static string s_tempHome = null;
#endregion
#region String methods
public static string TrimQuotes(string name)
{
return name.Trim('\'', '"');
}
public static string QuoteName(string name)
{
bool quotesNeeded = false;
foreach (var c in name)
{
if (Char.IsWhiteSpace(c))
{
quotesNeeded = true;
break;
}
}
if (!quotesNeeded)
{
return name;
}
return "'" + CodeGeneration.EscapeSingleQuotedStringContent(name) + "'";
}
public static string[] GetStringArrayFromString(string[] delimeter, string stringToConvertToArray)
{
// This will be a string where entries are separated by space.
if (String.IsNullOrEmpty(stringToConvertToArray))
{
return Utils.EmptyStrArray;
}
return stringToConvertToArray.Split(delimeter, StringSplitOptions.RemoveEmptyEntries);
}
/// <summary>
/// Converts an ArrayList of object types to a string array.
/// </summary>
public static string[] GetStringArray(ArrayList list)
{
if (list == null) { return null; }
var strArray = new string[list.Count];
for (int i=0; i < list.Count; i++)
{
strArray[i] = list[i] as string;
}
return strArray;
}
public static string[] ProcessNameWildcards(
string[] pkgNames,
bool removeWildcardEntries,
out string[] errorMsgs,
out bool isContainWildcard)
{
List<string> namesWithSupportedWildcards = new List<string>();
List<string> errorMsgsList = new List<string>();
if (pkgNames == null)
{
isContainWildcard = true;
errorMsgs = errorMsgsList.ToArray();
return new string[] {"*"};
}
isContainWildcard = false;
foreach (string name in pkgNames)
{
if (WildcardPattern.ContainsWildcardCharacters(name))
{
if (removeWildcardEntries)
{
// Tag // CommandName // DSCResourceName
errorMsgsList.Add($"{name} will be discarded from the provided entries.");
continue;
}
if (String.Equals(name, "*", StringComparison.InvariantCultureIgnoreCase))
{
isContainWildcard = true;
errorMsgs = new string[] {};
return new string[] {"*"};
}
if (name.Contains("?") || name.Contains("["))
{
errorMsgsList.Add(String.Format("-Name with wildcards '?' and '[' are not supported for this cmdlet so Name entry: {0} will be discarded.", name));
continue;
}
isContainWildcard = true;
namesWithSupportedWildcards.Add(name);
}
else
{
namesWithSupportedWildcards.Add(name);
}
}
errorMsgs = errorMsgsList.ToArray();
return namesWithSupportedWildcards.ToArray();
}
public static string FormatRequestsExceptions(Exception exception, HttpRequestMessage request)
{
string exMsg = $"'{exception.Message}' Request sent: '{request.RequestUri.AbsoluteUri}'";
if (exception.InnerException != null && !string.IsNullOrEmpty(exception.InnerException.Message))
{
exMsg += $" Inner exception: '{exception.InnerException.Message}'";
}
return exMsg;
}
public static string FormatCredentialRequestExceptions(Exception exception)
{
string exMsg = $"'{exception.Message}' Re-run the command with -Credential.";
if (exception.InnerException != null && !string.IsNullOrEmpty(exception.InnerException.Message))
{
exMsg += $" Inner exception: '{exception.InnerException.Message}'";
}
return exMsg;
}
#endregion
#region Version methods
public static bool TryGetVersionType(
string version,
out NuGetVersion nugetVersion,
out VersionRange versionRange,
out VersionType versionType,
out string error)
{
error = String.Empty;
nugetVersion = null;
versionRange = null;
versionType = VersionType.NoVersion;
if (String.IsNullOrEmpty(version))
{
return true;
}
if (version.Trim().Equals("*"))
{
// this method is called for find and install version parameter.
// for find, version = "*" means VersionRange.All
// for install, version = "*", means find latest version. This is handled in Install
versionRange = VersionRange.All;
versionType = VersionType.VersionRange;
return true;
}
bool isVersionRange;
if (version.Contains("*"))
{
string modifiedVersion;
string[] versionSplit = version.Split(new string[] { "." }, StringSplitOptions.None);
if (versionSplit.Length == 2 && versionSplit[1].Equals("*"))
{
// eg: 2.* should translate to the version range "[2.0,2.99999]"
modifiedVersion = $"[{versionSplit[0]}.0,{versionSplit[0]}.999999]";
}
else if (versionSplit.Length == 3 && versionSplit[2].Equals("*"))
{
// eg: 2.1.* should translate to the version range "[2.1.0,2.1.99999]"
modifiedVersion = $"[{versionSplit[0]}.{versionSplit[1]}.0,{versionSplit[0]}.{versionSplit[1]}.999999]";
}
else if (versionSplit.Length == 4 && versionSplit[3].Equals("*"))
{
// eg: 2.8.8.* should translate to the version range "[2.1.3.0,2.1.3.99999]"
modifiedVersion = $"[{versionSplit[0]}.{versionSplit[1]}.{versionSplit[2]}.0,{versionSplit[0]}.{versionSplit[1]}.{versionSplit[2]}.999999]";
}
else {
error = "Argument for -Version parameter is not in the proper format";
return false;
}
VersionRange.TryParse(modifiedVersion, out versionRange);
versionType = VersionType.VersionRange;
return true;
}
bool isNugetVersion = NuGetVersion.TryParse(version, out nugetVersion);
isVersionRange = VersionRange.TryParse(version, out versionRange);
if (!isNugetVersion && !isVersionRange)
{
error = "Argument for -Version parameter is not in the proper format";
return false;
}
if (isNugetVersion)
{
versionType = VersionType.SpecificVersion;
}
else if (isVersionRange)
{
versionType = VersionType.VersionRange;
}
return true;
}
public static string GetNormalizedVersionString(
string versionString,
string prerelease)
{
// versionString may be like 1.2.0.0 or 1.2.0
// prerelease may be null or "alpha1"
// possible passed in examples:
// versionString: "1.2.0" prerelease: "alpha1"
// versionString: "1.2.0" prerelease: "" <- doubtful though
// versionString: "1.2.0.0" prerelease: "alpha1"
// versionString: "1.2.0.0" prerelease: ""
if (String.IsNullOrEmpty(prerelease))
{
return versionString;
}
int numVersionDigits = versionString.Split('.').Count();
if (numVersionDigits == 3)
{
// versionString: "1.2.0" prerelease: "alpha1"
return versionString + "-" + prerelease;
}
else if (numVersionDigits == 4)
{
// versionString: "1.2.0.0" prerelease: "alpha1"
return versionString.Substring(0, versionString.LastIndexOf('.')) + "-" + prerelease;
}
return versionString;
}
public static bool TryParseVersionOrVersionRange(
string version,
out VersionRange versionRange)
{
versionRange = null;
if (version == null) { return false; }
if (version.Trim().Equals("*"))
{
versionRange = VersionRange.All;
return true;
}
// parse as NuGetVersion
if (NuGetVersion.TryParse(version, out NuGetVersion nugetVersion))
{
versionRange = new VersionRange(
minVersion: nugetVersion,
includeMinVersion: true,
maxVersion: nugetVersion,
includeMaxVersion: true,
floatRange: null,
originalString: version);
return true;
}
return VersionRange.TryParse(version, out versionRange);
}
public static bool GetVersionForInstallPath(
string installedPkgPath,
bool isModule,
PSCmdlet cmdletPassedIn,
out NuGetVersion pkgNuGetVersion)
{
// this method returns false if the PSGetModuleInfo.xml or {pkgName}_InstalledScriptInfo.xml file
// could not be parsed properly, or the version from it could not be parsed into a NuGetVersion.
// In this case the caller method (i.e GetHelper.FilterPkgPathsByVersion()) should skip the current
// installed package path or reassign NuGetVersion variable passed in to a non-null value as it sees fit.
// for Modules, installedPkgPath will look like this:
// ./PowerShell/Modules/test_module/3.0.0
// for Scripts, installedPkgPath will look like this:
// ./PowerShell/Scripts/test_script.ps1
string pkgName = isModule ? String.Empty : Utils.GetInstalledPackageName(installedPkgPath);
string packageInfoXMLFilePath = isModule ? Path.Combine(installedPkgPath, "PSGetModuleInfo.xml") : Path.Combine((new DirectoryInfo(installedPkgPath).Parent).FullName, "InstalledScriptInfos", $"{pkgName}_InstalledScriptInfo.xml");
if (!PSResourceInfo.TryRead(packageInfoXMLFilePath, out PSResourceInfo psGetInfo, out string errorMsg))
{
cmdletPassedIn.WriteVerbose(String.Format(
"The {0} file found at location: {1} cannot be parsed due to {2}",
isModule ? "PSGetModuleInfo.xml" : $"{pkgName}_InstalledScriptInfo.xml",
packageInfoXMLFilePath,
errorMsg));
pkgNuGetVersion = null;
return false;
}
psGetInfo.AdditionalMetadata.TryGetValue("NormalizedVersion", out string normalizedVersion);
if (!NuGetVersion.TryParse(
value: normalizedVersion,
version: out pkgNuGetVersion))
{
cmdletPassedIn.WriteVerbose(String.Format("Leaf directory in path '{0}' cannot be parsed into a version.", installedPkgPath));
return false;
}
return true;
}
#endregion
#region Uri methods
public static bool TryCreateValidUri(
string uriString,
PSCmdlet cmdletPassedIn,
out Uri uriResult,
out ErrorRecord errorRecord)
{
errorRecord = null;
if (Uri.TryCreate(uriString, UriKind.Absolute, out uriResult))
{
return true;
}
Exception ex;
try
{
// This is needed for a relative path Uri string. Does not throw error for an absolute path.
var filePath = cmdletPassedIn.GetResolvedProviderPathFromPSPath(uriString, out ProviderInfo provider).First();
if (Uri.TryCreate(filePath, UriKind.Absolute, out uriResult))
{
return true;
}
ex = new PSArgumentException($"Invalid Uri file path: {uriString}");
}
catch (Exception e)
{
ex = e;
}
errorRecord = new ErrorRecord(
new PSArgumentException($"The provided Uri is not valid: {uriString}. It must be of Uri Scheme: HTTP, HTTPS, FTP or a file path", ex),
"InvalidUri",
ErrorCategory.InvalidArgument,
cmdletPassedIn);
return false;
}
#endregion
#region PSCredentialInfo methods
public static bool TryCreateValidPSCredentialInfo(
PSObject credentialInfoCandidate,
PSCmdlet cmdletPassedIn,
out PSCredentialInfo repoCredentialInfo,
out ErrorRecord errorRecord)
{
repoCredentialInfo = null;
errorRecord = null;
try
{
if (!string.IsNullOrEmpty((string) credentialInfoCandidate.Properties[PSCredentialInfo.VaultNameAttribute]?.Value)
&& !string.IsNullOrEmpty((string) credentialInfoCandidate.Properties[PSCredentialInfo.SecretNameAttribute]?.Value))
{
PSCredential credential = null;
if (credentialInfoCandidate.Properties[PSCredentialInfo.CredentialAttribute] != null)
{
try
{
credential = (PSCredential) credentialInfoCandidate.Properties[PSCredentialInfo.CredentialAttribute].Value;
}
catch (Exception e)
{
errorRecord = new ErrorRecord(
new PSArgumentException($"Invalid CredentialInfo {PSCredentialInfo.CredentialAttribute}", e),
"InvalidCredentialInfo",
ErrorCategory.InvalidArgument,
cmdletPassedIn);
return false;
}
}
repoCredentialInfo = new PSCredentialInfo(
(string) credentialInfoCandidate.Properties[PSCredentialInfo.VaultNameAttribute].Value,
(string) credentialInfoCandidate.Properties[PSCredentialInfo.SecretNameAttribute].Value,
credential
);
return true;
}
else
{
errorRecord = new ErrorRecord(
new PSArgumentException($"Invalid CredentialInfo, must include non-empty {PSCredentialInfo.VaultNameAttribute} and {PSCredentialInfo.SecretNameAttribute}, and optionally a {PSCredentialInfo.CredentialAttribute}"),
"InvalidCredentialInfo",
ErrorCategory.InvalidArgument,
cmdletPassedIn);
return false;
}
}
catch (Exception e)
{
errorRecord = new ErrorRecord(
new PSArgumentException("Invalid CredentialInfo values", e),
"InvalidCredentialInfo",
ErrorCategory.InvalidArgument,
cmdletPassedIn);
return false;
}
}
public static PSCredential GetRepositoryCredentialFromSecretManagement(
string repositoryName,
PSCredentialInfo repositoryCredentialInfo,
PSCmdlet cmdletPassedIn)
{
if (!IsSecretManagementVaultAccessible(repositoryName, repositoryCredentialInfo, cmdletPassedIn))
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException($"Cannot access Microsoft.PowerShell.SecretManagement vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication."),
"RepositoryCredentialSecretManagementInaccessibleVault",
ErrorCategory.ResourceUnavailable,
cmdletPassedIn));
return null;
}
try
{
using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
{
var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters(
new Hashtable() {
{ "Name", "Microsoft.PowerShell.SecretManagement"},
{ "PassThru", true}
}).Invoke<PSModuleInfo>();
if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0)
{
foreach (var err in pwsh.Streams.Error)
{
cmdletPassedIn.WriteError(err);
}
return null;
}
if (module == null)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Microsoft.PowerShell.SecretManagement module could not be imported for PSResourceRepository '{repositoryName}' authentication."),
"RepositoryCredentialCannotLoadSecretManagementModule",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
return null;
}
pwsh.Commands.Clear();
var results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Get-Secret").AddParameters(
new Hashtable() {
{ "Vault", repositoryCredentialInfo.VaultName },
{ "Name", repositoryCredentialInfo.SecretName }
}).Invoke<Object>();
if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0)
{
foreach (var err in pwsh.Streams.Error)
{
cmdletPassedIn.WriteError(err);
}
return null;
}
var secretValue = (results?.Count == 1) ? results[0] : null;
if (secretValue == null)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Microsoft.PowerShell.SecretManagement\\Get-Secret encountered an error while reading secret '{repositoryCredentialInfo.SecretName}' from vault '{repositoryCredentialInfo.VaultName}' for PSResourceRepository '{repositoryName}' authentication."),
"RepositoryCredentialCannotGetSecretFromVault",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
return null;
}
if (secretValue is PSObject secretObject)
{
if (secretObject.BaseObject is PSCredential secretCredential)
{
return secretCredential;
}
else if (secretObject.BaseObject is SecureString secretString)
{
return new PSCredential("token", secretString);
}
}
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSNotSupportedException($"Secret '{repositoryCredentialInfo.SecretName}' from vault '{repositoryCredentialInfo.VaultName}' has an invalid type. The only supported type is PSCredential."),
"RepositoryCredentialInvalidSecretType",
ErrorCategory.InvalidType,
cmdletPassedIn));
return null;
}
}
catch (Exception e)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Microsoft.PowerShell.SecretManagement\\Get-Secret encountered an error while reading secret '{repositoryCredentialInfo.SecretName}' from vault '{repositoryCredentialInfo.VaultName}' for PSResourceRepository '{repositoryName}' authentication.",
innerException: e),
"RepositoryCredentialCannotGetSecretFromVault",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
return null;
}
}
public static string GetAzAccessToken()
{
var credOptions = new DefaultAzureCredentialOptions
{
ExcludeEnvironmentCredential = true,
ExcludeVisualStudioCodeCredential = true,
ExcludeVisualStudioCredential = true,
ExcludeWorkloadIdentityCredential = true,
ExcludeManagedIdentityCredential = true, // ManagedIdentityCredential makes the experience slow
ExcludeSharedTokenCacheCredential = true, // SharedTokenCacheCredential is not supported on macOS
ExcludeAzureCliCredential = false,
ExcludeAzurePowerShellCredential = false,
ExcludeInteractiveBrowserCredential = false
};
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;
}
public static string GetContainerRegistryAccessTokenFromSecretManagement(
string repositoryName,
PSCredentialInfo repositoryCredentialInfo,
PSCmdlet cmdletPassedIn)
{
if (!IsSecretManagementVaultAccessible(repositoryName, repositoryCredentialInfo, cmdletPassedIn))
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException($"Cannot access Microsoft.PowerShell.SecretManagement vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication."),
"RepositoryCredentialSecretManagementInaccessibleVault",
ErrorCategory.ResourceUnavailable,
cmdletPassedIn));
return null;
}
var results = PowerShellInvoker.InvokeScriptWithHost<object>(
cmdlet: cmdletPassedIn,
script: @"
param (
[string] $VaultName,
[string] $SecretName
)
$module = Microsoft.PowerShell.Core\Import-Module -Name Microsoft.PowerShell.SecretManagement -PassThru
if ($null -eq $module) {
return
}
& $module ""Get-Secret"" -Name $SecretName -Vault $VaultName
",
args: new object[] { repositoryCredentialInfo.VaultName, repositoryCredentialInfo.SecretName },
out Exception terminatingError);
var secretValue = (results.Count == 1) ? results[0] : null;
if (secretValue == null)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Microsoft.PowerShell.SecretManagement\\Get-Secret encountered an error while reading secret \"{repositoryCredentialInfo.SecretName}\" from vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication.",
innerException: terminatingError),
"ContainerRegistryRepositoryCannotGetSecretFromVault",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
}
if (secretValue is SecureString secretSecureString)
{
string password = new NetworkCredential(string.Empty, secretSecureString).Password;
return password;
}
else if(secretValue is PSCredential psCredSecret)
{
string password = new NetworkCredential(string.Empty, psCredSecret.Password).Password;
return password;
}
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSNotSupportedException($"Secret \"{repositoryCredentialInfo.SecretName}\" from vault \"{repositoryCredentialInfo.VaultName}\" has an invalid type. The only supported type is PSCredential."),
"ContainerRegistryRepositoryTokenIsInvalidSecretType",
ErrorCategory.InvalidType,
cmdletPassedIn));
return null;
}
public static void SaveRepositoryCredentialToSecretManagementVault(
string repositoryName,
PSCredentialInfo repositoryCredentialInfo,
PSCmdlet cmdletPassedIn)
{
if (!IsSecretManagementVaultAccessible(repositoryName, repositoryCredentialInfo, cmdletPassedIn))
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException($"Cannot access Microsoft.PowerShell.SecretManagement vault \"{repositoryCredentialInfo.VaultName}\" for PSResourceRepository ({repositoryName}) authentication."),
"RepositoryCredentialSecretManagementInaccessibleVault",
ErrorCategory.ResourceUnavailable,
cmdletPassedIn));
return;
}
try
{
using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
{
var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters(
new Hashtable() {
{ "Name", "Microsoft.PowerShell.SecretManagement"},
{ "PassThru", true}
}).Invoke<PSModuleInfo>();
if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0)
{
foreach (var err in pwsh.Streams.Error)
{
cmdletPassedIn.WriteError(err);
}
return;
}
if (module == null)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Microsoft.PowerShell.SecretManagement module could not be imported for PSResourceRepository '{repositoryName}' authentication."),
"RepositoryCredentialCannotLoadSecretManagementModule",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
return;
}
pwsh.Commands.Clear();
var results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Set-Secret").AddParameters(
new Hashtable() {
{ "Secret", repositoryCredentialInfo.Credential},
{ "Vault", repositoryCredentialInfo.VaultName },
{ "Name", repositoryCredentialInfo.SecretName }
}).Invoke<Object>();
if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0)
{
foreach (var err in pwsh.Streams.Error)
{
cmdletPassedIn.WriteError(err);
}
}
return;
}
}
catch (Exception e)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Microsoft.PowerShell.SecretManagement\\Set-Secret encountered an error while adding secret '{repositoryCredentialInfo.SecretName}' to vault '{repositoryCredentialInfo.VaultName}' for PSResourceRepository '{repositoryName}' authentication.",
innerException: e),
"RepositoryCredentialCannotAddSecretToVault",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
}
}
public static bool IsSecretManagementModuleAvailable(
string repositoryName,
PSCmdlet cmdletPassedIn)
{
try
{
using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
{
var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters(
new Hashtable() {
{ "Name", "Microsoft.PowerShell.SecretManagement"},
{ "PassThru", true},
{ "ErrorAction", "Ignore"}
}).Invoke<PSModuleInfo>();
if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0)
{
foreach (var err in pwsh.Streams.Error)
{
cmdletPassedIn.WriteError(err);
}
return false;
}
if (module == null)
{
return false;
}
}
}
catch (Exception e)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Cannot validate Microsoft.PowerShell.SecretManagement module setup for PSResourceRepository '{repositoryName}' authentication.",
innerException: e),
"RepositoryCredentialSecretManagementInvalidModule",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
}
return true;
}
public static bool IsSecretManagementVaultAccessible(
string repositoryName,
PSCredentialInfo repositoryCredentialInfo,
PSCmdlet cmdletPassedIn)
{
try
{
using (System.Management.Automation.PowerShell pwsh = System.Management.Automation.PowerShell.Create())
{
var module = pwsh.AddCommand("Microsoft.PowerShell.Core\\Import-Module").AddParameters(
new Hashtable() {
{ "Name", "Microsoft.PowerShell.SecretManagement"},
{ "PassThru", true}
}).Invoke<PSModuleInfo>();
if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0)
{
foreach (var err in pwsh.Streams.Error)
{
cmdletPassedIn.WriteError(err);
}
return false;
}
if (module == null)
{
return false;
}
pwsh.Commands.Clear();
var results = pwsh.AddCommand("Microsoft.PowerShell.SecretManagement\\Test-SecretVault").AddParameters(
new Hashtable() {
{ "Name", repositoryCredentialInfo.VaultName }
}).Invoke<bool>();
if (pwsh.HadErrors || pwsh.Streams.Error.Count > 0)
{
foreach (var err in pwsh.Streams.Error)
{
cmdletPassedIn.WriteError(err);
}
return false;
}
if (results == null)
{
return false;
}
return results.Count > 0 ? results[0] : false;
}
}
catch (Exception e)
{
cmdletPassedIn.ThrowTerminatingError(
new ErrorRecord(
new PSInvalidOperationException(
message: $"Microsoft.PowerShell.SecretManagement\\Test-SecretVault encountered an error while validating the vault '{repositoryCredentialInfo.VaultName}' for PSResourceRepository '{repositoryName}' authentication.",
innerException: e),
"RepositoryCredentialSecretManagementInvalidVault",
ErrorCategory.InvalidOperation,
cmdletPassedIn));
return false;
}
}
public static NetworkCredential SetNetworkCredential(
PSRepositoryInfo repository,
NetworkCredential networkCredential,
PSCmdlet cmdletPassedIn)
{
// Explicitly passed in Credential takes precedence over repository CredentialInfo.
if (networkCredential == null && repository.CredentialInfo != null)
{
PSCredential repoCredential = Utils.GetRepositoryCredentialFromSecretManagement(
repository.Name,
repository.CredentialInfo,
cmdletPassedIn);
networkCredential = new NetworkCredential(repoCredential.UserName, repoCredential.Password);
cmdletPassedIn.WriteVerbose("credential successfully read from vault and set for repository: " + repository.Name);
}
return networkCredential;
}
#endregion
#region Path methods
public static string[] GetSubDirectories(string dirPath)
{
try
{
return Directory.GetDirectories(dirPath);
}
catch
{
return EmptyStrArray;
}
}
public static string[] GetDirectoryFiles(string dirPath)
{
try
{
return Directory.GetFiles(dirPath);
}
catch
{
return EmptyStrArray;
}
}
public static string GetInstalledPackageName(string pkgPath)
{
if (string.IsNullOrEmpty(pkgPath))
{
return string.Empty;
}
if (File.Exists(pkgPath))
{
// ex: ./PowerShell/Scripts/TestScript.ps1
return Path.GetFileNameWithoutExtension(pkgPath);
}
// expecting the full version module path
// ex: ./PowerShell/Modules/TestModule/1.0.0
return new DirectoryInfo(pkgPath).Parent.Name;
}
// Find all potential resource paths
public static List<string> GetPathsFromEnvVarAndScope(
PSCmdlet psCmdlet,
ScopeType? scope)
{
GetStandardPlatformPaths(
psCmdlet,
out string myDocumentsPath,