-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathContainerRegistryServerAPICalls.cs
1727 lines (1510 loc) · 78.1 KB
/
ContainerRegistryServerAPICalls.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.PowerShell.PSResourceGet.UtilClasses;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using NuGet.Versioning;
using System.Threading.Tasks;
using System.Net;
using System.Management.Automation;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.Net.Http.Headers;
using System.Linq;
using Microsoft.PowerShell.PSResourceGet.Cmdlets;
using System.Text;
using System.Security.Cryptography;
using System.Text.Json;
namespace Microsoft.PowerShell.PSResourceGet
{
internal class ContainerRegistryServerAPICalls : ServerApiCall
{
// Any interface method that is not implemented here should be processed in the parent method and then call one of the implemented
// methods below.
#region Members
public override PSRepositoryInfo Repository { get; set; }
public String Registry { get; set; }
private readonly PSCmdlet _cmdletPassedIn;
private HttpClient _sessionClient { get; set; }
private static readonly Hashtable[] emptyHashResponses = new Hashtable[] { };
private static FindResponseType containerRegistryFindResponseType = FindResponseType.ResponseString;
private static readonly FindResults emptyResponseResults = new FindResults(stringResponse: Utils.EmptyStrArray, hashtableResponse: emptyHashResponses, responseType: containerRegistryFindResponseType);
const string containerRegistryRefreshTokenTemplate = "grant_type=access_token&service={0}&tenant={1}&access_token={2}"; // 0 - registry, 1 - tenant, 2 - access token
const string containerRegistryAccessTokenTemplate = "grant_type=refresh_token&service={0}&scope=repository:*:*&refresh_token={1}"; // 0 - registry, 1 - refresh token
const string containerRegistryOAuthExchangeUrlTemplate = "https://{0}/oauth2/exchange"; // 0 - registry
const string containerRegistryOAuthTokenUrlTemplate = "https://{0}/oauth2/token"; // 0 - registry
const string containerRegistryManifestUrlTemplate = "https://{0}/v2/{1}/manifests/{2}"; // 0 - registry, 1 - repo(modulename), 2 - tag(version)
const string containerRegistryBlobDownloadUrlTemplate = "https://{0}/v2/{1}/blobs/{2}"; // 0 - registry, 1 - repo(modulename), 2 - layer digest
const string containerRegistryFindImageVersionUrlTemplate = "https://{0}/v2/{1}/tags/list"; // 0 - registry, 1 - repo(modulename)
const string containerRegistryStartUploadTemplate = "https://{0}/v2/{1}/blobs/uploads/"; // 0 - registry, 1 - packagename
const string containerRegistryEndUploadTemplate = "https://{0}{1}&digest=sha256:{2}"; // 0 - registry, 1 - location, 2 - digest
#endregion
#region Constructor
public ContainerRegistryServerAPICalls(PSRepositoryInfo repository, PSCmdlet cmdletPassedIn, NetworkCredential networkCredential, string userAgentString) : base(repository, networkCredential)
{
Repository = repository;
Registry = Repository.Uri.Host;
_cmdletPassedIn = cmdletPassedIn;
HttpClientHandler handler = new HttpClientHandler()
{
Credentials = networkCredential
};
_sessionClient = new HttpClient(handler);
_sessionClient.Timeout = TimeSpan.FromMinutes(10);
_sessionClient.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", userAgentString);
}
#endregion
#region Overriden Methods
/// <summary>
/// Find method which allows for searching for all packages from a repository and returns latest version for each.
/// </summary>
public override FindResults FindAll(bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindAll()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find all is not supported for the ContainerRegistry server protocol repository '{Repository.Name}'"),
"FindAllFailure",
ErrorCategory.InvalidOperation,
this);
return emptyResponseResults;
}
/// <summary>
/// Find method which allows for searching for packages with tag from a repository and returns latest version for each.
/// </summary>
public override FindResults FindTags(string[] tags, bool includePrerelease, ResourceType _type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindTags()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find tags is not supported for the ContainerRegistry server protocol repository '{Repository.Name}'"),
"FindTagsFailure",
ErrorCategory.InvalidOperation,
this);
return emptyResponseResults;
}
/// <summary>
/// Find method which allows for searching for all packages that have specified Command or DSCResource name.
/// </summary>
public override FindResults FindCommandOrDscResource(string[] tags, bool includePrerelease, bool isSearchingForCommands, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindCommandOrDscResource()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find Command or DSC Resource is not supported for the ContainerRegistry server protocol repository '{Repository.Name}'"),
"FindCommandOrDscResourceFailure",
ErrorCategory.InvalidOperation,
this);
return emptyResponseResults;
}
/// <summary>
/// Find method which allows for searching for single name and returns latest version.
/// Name: no wildcard support
/// Examples: Search "PowerShellGet"
/// Implementation Note: Need to filter further for latest version (prerelease or non-prerelease dependening on user preference)
/// </summary>
public override FindResults FindName(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindName()");
// for FindName(), need to consider all versions (hence VersionType.VersionRange and VersionRange.All, and no requiredVersion) but only pick latest (hence getOnlyLatest: true)
Hashtable[] pkgResult = FindPackagesWithVersionHelper(packageName, VersionType.VersionRange, versionRange: VersionRange.All, requiredVersion: null, includePrerelease, getOnlyLatest: true, out errRecord);
if (errRecord != null)
{
return emptyResponseResults;
}
return new FindResults(stringResponse: new string[] { }, hashtableResponse: pkgResult.ToArray(), responseType: containerRegistryFindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name and tag and returns latest version.
/// Name: no wildcard support
/// Examples: Search "PowerShellGet" -Tag "Provider"
/// </summary>
public override FindResults FindNameWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindNameWithTag()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find name with tag(s) is not supported for the ContainerRegistry server protocol repository '{Repository.Name}'"),
"FindNameWithTagFailure",
ErrorCategory.InvalidOperation,
this);
return emptyResponseResults;
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and returns latest version.
/// Name: supports wildcards
/// Examples: Search "PowerShell*"
/// Implementation Note: filter additionally and verify ONLY package name was a match.
/// </summary>
public override FindResults FindNameGlobbing(string packageName, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindNameGlobbing()");
errRecord = new ErrorRecord(
new InvalidOperationException($"FindNameGlobbing all is not supported for the ContainerRegistry server protocol repository '{Repository.Name}'"),
"FindNameGlobbingFailure",
ErrorCategory.InvalidOperation,
this);
return emptyResponseResults;
}
/// <summary>
/// Find method which allows for searching for single name with wildcards and tag and returns latest version.
/// Name: supports wildcards
/// Examples: Search "PowerShell*" -Tag "Provider"
/// Implementation Note: filter additionally and verify ONLY package name was a match.
/// </summary>
public override FindResults FindNameGlobbingWithTag(string packageName, string[] tags, bool includePrerelease, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindNameGlobbingWithTag()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find name globbing with tag(s) is not supported for the ContainerRegistry server protocol repository '{Repository.Name}'"),
"FindNameGlobbingWithTagFailure",
ErrorCategory.InvalidOperation,
this);
return emptyResponseResults;
}
/// <summary>
/// Find method which allows for searching for single name with version range.
/// Name: no wildcard support
/// Version: supports wildcards
/// Examples: Search "PowerShellGet" "[3.0.0.0, 5.0.0.0]"
/// Search "PowerShellGet" "3.*"
/// Implementation note: Returns all versions, including prerelease ones. Later (in the API client side) we'll do filtering on the versions to satisfy what user provided.
/// </summary>
public override FindResults FindVersionGlobbing(string packageName, VersionRange versionRange, bool includePrerelease, ResourceType type, bool getOnlyLatest, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindVersionGlobbing()");
// for FindVersionGlobbing(), need to consider all versions that match version range criteria (hence VersionType.VersionRange and no requiredVersion)
Hashtable[] pkgResults = FindPackagesWithVersionHelper(packageName, VersionType.VersionRange, versionRange: versionRange, requiredVersion: null, includePrerelease, getOnlyLatest: false, out errRecord);
if (errRecord != null)
{
return emptyResponseResults;
}
return new FindResults(stringResponse: new string[] { }, hashtableResponse: pkgResults.ToArray(), responseType: containerRegistryFindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with specific version.
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "PowerShellGet" "2.2.5"
/// </summary>
public override FindResults FindVersion(string packageName, string version, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindVersion()");
if (!NuGetVersion.TryParse(version, out NuGetVersion requiredVersion))
{
errRecord = new ErrorRecord(
new ArgumentException($"Version {version} to be found is not a valid NuGet version."),
"FindNameFailure",
ErrorCategory.InvalidArgument,
this);
return emptyResponseResults;
}
_cmdletPassedIn.WriteDebug($"'{packageName}' version parsed as '{requiredVersion}'");
bool includePrereleaseVersions = requiredVersion.IsPrerelease;
// for FindVersion(), need to consider the specific required version (hence VersionType.SpecificVersion and no version range)
Hashtable[] pkgResult = FindPackagesWithVersionHelper(packageName, VersionType.SpecificVersion, versionRange: VersionRange.None, requiredVersion: requiredVersion, includePrereleaseVersions, getOnlyLatest: false, out errRecord);
if (errRecord != null)
{
return emptyResponseResults;
}
return new FindResults(stringResponse: new string[] { }, hashtableResponse: pkgResult.ToArray(), responseType: containerRegistryFindResponseType);
}
/// <summary>
/// Find method which allows for searching for single name with specific version and tag.
/// Name: no wildcard support
/// Version: no wildcard support
/// Examples: Search "PowerShellGet" "2.2.5" -Tag "Provider"
/// </summary>
public override FindResults FindVersionWithTag(string packageName, string version, string[] tags, ResourceType type, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindVersionWithTag()");
errRecord = new ErrorRecord(
new InvalidOperationException($"Find version with tag(s) is not supported for the ContainerRegistry server protocol repository '{Repository.Name}'"),
"FindVersionWithTagFailure",
ErrorCategory.InvalidOperation,
this);
return emptyResponseResults;
}
/** INSTALL APIS **/
/// <summary>
/// Installs a specific package.
/// User may request to install package with or without providing version (as seen in examples below), but prior to calling this method the package is located and package version determined.
/// Therefore, package version should not be null in this method.
/// Name: no wildcard support.
/// Examples: Install "PowerShellGet" -Version "3.5.0-alpha"
/// Install "PowerShellGet" -Version "3.0.0"
/// </summary>
public override Stream InstallPackage(string packageName, string packageVersion, bool includePrerelease, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::InstallPackage()");
Stream results = new MemoryStream();
if (string.IsNullOrEmpty(packageVersion))
{
errRecord = new ErrorRecord(
exception: new ArgumentNullException($"Package version could not be found for {packageName}"),
"PackageVersionNullOrEmptyError",
ErrorCategory.InvalidArgument,
_cmdletPassedIn);
return results;
}
string packageNameForInstall = PrependMARPrefix(packageName);
results = InstallVersion(packageNameForInstall, packageVersion, out errRecord);
return results;
}
/// <summary>
/// Installs a package with version specified.
/// Version can be prerelease or stable.
/// </summary>
private Stream InstallVersion(
string packageName,
string packageVersion,
out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::InstallVersion()");
errRecord = null;
string packageNameLowercase = packageName.ToLower();
string accessToken = string.Empty;
string tenantID = string.Empty;
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
try
{
Directory.CreateDirectory(tempPath);
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"InstallVersionTempDirCreationError",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
return null;
}
string containerRegistryAccessToken = GetContainerRegistryAccessToken(out errRecord);
if (errRecord != null)
{
return null;
}
_cmdletPassedIn.WriteVerbose($"Getting manifest for {packageNameLowercase} - {packageVersion}");
var manifest = GetContainerRegistryRepositoryManifest(packageNameLowercase, packageVersion, containerRegistryAccessToken, out errRecord);
if (errRecord != null)
{
return null;
}
string digest = GetDigestFromManifest(manifest, out errRecord);
if (errRecord != null)
{
return null;
}
_cmdletPassedIn.WriteVerbose($"Downloading blob for {packageNameLowercase} - {packageVersion}");
HttpContent responseContent;
try
{
responseContent = GetContainerRegistryBlobAsync(packageNameLowercase, digest, containerRegistryAccessToken).Result;
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"InstallVersionGetContainerRegistryBlobAsyncError",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
return null;
}
return responseContent.ReadAsStreamAsync().Result;
}
#endregion
#region Authentication and Token Methods
/// <summary>
/// Gets the access token for the container registry by following the below logic:
/// If a credential is provided when registering the repository, retrieve the token from SecretsManagement.
/// If no credential provided at registration then, check if the ACR endpoint can be accessed without a token. If not, try using Azure.Identity to get the az access token, then ACR refresh token and then ACR access token.
/// Note: Access token can be empty if the repository is unauthenticated
/// </summary>
internal string GetContainerRegistryAccessToken(out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryAccessToken()");
string accessToken = string.Empty;
string containerRegistryAccessToken = string.Empty;
string tenantID = string.Empty;
errRecord = null;
var repositoryCredentialInfo = Repository.CredentialInfo;
if (repositoryCredentialInfo != null)
{
accessToken = Utils.GetContainerRegistryAccessTokenFromSecretManagement(
Repository.Name,
repositoryCredentialInfo,
_cmdletPassedIn);
_cmdletPassedIn.WriteVerbose("Access token retrieved.");
tenantID = repositoryCredentialInfo.SecretName;
}
else
{
bool isRepositoryUnauthenticated = IsContainerRegistryUnauthenticated(Repository.Uri.ToString(), out errRecord);
if (errRecord != null)
{
return null;
}
if (!isRepositoryUnauthenticated)
{
accessToken = Utils.GetAzAccessToken();
if (string.IsNullOrEmpty(accessToken))
{
errRecord = new ErrorRecord(
new InvalidOperationException("Failed to get access token from Azure."),
"AzAccessTokenFailure",
ErrorCategory.AuthenticationError,
this);
return null;
}
}
else
{
_cmdletPassedIn.WriteVerbose("Repository is unauthenticated");
return null;
}
}
var containerRegistryRefreshToken = GetContainerRegistryRefreshToken(tenantID, accessToken, out errRecord);
if (errRecord != null)
{
return null;
}
containerRegistryAccessToken = GetContainerRegistryAccessTokenByRefreshToken(containerRegistryRefreshToken, out errRecord);
if (errRecord != null)
{
return null;
}
return containerRegistryAccessToken;
}
/// <summary>
/// Checks if container registry repository is unauthenticated.
/// </summary>
internal bool IsContainerRegistryUnauthenticated(string containerRegistyUrl, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::IsContainerRegistryUnauthenticated()");
errRecord = null;
string endpoint = $"{containerRegistyUrl}/v2/";
HttpResponseMessage response;
try
{
response = _sessionClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, endpoint)).Result;
}
catch (Exception e)
{
errRecord = new ErrorRecord(
e,
"RegistryUnauthenticationCheckError",
ErrorCategory.InvalidResult,
this);
return false;
}
return (response.StatusCode == HttpStatusCode.OK);
}
/// <summary>
/// Given the access token retrieved from credentials, gets the refresh token.
/// </summary>
internal string GetContainerRegistryRefreshToken(string tenant, string accessToken, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryRefreshToken()");
string content = string.Format(containerRegistryRefreshTokenTemplate, Registry, tenant, accessToken);
var contentHeaders = new Collection<KeyValuePair<string, string>> { new KeyValuePair<string, string>("Content-Type", "application/x-www-form-urlencoded") };
string exchangeUrl = string.Format(containerRegistryOAuthExchangeUrlTemplate, Registry);
var results = GetHttpResponseJObjectUsingContentHeaders(exchangeUrl, HttpMethod.Post, content, contentHeaders, out errRecord);
if (errRecord != null || results == null || results["refresh_token"] == null)
{
return string.Empty;
}
return results["refresh_token"].ToString();
}
/// <summary>
/// Given the refresh token, gets the new access token with appropriate scope access permissions.
/// </summary>
internal string GetContainerRegistryAccessTokenByRefreshToken(string refreshToken, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryAccessTokenByRefreshToken()");
string content = string.Format(containerRegistryAccessTokenTemplate, Registry, refreshToken);
var contentHeaders = new Collection<KeyValuePair<string, string>> { new KeyValuePair<string, string>("Content-Type", "application/x-www-form-urlencoded") };
string tokenUrl = string.Format(containerRegistryOAuthTokenUrlTemplate, Registry);
var results = GetHttpResponseJObjectUsingContentHeaders(tokenUrl, HttpMethod.Post, content, contentHeaders, out errRecord);
if (errRecord != null || results == null || results["access_token"] == null)
{
return string.Empty;
}
return results["access_token"].ToString();
}
#endregion
#region Private Methods
/// <summary>
/// Parses package manifest JObject to find digest entry, which is the SHA needed to identify and get the package.
/// </summary>
private string GetDigestFromManifest(JObject manifest, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetDigestFromManifest()");
errRecord = null;
string digest = String.Empty;
if (manifest == null)
{
errRecord = new ErrorRecord(
exception: new ArgumentNullException("Manifest (passed in to determine digest) is null."),
"ManifestNullError",
ErrorCategory.InvalidArgument,
_cmdletPassedIn);
return digest;
}
JToken layers = manifest["layers"];
if (layers == null || !layers.HasValues)
{
errRecord = new ErrorRecord(
exception: new ArgumentNullException("Manifest 'layers' property (passed in to determine digest) is null or does not have values."),
"ManifestLayersNullOrEmptyError",
ErrorCategory.InvalidArgument,
_cmdletPassedIn);
return digest;
}
foreach (JObject item in layers)
{
if (item.ContainsKey("digest"))
{
digest = item.GetValue("digest").ToString();
break;
}
}
return digest;
}
/// <summary>
/// Gets the manifest for a package (ie repository in container registry terms) from the repository (ie registry in container registry terms)
/// </summary>
internal JObject GetContainerRegistryRepositoryManifest(string packageName, string version, string containerRegistryAccessToken, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryRepositoryManifest()");
// example of manifestUrl: https://psgetregistry.azurecr.io/hello-world:3.0.0
string manifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, version);
var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken);
return GetHttpResponseJObjectUsingDefaultHeaders(manifestUrl, HttpMethod.Get, defaultHeaders, out errRecord);
}
/// <summary>
/// Get the blob for the package (ie repository in container registry terms) from the repositroy (ie registry in container registry terms)
/// Used when installing the package
/// </summary>
internal async Task<HttpContent> GetContainerRegistryBlobAsync(string packageName, string digest, string containerRegistryAccessToken)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryBlobAsync()");
string blobUrl = string.Format(containerRegistryBlobDownloadUrlTemplate, Registry, packageName, digest);
var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken);
return await GetHttpContentResponseJObject(blobUrl, defaultHeaders);
}
/// <summary>
/// Gets the image tags associated with the package (i.e repository in container registry terms), where the tag corresponds to the package's versions.
/// If the package version is specified search for that specific tag for the image, if the package version is "*" search for all tags for the image.
/// </summary>
internal JObject FindContainerRegistryImageTags(string packageName, string version, string containerRegistryAccessToken, out ErrorRecord errRecord)
{
/*
{
"name": "<name>",
"tags": [
"<tag1>",
"<tag2>",
"<tag3>"
]
}
*/
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindContainerRegistryImageTags()");
string resolvedVersion = string.Equals(version, "*", StringComparison.OrdinalIgnoreCase) ? null : $"/{version}";
string findImageUrl = string.Format(containerRegistryFindImageVersionUrlTemplate, Registry, packageName);
var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken);
return GetHttpResponseJObjectUsingDefaultHeaders(findImageUrl, HttpMethod.Get, defaultHeaders, out errRecord);
}
/// <summary>
/// Get metadata for a package version.
/// </summary>
internal Hashtable GetContainerRegistryMetadata(string packageName, string exactTagVersion, string containerRegistryAccessToken, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetContainerRegistryMetadata()");
Hashtable requiredVersionResponse = new Hashtable();
var foundTags = FindContainerRegistryManifest(packageName, exactTagVersion, containerRegistryAccessToken, out errRecord);
if (errRecord != null)
{
return requiredVersionResponse;
}
/* Response returned looks something like:
* {
* "schemaVersion": 2,
* "config": {
* "mediaType": "application/vnd.unknown.config.v1+json",
* "digest": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
* "size": 0
* },
* "layers": [
* {
* "mediaType": "application/vnd.oci.image.layer.nondistributable.v1.tar+gzip'",
* "digest": "sha256:7c55c7b66cb075628660d8249cc4866f16e34741c246a42ed97fb23ccd4ea956",
* "size": 3533,
* "annotations": {
* "org.opencontainers.image.title": "test_module.1.0.0.nupkg",
* "metadata": "{\"GUID\":\"45219bf4-10a4-4242-92d6-9bfcf79878fd\",\"FunctionsToExport\":[],\"CompanyName\":\"Anam\",\"CmdletsToExport\":[],\"VariablesToExport\":\"*\",\"Author\":\"Anam Navied\",\"ModuleVersion\":\"1.0.0\",\"Copyright\":\"(c) Anam Navied. All rights reserved.\",\"PrivateData\":{\"PSData\":{\"Tags\":[\"Test\",\"CommandsAndResource\",\"Tag2\"]}},\"RequiredModules\":[],\"Description\":\"This is a test module, for PSGallery team internal testing. Do not take a dependency on this package. This version contains tags for the package.\",\"AliasesToExport\":[]}"
* }
* }
* ]
* }
*/
var serverPkgInfo = GetMetadataProperty(foundTags, packageName, out errRecord);
if (errRecord != null)
{
return requiredVersionResponse;
}
try
{
using (JsonDocument metadataJSONDoc = JsonDocument.Parse(serverPkgInfo.Metadata))
{
string pkgVersionString = String.Empty;
JsonElement rootDom = metadataJSONDoc.RootElement;
if (rootDom.TryGetProperty("ModuleVersion", out JsonElement pkgVersionElement))
{
// module metadata will have "ModuleVersion" property
pkgVersionString = pkgVersionElement.ToString();
if (rootDom.TryGetProperty("PrivateData", out JsonElement pkgPrivateDataElement) && pkgPrivateDataElement.TryGetProperty("PSData", out JsonElement pkgPSDataElement)
&& pkgPSDataElement.TryGetProperty("Prerelease", out JsonElement pkgPrereleaseLabelElement) && !String.IsNullOrEmpty(pkgPrereleaseLabelElement.ToString().Trim()))
{
pkgVersionString += $"-{pkgPrereleaseLabelElement.ToString()}";
}
}
else if (rootDom.TryGetProperty("Version", out pkgVersionElement) || rootDom.TryGetProperty("version", out pkgVersionElement))
{
// script metadata will have "Version" property, but nupkg only based .nuspec will have lowercase "version" property and JsonElement.TryGetProperty() is case sensitive
pkgVersionString = pkgVersionElement.ToString();
}
else
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain 'ModuleVersion' or 'Version' property in metadata for package '{packageName}' in '{Repository.Name}'."),
"ParseMetadataFailure",
ErrorCategory.InvalidResult,
this);
return requiredVersionResponse;
}
if (!NuGetVersion.TryParse(pkgVersionString, out NuGetVersion pkgVersion))
{
errRecord = new ErrorRecord(
new ArgumentException($"Version {pkgVersionString} to be parsed from metadata is not a valid NuGet version."),
"ParseMetadataFailure",
ErrorCategory.InvalidArgument,
this);
return requiredVersionResponse;
}
if (!NuGetVersion.TryParse(exactTagVersion, out NuGetVersion requiredVersion))
{
errRecord = new ErrorRecord(
new ArgumentException($"Version {exactTagVersion} to be parsed from method input is not a valid NuGet version."),
"ParseMetadataFailure",
ErrorCategory.InvalidArgument,
this);
return requiredVersionResponse;
}
_cmdletPassedIn.WriteDebug($"'{packageName}' version parsed as '{pkgVersion}'");
if (pkgVersion.ToNormalizedString() == requiredVersion.ToNormalizedString())
{
requiredVersionResponse = serverPkgInfo.ToHashtable();
}
}
}
catch (Exception e)
{
errRecord = new ErrorRecord(
new ArgumentException($"Error parsing server metadata: {e.Message}"),
"ParseMetadataFailure",
ErrorCategory.InvalidData,
this);
return requiredVersionResponse;
}
return requiredVersionResponse;
}
/// <summary>
/// Get the manifest associated with the package version.
/// </summary>
internal JObject FindContainerRegistryManifest(string packageName, string version, string containerRegistryAccessToken, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::FindContainerRegistryManifest()");
var createManifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, version);
_cmdletPassedIn.WriteDebug($"GET manifest url: {createManifestUrl}");
var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken);
return GetHttpResponseJObjectUsingDefaultHeaders(createManifestUrl, HttpMethod.Get, defaultHeaders, out errRecord);
}
/// <summary>
/// Get metadata for the package by parsing its manifest.
/// </summary>
internal ContainerRegistryInfo GetMetadataProperty(JObject foundTags, string packageName, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetMetadataProperty()");
errRecord = null;
ContainerRegistryInfo serverPkgInfo = null;
var layers = foundTags["layers"];
if (layers == null || layers[0] == null)
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain 'layers' element in manifest for package '{packageName}' in '{Repository.Name}'."),
"GetMetadataPropertyLayersError",
ErrorCategory.InvalidData,
this);
return serverPkgInfo;
}
var annotations = layers[0]["annotations"];
if (annotations == null)
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain 'annotations' element in manifest for package '{packageName}' in '{Repository.Name}'."),
"GetMetadataPropertyAnnotationsError",
ErrorCategory.InvalidData,
this);
return serverPkgInfo;
}
// Check for package name
var pkgTitleJToken = annotations["org.opencontainers.image.title"];
if (pkgTitleJToken == null)
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain 'org.opencontainers.image.title' element for package '{packageName}' in '{Repository.Name}'."),
"GetMetadataPropertyOCITitleError",
ErrorCategory.InvalidData,
this);
return serverPkgInfo;
}
string metadataPkgName = pkgTitleJToken.ToString();
if (string.IsNullOrWhiteSpace(metadataPkgName))
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response element 'org.opencontainers.image.title' is empty for package '{packageName}' in '{Repository.Name}'."),
"GetMetadataPropertyOCITitleEmptyError",
ErrorCategory.InvalidData,
this);
return serverPkgInfo;
}
// Check for package metadata
var pkgMetadataJToken = annotations["metadata"];
if (pkgMetadataJToken == null)
{
errRecord = new ErrorRecord(
new InvalidOrEmptyResponse($"Response does not contain 'metadata' element in manifest for package '{packageName}' in '{Repository.Name}'."),
"GetMetadataPropertyMetadataError",
ErrorCategory.InvalidData,
this);
return serverPkgInfo;
}
var metadata = pkgMetadataJToken.ToString();
// Check for package artifact type
var resourceTypeJToken = annotations["resourceType"];
var resourceType = resourceTypeJToken != null ? resourceTypeJToken.ToString() : "None";
return new ContainerRegistryInfo(metadataPkgName, metadata, resourceType);
}
/// <summary>
/// Upload manifest for the package, used for publishing.
/// </summary>
internal async Task<HttpResponseMessage> UploadManifest(string packageName, string packageVersion, string configPath, bool isManifest, string containerRegistryAccessToken)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::UploadManifest()");
try
{
var createManifestUrl = string.Format(containerRegistryManifestUrlTemplate, Registry, packageName, packageVersion);
var defaultHeaders = GetDefaultHeaders(containerRegistryAccessToken);
return await PutRequestAsync(createManifestUrl, configPath, isManifest, defaultHeaders);
}
catch (HttpRequestException e)
{
throw new HttpRequestException("Error occured while trying to create manifest: " + e.Message);
}
}
internal async Task<HttpContent> GetHttpContentResponseJObject(string url, Collection<KeyValuePair<string, string>> defaultHeaders)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetHttpContentResponseJObject()");
try
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url);
SetDefaultHeaders(defaultHeaders);
return await SendContentRequestAsync(request);
}
catch (HttpRequestException e)
{
throw new HttpRequestException("Error occured while trying to retrieve response: " + e.Message);
}
}
/// <summary>
/// Get response object when using default headers in the request.
/// </summary>
internal JObject GetHttpResponseJObjectUsingDefaultHeaders(string url, HttpMethod method, Collection<KeyValuePair<string, string>> defaultHeaders, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetHttpResponseJObjectUsingDefaultHeaders()");
try
{
errRecord = null;
HttpRequestMessage request = new HttpRequestMessage(method, url);
SetDefaultHeaders(defaultHeaders);
return SendRequestAsync(request).GetAwaiter().GetResult();
}
catch (ResourceNotFoundException e)
{
errRecord = new ErrorRecord(
exception: e,
"ResourceNotFound",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
catch (UnauthorizedException e)
{
errRecord = new ErrorRecord(
exception: e,
"UnauthorizedRequest",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
catch (HttpRequestException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestCallFailure",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestCallFailure",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
return null;
}
/// <summary>
/// Get response object when using content headers in the request.
/// </summary>
internal JObject GetHttpResponseJObjectUsingContentHeaders(string url, HttpMethod method, string content, Collection<KeyValuePair<string, string>> contentHeaders, out ErrorRecord errRecord)
{
_cmdletPassedIn.WriteDebug("In ContainerRegistryServerAPICalls::GetHttpResponseJObjectUsingContentHeaders()");
errRecord = null;
try
{
HttpRequestMessage request = new HttpRequestMessage(method, url);
if (string.IsNullOrEmpty(content))
{
errRecord = new ErrorRecord(
exception: new ArgumentNullException($"Content is null or empty and cannot be used to make a request as its content headers."),
"RequestContentHeadersNullOrEmpty",
ErrorCategory.InvalidData,
_cmdletPassedIn);
return null;
}
request.Content = new StringContent(content);
request.Content.Headers.Clear();
if (contentHeaders != null)
{
foreach (var header in contentHeaders)
{
request.Content.Headers.Add(header.Key, header.Value);
}
}
return SendRequestAsync(request).GetAwaiter().GetResult();
}
catch (ResourceNotFoundException e)
{
errRecord = new ErrorRecord(
exception: e,
"ResourceNotFound",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
catch (UnauthorizedException e)
{
errRecord = new ErrorRecord(
exception: e,
"UnauthorizedRequest",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
catch (HttpRequestException e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestCallFailure",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
catch (Exception e)
{
errRecord = new ErrorRecord(
exception: e,
"HttpRequestCallFailure",
ErrorCategory.InvalidResult,
_cmdletPassedIn);
}
return null;
}
/// <summary>
/// Get response headers.
/// </summary>
internal async Task<HttpResponseHeaders> GetHttpResponseHeader(string url, HttpMethod method, Collection<KeyValuePair<string, string>> defaultHeaders)
{
try
{
HttpRequestMessage request = new HttpRequestMessage(method, url);
SetDefaultHeaders(defaultHeaders);
return await SendRequestHeaderAsync(request);
}
catch (HttpRequestException e)
{
throw new HttpRequestException("Error occured while trying to retrieve response header: " + e.Message);
}
}
/// <summary>
/// Set default headers for HttpClient.
/// </summary>
private void SetDefaultHeaders(Collection<KeyValuePair<string, string>> defaultHeaders)
{
_sessionClient.DefaultRequestHeaders.Clear();
if (defaultHeaders != null)
{
foreach (var header in defaultHeaders)
{
if (string.Equals(header.Key, "Authorization", StringComparison.OrdinalIgnoreCase))
{
_sessionClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", header.Value);
}
else if (string.Equals(header.Key, "Accept", StringComparison.OrdinalIgnoreCase))
{
_sessionClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(header.Value));
}
else
{
_sessionClient.DefaultRequestHeaders.Add(header.Key, header.Value);
}
}
}
}
/// <summary>