-
Notifications
You must be signed in to change notification settings - Fork 104
Expand file tree
/
Copy pathRepositorySettings.cs
More file actions
1026 lines (891 loc) · 50.7 KB
/
RepositorySettings.cs
File metadata and controls
1026 lines (891 loc) · 50.7 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Xml;
using System.Xml.Linq;
using Microsoft.PowerShell.PSResourceGet.Cmdlets;
using static Microsoft.PowerShell.PSResourceGet.UtilClasses.PSRepositoryInfo;
namespace Microsoft.PowerShell.PSResourceGet.UtilClasses
{
/// <summary>
/// The class contains basic information of a repository path settings as well as methods to
/// perform Create/Read/Update/Delete operations on the repository store file.
/// </summary>
internal static class RepositorySettings
{
#region Members
// File name for a user's repository store file is 'PSResourceRepository.xml'
// The repository store file's location is currently only at '%LOCALAPPDATA%\PSResourceGet' for the user account.
private const string PSGalleryRepoName = "PSGallery";
private const string PSGalleryRepoUri = "https://www.powershellgallery.com/api/v2";
private const int DefaultPriority = 50;
private const bool DefaultTrusted = false;
private const string RepositoryFileName = "PSResourceRepository.xml";
private static readonly string RepositoryPath = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.LocalApplicationData), "PSResourceGet");
private static readonly string FullRepositoryPath = Path.Combine(RepositoryPath, RepositoryFileName);
#endregion
#region Public methods
/// <summary>
/// Check if repository store xml file exists, if not then create
/// </summary>
public static void CheckRepositoryStore()
{
if (!File.Exists(FullRepositoryPath))
{
try
{
if (!Directory.Exists(RepositoryPath))
{
Directory.CreateDirectory(RepositoryPath);
}
XDocument newRepoXML = new XDocument(
new XElement("configuration"));
newRepoXML.Save(FullRepositoryPath);
}
catch (Exception e)
{
throw new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Repository store creation failed with error: {0}.", e.Message));
}
// Add PSGallery to the newly created store
Uri psGalleryUri = new Uri(PSGalleryRepoUri);
Add(PSGalleryRepoName, psGalleryUri, DefaultPriority, DefaultTrusted, repoCredentialInfo: null, repoCredentialProvider: CredentialProviderType.None, APIVersion.V2, force: false);
}
// Open file (which should exist now), if cannot/is corrupted then throw error
try
{
LoadXDocument(FullRepositoryPath);
}
catch (Exception e)
{
throw new PSInvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Repository store may be corrupted, file reading failed with error: {0}. Try running 'Reset-PSResourceRepository' to reset the repository store.", e.Message));
}
}
public static PSRepositoryInfo AddRepository(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, APIVersion? apiVersion, PSCredentialInfo repoCredentialInfo, CredentialProviderType? repoCredentialProvider, bool force, PSCmdlet cmdletPassedIn, out string errorMsg)
{
errorMsg = String.Empty;
if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase))
{
errorMsg = "Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery";
return null;
}
return AddToRepositoryStore(repoName, repoUri, repoPriority, repoTrusted, apiVersion, repoCredentialInfo, repoCredentialProvider, force, cmdletPassedIn, out errorMsg);
}
public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, APIVersion? apiVersion, PSCredentialInfo repoCredentialInfo, CredentialProviderType? credentialProvider, bool force, PSCmdlet cmdletPassedIn, out string errorMsg)
{
errorMsg = string.Empty;
// remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition
repoName = repoName.Trim(' ');
if (String.IsNullOrEmpty(repoName) || repoName.Contains("*"))
{
throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace");
}
// repositories with Uri Scheme "temp" may have PSPath Uri's like: "Temp:\repo"
if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile || repoUri.Scheme.Equals("temp", StringComparison.OrdinalIgnoreCase)))
{
errorMsg = "Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based or temp.";
return null;
}
APIVersion resolvedAPIVersion = apiVersion ?? GetRepoAPIVersion(repoUri);
if (repoCredentialInfo != null)
{
bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn);
if (repoCredentialInfo.Credential != null)
{
if (!isSecretManagementModuleAvailable)
{
errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault.";
return null;
}
else
{
Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn);
}
}
if (!isSecretManagementModuleAvailable)
{
cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo.");
}
}
CredentialProviderType resolvedCredentialProvider = credentialProvider ?? CredentialProviderType.None;
// If it's an ADO feed with an ADO designated URL (eg: msazure.pkgs.) then add the 'CredentialProvider' attribute to the repository and by default set it to AzArtifacts
if ((repoUri.AbsoluteUri.Contains("pkgs.dev.azure.com") || repoUri.AbsoluteUri.Contains("pkgs.visualstudio.com")) && credentialProvider == null)
{
resolvedCredentialProvider = CredentialProviderType.AzArtifacts;
}
if (!cmdletPassedIn.ShouldProcess(repoName, "Register repository to repository store"))
{
return null;
}
if (!string.IsNullOrEmpty(errorMsg))
{
return null;
}
var repo = Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, resolvedCredentialProvider, resolvedAPIVersion, force);
return repo;
}
public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, APIVersion? apiVersion, PSCredentialInfo repoCredentialInfo, CredentialProviderType? credentialProvider, PSCmdlet cmdletPassedIn, out string errorMsg)
{
errorMsg = string.Empty;
// repositories with Uri Scheme "temp" may have PSPath Uri's like: "Temp:\repo"
if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile || repoUri.Scheme.Equals("temp", StringComparison.OrdinalIgnoreCase)))
{
errorMsg = "Invalid Uri, Uri must be one of the following schemes: HTTPS, HTTP, FTP, File Based";
return null;
}
// check repoName can't contain * or just be whitespace
// remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition
repoName = repoName.Trim();
if (String.IsNullOrEmpty(repoName) || repoName.Contains("*"))
{
errorMsg = "Name cannot be null or empty, or contain wildcards";
return null;
}
// check PSGallery Uri is not trying to be set
if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUri != null)
{
errorMsg = "The PSGallery repository has a predefined Uri. Setting the -Uri parameter for this repository is not allowed. Please run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery.";
return null;
}
// check PSGallery CredentialInfo is not trying to be set
if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoCredentialInfo != null)
{
errorMsg = "Setting the -CredentialInfo parameter for PSGallery is not allowed. Run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery.";
return null;
}
// determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable)
bool? _trustedNullable = isSet ? new bool?(repoTrusted) : new bool?();
if (repoCredentialInfo != null)
{
bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn);
if (repoCredentialInfo.Credential != null)
{
if (!isSecretManagementModuleAvailable)
{
errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault.";
return null;
}
else
{
Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn);
}
}
if (!isSecretManagementModuleAvailable)
{
cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo.");
}
}
if (!cmdletPassedIn.ShouldProcess(repoName, "Set repository's value(s) in repository store"))
{
return null;
}
if (!string.IsNullOrEmpty(errorMsg))
{
return null;
}
return Update(repoName, repoUri, repoPriority, _trustedNullable, apiVersion, repoCredentialInfo, credentialProvider, cmdletPassedIn, out errorMsg);
}
/// <summary>
/// Add a repository to the store
/// Returns: PSRepositoryInfo containing information about the repository just added to the repository store
/// </summary>
/// <param name="sectionName"></param>
public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, CredentialProviderType repoCredentialProvider, APIVersion apiVersion, bool force)
{
try
{
// Open file
XDocument doc = LoadXDocument(FullRepositoryPath);
if (FindRepositoryElement(doc, repoName) != null)
{
if (!force)
{
throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName));
}
// Delete the existing repository before overwriting it (otherwise multiple repos with the same name will be added)
List<PSRepositoryInfo> removedRepositories = Remove(new string[] { repoName }, out string[] errorList);
// Need to load the document again because of changes after removing
doc = LoadXDocument(FullRepositoryPath);
if (errorList.Count() > 0)
{
throw new PSInvalidOperationException($"The PSResource Repository '{repoName}' cannot be overwritten: ${errorList.FirstOrDefault()}");
}
}
// Else, keep going
// Get root of XDocument (XElement)
var root = doc.Root;
// Create new element
XElement newElement = new XElement(
"Repository",
new XAttribute("Name", repoName),
new XAttribute("Url", repoUri),
new XAttribute("APIVersion", apiVersion),
new XAttribute("Priority", repoPriority),
new XAttribute("Trusted", repoTrusted),
new XAttribute("CredentialProvider", repoCredentialProvider)
);
if (repoCredentialInfo != null)
{
newElement.Add(new XAttribute(PSCredentialInfo.VaultNameAttribute, repoCredentialInfo.VaultName));
newElement.Add(new XAttribute(PSCredentialInfo.SecretNameAttribute, repoCredentialInfo.SecretName));
}
root.Add(newElement);
// Close the file
root.Save(FullRepositoryPath);
}
catch (Exception e)
{
throw new PSInvalidOperationException(String.Format("Adding to repository store failed: {0}", e.Message));
}
bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repoUri) : true;
return new PSRepositoryInfo(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, repoCredentialProvider, apiVersion, isAllowed);
}
/// <summary>
/// Updates a repository name, Uri, priority, installation policy, or credential information
/// Returns: void
/// </summary>
public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, APIVersion? apiVersion, PSCredentialInfo repoCredentialInfo, CredentialProviderType? credentialProvider, PSCmdlet cmdletPassedIn, out string errorMsg)
{
errorMsg = string.Empty;
PSRepositoryInfo updatedRepo;
try
{
// Open file
XDocument doc = LoadXDocument(FullRepositoryPath);
XElement node = FindRepositoryElement(doc, repoName);
if (node == null)
{
bool repoIsTrusted = !(repoTrusted == null || repoTrusted == false);
repoPriority = repoPriority < 0 ? DefaultPriority : repoPriority;
return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, apiVersion, repoCredentialInfo, credentialProvider, force:true, cmdletPassedIn, out errorMsg);
}
// Check that repository node we are attempting to update has all required attributes: Name, Url (or Uri), Priority, Trusted.
// Name attribute is already checked for in FindRepositoryElement()
if (node.Attribute("Priority") == null)
{
errorMsg = $"Repository element does not contain necessary 'Priority' attribute, in file located at path: {FullRepositoryPath}. Fix this in your file and run again.";
return null;
}
if (node.Attribute("Trusted") == null)
{
errorMsg = $"Repository element does not contain necessary 'Trusted' attribute, in file located at path: {FullRepositoryPath}. Fix this in your file and run again.";
return null;
}
if (node.Attribute("APIVersion") == null)
{
errorMsg = $"Repository element does not contain necessary 'APIVersion' attribute, in file located at path: {FullRepositoryPath}. Fix this in your file and run again.";
return null;
}
bool urlAttributeExists = node.Attribute("Url") != null;
bool uriAttributeExists = node.Attribute("Uri") != null;
if (!urlAttributeExists && !uriAttributeExists)
{
errorMsg = $"Repository element does not contain necessary 'Url' attribute (or alternatively 'Uri' attribute), in file located at path: {FullRepositoryPath}. Fix this in your file and run again.";
return null;
}
// Else, keep going
// Get root of XDocument (XElement)
var root = doc.Root;
// A null Uri (or Url) value passed in signifies the Uri was not attempted to be set.
// So only set Uri attribute if non-null value passed in for repoUri
// determine if existing repository node (which we wish to update) had Url or Uri attribute
Uri thisUrl = null;
if (repoUri != null)
{
if (urlAttributeExists)
{
node.Attribute("Url").Value = repoUri.ToString();
}
else
{
node.Attribute("Uri").Value = repoUri.ToString();
}
thisUrl = repoUri;
if (apiVersion == null)
{
apiVersion = GetRepoAPIVersion(repoUri);
}
}
else
{
if (urlAttributeExists)
{
if(!Uri.TryCreate(node.Attribute("Url").Value, UriKind.Absolute, out thisUrl))
{
throw new PSInvalidOperationException(String.Format("The 'Url' for repository {0} is invalid and the repository cannot be used. Please update the Url field or remove the repository entry.", repoName));
}
}
else
{
if(!Uri.TryCreate(node.Attribute("Uri").Value, UriKind.Absolute, out thisUrl))
{
throw new PSInvalidOperationException(String.Format("The 'Url' for repository {0} is invalid and the repository cannot be used. Please update the Url field or remove the repository entry.", repoName));
}
}
}
// A negative Priority value passed in signifies the Priority value was not attempted to be set.
// So only set Priority attribute if non-null value passed in for repoPriority
if (repoPriority >= 0)
{
node.Attribute("Priority").Value = repoPriority.ToString();
}
// A null Trusted value passed in signifies the Trusted value was not attempted to be set.
// So only set Trusted attribute if non-null value passed in for repoTrusted.
if (repoTrusted != null)
{
node.Attribute("Trusted").Value = repoTrusted.ToString();
}
// A null CredentialInfo value passed in signifies that CredentialInfo was not attempted to be set.
// Set VaultName and SecretName attributes if non-null value passed in for repoCredentialInfo
if (repoCredentialInfo != null)
{
if (node.Attribute(PSCredentialInfo.VaultNameAttribute) == null)
{
node.Add(new XAttribute(PSCredentialInfo.VaultNameAttribute, repoCredentialInfo.VaultName));
}
else
{
node.Attribute(PSCredentialInfo.VaultNameAttribute).Value = repoCredentialInfo.VaultName;
}
if (node.Attribute(PSCredentialInfo.SecretNameAttribute) == null)
{
node.Add(new XAttribute(PSCredentialInfo.SecretNameAttribute, repoCredentialInfo.SecretName));
}
else
{
node.Attribute(PSCredentialInfo.SecretNameAttribute).Value = repoCredentialInfo.SecretName;
}
}
// Update APIVersion if necessary
APIVersion resolvedAPIVersion = APIVersion.Unknown;
if (apiVersion != null)
{
resolvedAPIVersion = (APIVersion)apiVersion;
node.Attribute("APIVersion").Value = resolvedAPIVersion.ToString();
}
else
{
resolvedAPIVersion = (APIVersion)Enum.Parse(typeof(APIVersion), node.Attribute("APIVersion").Value, ignoreCase: true);
}
// Create CredentialInfo based on new values or whether it was empty to begin with
PSCredentialInfo thisCredentialInfo = null;
if (node.Attribute(PSCredentialInfo.VaultNameAttribute)?.Value != null &&
node.Attribute(PSCredentialInfo.SecretNameAttribute)?.Value != null)
{
thisCredentialInfo = new PSCredentialInfo(
node.Attribute(PSCredentialInfo.VaultNameAttribute).Value,
node.Attribute(PSCredentialInfo.SecretNameAttribute).Value);
}
if (GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled())
{
var allowedList = GroupPolicyRepositoryEnforcement.GetAllowedRepositoryURIs();
}
// Update CredentialProvider if necessary
CredentialProviderType resolvedCredentialProvider = credentialProvider ?? CredentialProviderType.None;
if (credentialProvider != null)
{
resolvedCredentialProvider = (CredentialProviderType)credentialProvider;
if (node.Attribute("CredentialProvider") == null)
{
node.Add(new XAttribute("CredentialProvider", resolvedCredentialProvider.ToString()));
}
else
{
node.Attribute("CredentialProvider").Value = resolvedCredentialProvider.ToString();
}
}
bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true;
updatedRepo = new PSRepositoryInfo(repoName,
thisUrl,
Int32.Parse(node.Attribute("Priority").Value),
Boolean.Parse(node.Attribute("Trusted").Value),
thisCredentialInfo,
resolvedCredentialProvider,
resolvedAPIVersion,
isAllowed);
// Close the file
root.Save(FullRepositoryPath);
}
catch (Exception e)
{
throw new PSInvalidOperationException(String.Format("Updating to repository store failed: {0}", e.Message));
}
return updatedRepo;
}
/// <summary>
/// Removes a repository from the XML
/// Returns: void
/// </summary>
/// <param name="sectionName"></param>
public static List<PSRepositoryInfo> Remove(string[] repoNames, out string[] errorList)
{
List<PSRepositoryInfo> removedRepos = new List<PSRepositoryInfo>();
List<string> tempErrorList = new List<string>();
XDocument doc;
try
{
// Open file
doc = LoadXDocument(FullRepositoryPath);
}
catch (Exception e)
{
throw new PSInvalidOperationException(String.Format("Loading repository store failed: {0}", e.Message));
}
// Get root of XDocument (XElement)
var root = doc.Root;
foreach (string repo in repoNames)
{
XElement node = FindRepositoryElement(doc, repo);
if (node == null)
{
tempErrorList.Add(String.Format("Unable to find repository '{0}'. Use Get-PSResourceRepository to see all available repositories.", repo));
continue;
}
PSCredentialInfo repoCredentialInfo = null;
if (node.Attribute("VaultName") != null & node.Attribute("SecretName") != null)
{
repoCredentialInfo = new PSCredentialInfo(node.Attribute("VaultName").Value, node.Attribute("SecretName").Value);
}
if (node.Attribute("Priority") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Priority' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
if (node.Attribute("Trusted") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Trusted' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
if (node.Attribute("APIVersion") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'APIVersion' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
CredentialProviderType resolvedCredentialProvider = CredentialProviderType.None;
if (node.Attribute("CredentialProvider") != null)
{
resolvedCredentialProvider = (CredentialProviderType)Enum.Parse(typeof(CredentialProviderType), node.Attribute("CredentialProvider").Value, ignoreCase: true);
}
// determine if repo had Url or Uri (less likely) attribute
bool urlAttributeExists = node.Attribute("Url") != null;
bool uriAttributeExists = node.Attribute("Uri") != null;
if (!urlAttributeExists && !uriAttributeExists)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Url' or equivalent 'Uri' attribute (it must contain one per Repository), in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
string attributeUrlUriName = urlAttributeExists ? "Url" : "Uri";
Uri repoUri = new Uri(node.Attribute(attributeUrlUriName).Value);
bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(repoUri) : true;
removedRepos.Add(
new PSRepositoryInfo(repo,
new Uri(node.Attribute(attributeUrlUriName).Value),
Int32.Parse(node.Attribute("Priority").Value),
Boolean.Parse(node.Attribute("Trusted").Value),
repoCredentialInfo,
resolvedCredentialProvider,
(APIVersion)Enum.Parse(typeof(APIVersion), node.Attribute("APIVersion").Value, ignoreCase: true),
isAllowed));
// Remove item from file
node.Remove();
}
// Close the file
root.Save(FullRepositoryPath);
errorList = tempErrorList.ToArray();
return removedRepos;
}
public static List<PSRepositoryInfo> Read(string[] repoNames, out string[] errorList)
{
List<string> tempErrorList = new List<string>();
var foundRepos = new List<PSRepositoryInfo>();
XDocument doc;
try
{
// Open file
doc = LoadXDocument(FullRepositoryPath);
}
catch (Exception e)
{
throw new PSInvalidOperationException(String.Format("Loading repository store failed: {0}", e.Message));
}
if (repoNames == null || repoNames.Length == 0 || string.Equals(repoNames[0], "*") || repoNames[0] == null)
{
// Name array or single value is null so we will list all repositories registered
// iterate through the doc
foreach (XElement repo in doc.Descendants("Repository"))
{
if (repo.Attribute("Name") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Name' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
if (repo.Attribute("Priority") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Priority' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
if (repo.Attribute("Trusted") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Trusted' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
bool urlAttributeExists = repo.Attribute("Url") != null;
bool uriAttributeExists = repo.Attribute("Uri") != null;
// case: neither Url nor Uri attributes exist
if (!urlAttributeExists && !uriAttributeExists)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Url' or equivalent 'Uri' attribute (it must contain one), in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
Uri thisUrl = null;
// case: either attribute Uri or Url exists
// TODO: do we only allow both to exist, across repositories? (i.e if a file has Uri attribute for one repo and Url attribute for another --> is that invalid?)
if (urlAttributeExists)
{
if (!Uri.TryCreate(repo.Attribute("Url").Value, UriKind.Absolute, out thisUrl))
{
tempErrorList.Add(String.Format("Unable to read incorrectly formatted Url for repo {0}", repo.Attribute("Name").Value));
continue;
}
}
else if (uriAttributeExists)
{
if (!Uri.TryCreate(repo.Attribute("Uri").Value, UriKind.Absolute, out thisUrl))
{
tempErrorList.Add(String.Format("Unable to read incorrectly formatted Uri for repo {0}", repo.Attribute("Name").Value));
continue;
}
}
if (repo.Attribute("APIVersion") == null)
{
APIVersion apiVersion = GetRepoAPIVersion(thisUrl);
XElement repoXElem = FindRepositoryElement(doc, repo.Attribute("Name").Value);
repoXElem.SetAttributeValue("APIVersion", apiVersion.ToString());
doc.Save(FullRepositoryPath);
}
CredentialProviderType credentialProvider = CredentialProviderType.None;
if (repo.Attribute("CredentialProvider") != null)
{
credentialProvider = (CredentialProviderType)Enum.Parse(typeof(CredentialProviderType), repo.Attribute("CredentialProvider").Value, ignoreCase: true);
}
PSCredentialInfo thisCredentialInfo;
string credentialInfoErrorMessage = $"Repository {repo.Attribute("Name").Value} has invalid CredentialInfo. {PSCredentialInfo.VaultNameAttribute} and {PSCredentialInfo.SecretNameAttribute} should both be present and non-empty";
// both keys are present
if (repo.Attribute(PSCredentialInfo.VaultNameAttribute) != null && repo.Attribute(PSCredentialInfo.SecretNameAttribute) != null)
{
try
{
// both values are non-empty
// = valid credentialInfo
thisCredentialInfo = new PSCredentialInfo(repo.Attribute(PSCredentialInfo.VaultNameAttribute).Value, repo.Attribute(PSCredentialInfo.SecretNameAttribute).Value);
}
catch (Exception)
{
thisCredentialInfo = null;
tempErrorList.Add(credentialInfoErrorMessage);
continue;
}
}
// both keys are missing
else if (repo.Attribute(PSCredentialInfo.VaultNameAttribute) == null && repo.Attribute(PSCredentialInfo.SecretNameAttribute) == null)
{
// = valid credentialInfo
thisCredentialInfo = null;
}
// one of the keys is missing
else
{
thisCredentialInfo = null;
tempErrorList.Add(credentialInfoErrorMessage);
continue;
}
bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true;
PSRepositoryInfo currentRepoItem = new PSRepositoryInfo(repo.Attribute("Name").Value,
thisUrl,
Int32.Parse(repo.Attribute("Priority").Value),
Boolean.Parse(repo.Attribute("Trusted").Value),
thisCredentialInfo,
credentialProvider,
(APIVersion)Enum.Parse(typeof(APIVersion), repo.Attribute("APIVersion").Value, ignoreCase: true),
isAllowed);
foundRepos.Add(currentRepoItem);
}
}
else
{
foreach (string repo in repoNames)
{
bool repoMatch = false;
WildcardPattern nameWildCardPattern = new WildcardPattern(repo, WildcardOptions.IgnoreCase);
foreach (var node in doc.Descendants("Repository").Where(e => e.Attribute("Name") != null && nameWildCardPattern.IsMatch(e.Attribute("Name").Value)))
{
if (node.Attribute("Priority") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Priority' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
if (node.Attribute("Trusted") == null)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Trusted' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
repoMatch = true;
bool urlAttributeExists = node.Attribute("Url") != null;
bool uriAttributeExists = node.Attribute("Uri") != null;
// case: neither Url nor Uri attributes exist
if (!urlAttributeExists && !uriAttributeExists)
{
tempErrorList.Add(String.Format("Repository element does not contain necessary 'Url' or equivalent 'Uri' attribute (it must contain one), in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath));
continue;
}
Uri thisUrl = null;
// case: either attribute Uri or Url exists
// TODO: do we only allow both to exist, across repositories? (i.e if a file has Uri attribute for one repo and Url attribute for another --> is that invalid?)
if (urlAttributeExists)
{
if (!Uri.TryCreate(node.Attribute("Url").Value, UriKind.Absolute, out thisUrl))
{
tempErrorList.Add(String.Format("Unable to read incorrectly formatted Url for repo {0}", node.Attribute("Name").Value));
continue;
}
}
else if (uriAttributeExists)
{
if (!Uri.TryCreate(node.Attribute("Uri").Value, UriKind.Absolute, out thisUrl))
{
tempErrorList.Add(String.Format("Unable to read incorrectly formatted Uri for repo {0}", node.Attribute("Name").Value));
continue;
}
}
if (node.Attribute("APIVersion") == null)
{
APIVersion apiVersion = GetRepoAPIVersion(thisUrl);
XElement repoXElem = FindRepositoryElement(doc, node.Attribute("Name").Value);
repoXElem.SetAttributeValue("APIVersion", apiVersion.ToString());
doc.Save(FullRepositoryPath);
}
CredentialProviderType credentialProvider = CredentialProviderType.None;
if (node.Attribute("CredentialProvider") != null)
{
credentialProvider = (CredentialProviderType)Enum.Parse(typeof(CredentialProviderType), node.Attribute("CredentialProvider").Value, ignoreCase: true);
}
PSCredentialInfo thisCredentialInfo;
string credentialInfoErrorMessage = $"Repository {node.Attribute("Name").Value} has invalid CredentialInfo. {PSCredentialInfo.VaultNameAttribute} and {PSCredentialInfo.SecretNameAttribute} should both be present and non-empty";
// both keys are present
if (node.Attribute(PSCredentialInfo.VaultNameAttribute) != null && node.Attribute(PSCredentialInfo.SecretNameAttribute) != null)
{
try
{
// both values are non-empty
// = valid credentialInfo
thisCredentialInfo = new PSCredentialInfo(node.Attribute(PSCredentialInfo.VaultNameAttribute).Value, node.Attribute(PSCredentialInfo.SecretNameAttribute).Value);
}
catch (Exception)
{
thisCredentialInfo = null;
tempErrorList.Add(credentialInfoErrorMessage);
continue;
}
}
// both keys are missing
else if (node.Attribute(PSCredentialInfo.VaultNameAttribute) == null && node.Attribute(PSCredentialInfo.SecretNameAttribute) == null)
{
// = valid credentialInfo
thisCredentialInfo = null;
}
// one of the keys is missing
else
{
thisCredentialInfo = null;
tempErrorList.Add(credentialInfoErrorMessage);
continue;
}
bool isAllowed = GroupPolicyRepositoryEnforcement.IsGroupPolicyEnabled() ? GroupPolicyRepositoryEnforcement.IsRepositoryAllowed(thisUrl) : true;
PSRepositoryInfo currentRepoItem = new PSRepositoryInfo(node.Attribute("Name").Value,
thisUrl,
Int32.Parse(node.Attribute("Priority").Value),
Boolean.Parse(node.Attribute("Trusted").Value),
thisCredentialInfo,
credentialProvider,
(APIVersion)Enum.Parse(typeof(APIVersion), node.Attribute("APIVersion").Value, ignoreCase: true),
isAllowed);
foundRepos.Add(currentRepoItem);
}
if (!repo.Contains("*") && !repoMatch)
{
tempErrorList.Add(String.Format("Unable to find repository with Name '{0}'. Use Get-PSResourceRepository to see all available repositories.", repo));
}
}
}
errorList = tempErrorList.ToArray();
// Sort by priority, then by repo name
var reposToReturn = foundRepos.OrderBy(x => x.Priority).ThenBy(x => x.Name);
return reposToReturn.ToList();
}
/// <summary>
/// Reset the repository store by creating a new PSRepositories.xml file with PSGallery registered.
/// This creates a temporary new file first, and only replaces the old file if creation succeeds.
/// If creation fails, the old file is restored.
/// Returns: PSRepositoryInfo for the PSGallery repository
/// </summary>
public static PSRepositoryInfo Reset(out string errorMsg)
{
errorMsg = string.Empty;
string tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".xml");
string backupFilePath = string.Empty;
try
{
// Ensure the repository directory exists
if (!Directory.Exists(RepositoryPath))
{
Directory.CreateDirectory(RepositoryPath);
}
// Create new repository XML in a temporary location
XDocument newRepoXML = new XDocument(
new XElement("configuration"));
newRepoXML.Save(tempFilePath);
// Validate that the temporary file can be loaded
try
{
LoadXDocument(tempFilePath);
}
catch (Exception loadEx)
{
// Clean up temp file on validation failure
if (File.Exists(tempFilePath))
{
try
{
File.Delete(tempFilePath);
}
catch (Exception cleanupEx)
{
errorMsg = string.Format(CultureInfo.InvariantCulture, "Failed to validate newly created repository store file with error: {0}. Additionally, cleanup of temporary file failed with error: {1}", loadEx.Message, cleanupEx.Message);
return null;
}
}
errorMsg = string.Format(CultureInfo.InvariantCulture, "Failed to validate newly created repository store file with error: {0}.", loadEx.Message);
return null;
}
// Back up the existing file if it exists
if (File.Exists(FullRepositoryPath))
{
backupFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + "_backup.xml");
Utils.MoveFiles(FullRepositoryPath, backupFilePath, overwrite: true);
}
// Move the temporary file to the actual location
Utils.MoveFiles(tempFilePath, FullRepositoryPath, overwrite: true);
// Add PSGallery to the newly created store
Uri psGalleryUri = new Uri(PSGalleryRepoUri);
PSRepositoryInfo psGalleryRepo = Add(PSGalleryRepoName, psGalleryUri, DefaultPriority, DefaultTrusted, repoCredentialInfo: null, repoCredentialProvider: CredentialProviderType.None, APIVersion.V2, force: false);
// Clean up backup file on success
if (!string.IsNullOrEmpty(backupFilePath) && File.Exists(backupFilePath))
{
File.Delete(backupFilePath);
}
return psGalleryRepo;
}
catch (Exception e)
{
// Restore the backup file if it exists
if (!string.IsNullOrEmpty(backupFilePath) && File.Exists(backupFilePath))
{
try
{
if (File.Exists(FullRepositoryPath))
{
File.Delete(FullRepositoryPath);
}
Utils.MoveFiles(backupFilePath, FullRepositoryPath, overwrite: true);
}
catch (Exception restoreEx)
{
errorMsg = string.Format(CultureInfo.InvariantCulture, "Repository store reset failed with error: {0}. An attempt to restore the old repository store also failed with error: {1}", e.Message, restoreEx.Message);
return null;
}
}
// Clean up temporary file
if (File.Exists(tempFilePath))
{
try
{
File.Delete(tempFilePath);
}
catch (Exception cleanupEx)
{
errorMsg = string.Format(CultureInfo.InvariantCulture, "Repository store reset failed with error: {0}. Additionally, cleanup of temporary file failed with error: {1}", e.Message, cleanupEx.Message);
return null;
}
}
errorMsg = string.Format(CultureInfo.InvariantCulture, "Repository store reset failed with error: {0}.", e.Message);
return null;
}
}
#endregion
#region Private methods
private static XElement FindRepositoryElement(XDocument doc, string name)
{
return doc.Descendants("Repository").Where(
e => e.Attribute("Name") != null &&
string.Equals(
e.Attribute("Name").Value,
name,
StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
}
private static readonly XmlReaderSettings XDocReaderSettings = new XmlReaderSettings()
{
DtdProcessing = DtdProcessing.Prohibit, // Disallow any DTD elements
XmlResolver = null, // Do not resolve external links
CheckCharacters = true,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
IgnoreWhitespace = true,
MaxCharactersFromEntities = 1024,
MaxCharactersInDocument = 512 * 1024 * 1024, // 512M characters = 1GB
ValidationFlags = System.Xml.Schema.XmlSchemaValidationFlags.None,
ValidationType = ValidationType.None
};
private static XDocument LoadXDocument(string filePath)
{
using var xmlReader = XmlReader.Create(filePath, XDocReaderSettings);
return XDocument.Load(xmlReader);
}
private static APIVersion GetRepoAPIVersion(Uri repoUri)
{
if (repoUri.AbsoluteUri.EndsWith("/v2", StringComparison.OrdinalIgnoreCase))
{
// Scenario: V2 server protocol repositories (i.e PSGallery)
return APIVersion.V2;
}
else if (repoUri.AbsoluteUri.EndsWith("/index.json", StringComparison.OrdinalIgnoreCase))
{