forked from oras-project/oras-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRepositoryTest.cs
More file actions
4635 lines (4237 loc) · 184 KB
/
Copy pathRepositoryTest.cs
File metadata and controls
4635 lines (4237 loc) · 184 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 The ORAS Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using OrasProject.Oras.Content;
using OrasProject.Oras.Exceptions;
using OrasProject.Oras.Oci;
using OrasProject.Oras.Registry;
using OrasProject.Oras.Registry.Remote;
using OrasProject.Oras.Registry.Remote.Exceptions;
using System.Diagnostics;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Xunit;
using Xunit.Abstractions;
using static OrasProject.Oras.Content.Digest;
using static OrasProject.Oras.Tests.Remote.Util.Util;
using static OrasProject.Oras.Tests.Remote.Util.RandomDataGenerator;
using JsonSerializer = System.Text.Json.JsonSerializer;
namespace OrasProject.Oras.Tests.Registry.Remote;
public class RepositoryTest(ITestOutputHelper iTestOutputHelper)
{
public struct TestIoStruct
{
public bool IsTag;
public bool ErrExpectedOnHead;
public string ServerCalculatedDigest;
public string ClientSuppliedReference;
public bool ErrExpectedOnGet;
}
private readonly ITestOutputHelper _iTestOutputHelper = iTestOutputHelper;
private readonly byte[] _theAmazingBanClan = "Ban Gu, Ban Chao, Ban Zhao"u8.ToArray();
private const string _theAmazingBanDigest = "b526a4f2be963a2f9b0990c001255669eab8a254ab1a6e3f84f1820212ac7078";
private const string _dockerContentDigestHeader = "Docker-Content-Digest";
private const string _contentTypeHeader = "Content-Type";
private const string _headerOciFiltersApplied = "OCI-Filters-Applied";
// The following truth table aims to cover the expected GET/HEAD request outcome
// for all possible permutations of the client/server "containing a digest", for
// both Manifests and Blobs. Where the results between the two differ, the index
// of the first column has an exclamation mark.
//
// The client is said to "contain a digest" if the user-supplied reference string
// is of the form that contains a digest rather than a tag. The server, on the
// other hand, is said to "contain a digest" if the server responded with the
// special header `Docker-Content-Digest`.
//
// In this table, anything denoted with an asterisk indicates that the true
// response should actually be the opposite of what's expected; for example,
// `*PASS` means we will get a `PASS`, even though the true answer would be its
// diametric opposite--a `FAIL`. This may seem odd, and deserves an explanation.
// This function has blind-spots, and while it can expend power to gain sight,
// i.e., perform the expensive validation, we chose not to. The reason is two-
// fold: a) we "know" that even if we say "!PASS", it will eventually fail later
// when checks are performed, and with that assumption, we have the luxury for
// the second point, which is b) performance.
//
// _______________________________________________________________________________________________________________
// | ID | CLIENT | SERVER | Manifest.GET | Blob.GET | Manifest.HEAD | Blob.HEAD |
// |----+-----------------+------------------+-----------------------+-----------+---------------------+-----------+
// | 1 | tag | missing | CALCULATE,PASS | n/a | FAIL | n/a |
// | 2 | tag | presentCorrect | TRUST,PASS | n/a | TRUST,PASS | n/a |
// | 3 | tag | presentIncorrect | TRUST,*PASS | n/a | TRUST,*PASS | n/a |
// | 4 | correctDigest | missing | TRUST,PASS | PASS | TRUST,PASS | PASS |
// | 5 | correctDigest | presentCorrect | TRUST,COMPARE,PASS | PASS | TRUST,COMPARE,PASS | PASS |
// | 6 | correctDigest | presentIncorrect | TRUST,COMPARE,FAIL | FAIL | TRUST,COMPARE,FAIL | FAIL |
// ---------------------------------------------------------------------------------------------------------------
/// <summary>
/// GetTestIOStructMapForGetDescriptorClass returns a map of test cases for different
/// GET/HEAD request outcome for all possible permutations of the client/server "containing a digest", for
/// both Manifests and Blobs.
/// </summary>
/// <returns></returns>
public static Dictionary<string, TestIoStruct> GetTestIOStructMapForGetDescriptorClass()
{
string correctDigest = $"sha256:{_theAmazingBanDigest}";
string incorrectDigest = $"sha256:ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
return new Dictionary<string, TestIoStruct>
{
["1. Client:Tag & Server:DigestMissing"] = new TestIoStruct
{
IsTag = true,
ErrExpectedOnHead = true
},
["2. Client:Tag & Server:DigestValid"] = new TestIoStruct
{
IsTag = true,
ServerCalculatedDigest = correctDigest
},
["3. Client:Tag & Server:DigestWrongButSyntacticallyValid"] = new TestIoStruct
{
IsTag = true,
ServerCalculatedDigest = incorrectDigest
},
["4. Client:DigestValid & Server:DigestMissing"] = new TestIoStruct
{
ClientSuppliedReference = correctDigest
},
["5. Client:DigestValid & Server:DigestValid"] = new TestIoStruct
{
ClientSuppliedReference = correctDigest,
ServerCalculatedDigest = correctDigest
},
["6. Client:DigestValid & Server:DigestWrongButSyntacticallyValid"] = new TestIoStruct
{
ClientSuppliedReference = correctDigest,
ServerCalculatedDigest = incorrectDigest,
ErrExpectedOnHead = true,
ErrExpectedOnGet = true
}
};
}
/// <summary>
/// Repository_FetchAsync tests the FetchAsync method of the Repository.
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_FetchAsync()
{
var blob = Encoding.UTF8.GetBytes("hello world");
var blobDesc = new Descriptor()
{
Digest = ComputeSha256(blob),
MediaType = "test",
Size = (uint)blob.Length
};
var index = """{"manifests":[]}"""u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var resp = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Get)
{
Debug.WriteLine("Expected GET request");
resp.StatusCode = HttpStatusCode.BadRequest;
return resp;
}
var path = req.RequestUri!.AbsolutePath;
if (path == "/v2/test/blobs/" + blobDesc.Digest)
{
resp.Content = new ByteArrayContent(blob);
resp.Content.Headers.Add("Content-Type", "application/octet-stream");
resp.Headers.Add(_dockerContentDigestHeader, blobDesc.Digest);
return resp;
}
if (path == "/v2/test/manifests/" + indexDesc.Digest)
{
if (!req.Headers.Accept.Contains(new MediaTypeWithQualityHeaderValue(MediaType.ImageIndex)))
{
resp.StatusCode = HttpStatusCode.BadRequest;
Debug.WriteLine("manifest not convertable: " + req.Headers.Accept);
return resp;
}
resp.Content = new ByteArrayContent(index);
resp.Content.Headers.Add("Content-Type", indexDesc.MediaType);
resp.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
return resp;
}
resp.StatusCode = HttpStatusCode.NotFound;
return resp;
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
var stream = await repo.FetchAsync(blobDesc, cancellationToken);
var buf = new byte[stream.Length];
await stream.ReadExactlyAsync(buf, cancellationToken);
Assert.Equal(blob, buf);
stream = await repo.FetchAsync(indexDesc, cancellationToken);
buf = new byte[stream.Length];
await stream.ReadExactlyAsync(buf, cancellationToken);
Assert.Equal(index, buf);
}
/// <summary>
/// Repository_PushAsync tests the PushAsync method of the Repository
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_PushAsync()
{
var blob = @"hello world"u8.ToArray();
var blobDesc = new Descriptor()
{
Digest = ComputeSha256(blob),
MediaType = "test",
Size = (uint)blob.Length
};
var index = @"{""manifests"":[]}"u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
var uuid = Guid.NewGuid().ToString();
var gotBlob = new byte[blobDesc.Size];
var gotIndex = new byte[indexDesc.Size];
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var resp = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method == HttpMethod.Post && req.RequestUri!.AbsolutePath == "/v2/test/blobs/uploads/")
{
resp.Headers.Location = new Uri("http://localhost:5000/v2/test/blobs/uploads/" + uuid);
resp.StatusCode = HttpStatusCode.Accepted;
return resp;
}
if (req.Method == HttpMethod.Put &&
req.RequestUri!.AbsolutePath == "/v2/test/blobs/uploads/" + uuid)
{
if (req.Headers.TryGetValues("Content-Type", out var values) &&
!values.Contains("application/octet-stream"))
{
resp.StatusCode = HttpStatusCode.BadRequest;
return resp;
}
var queries = HttpUtility.ParseQueryString(req.RequestUri.Query);
if (queries["digest"] != blobDesc.Digest)
{
resp.StatusCode = HttpStatusCode.BadRequest;
return resp;
}
var stream = req.Content!.ReadAsStream(cancellationToken);
stream.ReadExactly(gotBlob);
resp.Headers.Add(_dockerContentDigestHeader, blobDesc.Digest);
resp.StatusCode = HttpStatusCode.Created;
return resp;
}
if (req.Method == HttpMethod.Put &&
req.RequestUri!.AbsolutePath == "/v2/test/manifests/" + indexDesc.Digest)
{
if (req.Headers.TryGetValues("Content-Type", out var values) &&
!values.Contains(MediaType.ImageIndex))
{
resp.StatusCode = HttpStatusCode.BadRequest;
return resp;
}
var stream = req.Content!.ReadAsStream(cancellationToken);
stream.ReadExactly(gotIndex);
resp.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
resp.StatusCode = HttpStatusCode.Created;
return resp;
}
resp.StatusCode = HttpStatusCode.Forbidden;
return resp;
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
await repo.PushAsync(blobDesc, new MemoryStream(blob), cancellationToken);
Assert.Equal(blob, gotBlob);
await repo.PushAsync(indexDesc, new MemoryStream(index), cancellationToken);
Assert.Equal(index, gotIndex);
}
/// <summary>
/// Repository_ExistsAsync tests the ExistsAsync method of the Repository
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_ExistsAsync()
{
var blob = @"hello world"u8.ToArray();
var blobDesc = new Descriptor()
{
Digest = ComputeSha256(blob),
MediaType = "test",
Size = (uint)blob.Length
};
var index = @"{""manifests"":[]}"u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Head)
{
return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
}
if (req.RequestUri!.AbsolutePath == "/v2/test/blobs/" + blobDesc.Digest)
{
res.Content.Headers.Add("Content-Type", "application/octet-stream");
res.Content.Headers.Add("Content-Length", blobDesc.Size.ToString());
res.Headers.Add(_dockerContentDigestHeader, blobDesc.Digest);
return res;
}
if (req.RequestUri!.AbsolutePath == "/v2/test/manifests/" + indexDesc.Digest)
{
if (req.Headers.TryGetValues("Accept", out var values) &&
!values.Contains(MediaType.ImageIndex))
{
return new HttpResponseMessage(HttpStatusCode.NotAcceptable);
}
res.Content.Headers.Add("Content-Type", indexDesc.MediaType);
res.Content.Headers.Add("Content-Length", indexDesc.Size.ToString());
res.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
return res;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
var exists = await repo.ExistsAsync(blobDesc, cancellationToken);
Assert.True(exists);
exists = await repo.ExistsAsync(indexDesc, cancellationToken);
Assert.True(exists);
}
/// <summary>
/// Repository_DeleteAsync tests the DeleteAsync method of the Repository
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_DeleteAsync()
{
var blob = @"hello world"u8.ToArray();
var blobDesc = new Descriptor()
{
Digest = ComputeSha256(blob),
MediaType = "test",
Size = (uint)blob.Length
};
var blobDeleted = false;
var index = @"{""manifests"":[]}"u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
var indexDeleted = false;
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Delete && req.Method != HttpMethod.Get)
{
return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
}
if (req.Method == HttpMethod.Delete && req.RequestUri!.AbsolutePath == "/v2/test/blobs/" + blobDesc.Digest)
{
blobDeleted = true;
res.Headers.Add(_dockerContentDigestHeader, blobDesc.Digest);
res.StatusCode = HttpStatusCode.Accepted;
return res;
}
if (req.Method == HttpMethod.Delete && req.RequestUri!.AbsolutePath == "/v2/test/manifests/" + indexDesc.Digest)
{
indexDeleted = true;
// no dockerContentDigestHeader header for manifest deletion
res.StatusCode = HttpStatusCode.Accepted;
return res;
}
if (req.Method == HttpMethod.Get && req.RequestUri?.AbsolutePath == $"/v2/test/manifests/{indexDesc.Digest}")
{
if (req.Headers.TryGetValues("Accept", out IEnumerable<string>? values) && !values.Contains(MediaType.ImageIndex))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
res.Content = new ByteArrayContent(index);
res.Headers.Add(_dockerContentDigestHeader, [indexDesc.Digest]);
res.Content.Headers.Add("Content-Type", [MediaType.ImageIndex]);
return res;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
await repo.DeleteAsync(blobDesc, cancellationToken);
Assert.True(blobDeleted);
await repo.DeleteAsync(indexDesc, cancellationToken);
Assert.True(indexDeleted);
}
/// <summary>
/// Repository_ResolveAsync tests the ResolveAsync method of the Repository
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_ResolveAsync()
{
var blob = @"hello world"u8.ToArray();
var blobDesc = new Descriptor()
{
Digest = ComputeSha256(blob),
MediaType = "test",
Size = (uint)blob.Length
};
var index = @"{""manifests"":[]}"u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
var reference = "foobar";
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Head)
{
return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
}
if (req.RequestUri!.AbsolutePath == "/v2/test/manifests/" + blobDesc.Digest)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
if (req.RequestUri!.AbsolutePath == "/v2/test/manifests/" + indexDesc.Digest
|| req.RequestUri!.AbsolutePath == "/v2/test/manifests/" + reference)
{
if (req.Headers.TryGetValues("Accept", out var values) &&
!values.Contains(MediaType.ImageIndex))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
res.Content.Headers.Add("Content-Type", indexDesc.MediaType);
res.Content.Headers.Add("Content-Length", indexDesc.Size.ToString());
res.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
return res;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
await Assert.ThrowsAsync<NotFoundException>(async () =>
await repo.ResolveAsync(blobDesc.Digest, cancellationToken));
// await repo.ResolveAsync(blobDesc.Digest, cancellationToken);
var got = await repo.ResolveAsync(indexDesc.Digest, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, got));
got = await repo.ResolveAsync(reference, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, got));
var tagDigestRef = "whatever" + "@" + indexDesc.Digest;
got = await repo.ResolveAsync(tagDigestRef, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, got));
var fqdnRef = "localhost:5000/test" + ":" + tagDigestRef;
got = await repo.ResolveAsync(fqdnRef, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, got));
}
/// <summary>
/// Repository_ResolveAsync tests the ResolveAsync method of the Repository
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_TagAsync()
{
var blob = "hello"u8.ToArray();
var blobDesc = new Descriptor()
{
Digest = ComputeSha256(blob),
MediaType = "test",
Size = (uint)blob.Length
};
var index = @"{""manifests"":[]}"u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
byte[]? gotIndex = null;
var reference = "foobar";
async Task<HttpResponseMessage> MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method == HttpMethod.Get &&
req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + blobDesc.Digest)
{
return new HttpResponseMessage(HttpStatusCode.Found);
}
if (req.Method == HttpMethod.Get &&
req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + indexDesc.Digest)
{
if (req.Headers.TryGetValues("Accept", out var values) &&
!values.Contains(MediaType.ImageIndex))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
res.Content = new ByteArrayContent(index);
res.Content.Headers.Add("Content-Type", indexDesc.MediaType);
res.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
return res;
}
if (req.Method == HttpMethod.Put && req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + reference
|| req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + indexDesc.Digest)
{
if (req.Headers.TryGetValues("Content-Type", out var values) &&
!values.Contains(MediaType.ImageIndex))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
if (req.Content != null)
{
gotIndex = await req.Content.ReadAsByteArrayAsync(cancellationToken);
}
res.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
res.StatusCode = HttpStatusCode.Created;
return res;
}
return new HttpResponseMessage(HttpStatusCode.Forbidden);
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
await Assert.ThrowsAnyAsync<Exception>(
async () => await repo.TagAsync(blobDesc, reference, cancellationToken));
await repo.TagAsync(indexDesc, reference, cancellationToken);
Assert.Equal(index, gotIndex);
await repo.TagAsync(indexDesc, indexDesc.Digest, cancellationToken);
Assert.Equal(index, gotIndex);
}
/// <summary>
/// Repository_PushReferenceAsync tests the PushReferenceAsync method of the Repository
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_PushReferenceAsync()
{
var index = @"{""manifests"":[]}"u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
byte[]? gotIndex = null;
var reference = "foobar";
async Task<HttpResponseMessage> MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method == HttpMethod.Put && req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + reference)
{
if (req.Headers.TryGetValues("Content-Type", out var values) &&
!values.Contains(MediaType.ImageIndex))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
if (req.Content != null)
{
gotIndex = await req.Content.ReadAsByteArrayAsync(cancellationToken);
}
res.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
res.StatusCode = HttpStatusCode.Created;
return res;
}
return new HttpResponseMessage(HttpStatusCode.Forbidden);
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
var streamContent = new MemoryStream(index);
await repo.PushAsync(indexDesc, streamContent, reference, cancellationToken);
Assert.Equal(index, gotIndex);
}
/// <summary>
/// Repository_FetchReferenceAsync tests the FetchReferenceAsync method of the Repository
/// </summary>
/// <returns></returns>
[Fact]
public async Task Repository_FetchReferenceAsyc()
{
var blob = "hello"u8.ToArray();
var blobDesc = new Descriptor()
{
Digest = ComputeSha256(blob),
MediaType = "test",
Size = (uint)blob.Length
};
var index = @"{""manifests"":[]}"u8.ToArray();
var indexDesc = new Descriptor()
{
Digest = ComputeSha256(index),
MediaType = MediaType.ImageIndex,
Size = index.Length
};
var reference = "foobar";
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Get)
{
return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
}
if (req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + blobDesc.Digest)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
if (req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + indexDesc.Digest
|| req.RequestUri?.AbsolutePath == "/v2/test/manifests/" + reference)
{
if (req.Headers.TryGetValues("Accept", out var values) &&
!values.Contains(MediaType.ImageIndex))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
res.Content = new ByteArrayContent(index);
res.Content.Headers.Add("Content-Type", indexDesc.MediaType);
res.Headers.Add(_dockerContentDigestHeader, indexDesc.Digest);
return res;
}
return new HttpResponseMessage(HttpStatusCode.Found);
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
// test with blob digest
await Assert.ThrowsAsync<NotFoundException>(
async () => await repo.FetchAsync(blobDesc.Digest, cancellationToken));
// test with manifest digest
var data = await repo.FetchAsync(indexDesc.Digest, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, data.Descriptor));
var buf = new byte[data.Stream.Length];
await data.Stream.ReadExactlyAsync(buf, cancellationToken);
Assert.Equal(index, buf);
// test with manifest tag
data = await repo.FetchAsync(reference, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, data.Descriptor));
buf = new byte[data.Stream.Length];
await data.Stream.ReadExactlyAsync(buf, cancellationToken);
Assert.Equal(index, buf);
// test with manifest tag@digest
var tagDigestRef = "whatever" + "@" + indexDesc.Digest;
data = await repo.FetchAsync(tagDigestRef, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, data.Descriptor));
buf = new byte[data.Stream.Length];
await data.Stream.ReadExactlyAsync(buf, cancellationToken);
Assert.Equal(index, buf);
// test with manifest FQDN
var fqdnRef = "localhost:5000/test" + ":" + tagDigestRef;
data = await repo.FetchAsync(fqdnRef, cancellationToken);
Assert.True(AreDescriptorsEqual(indexDesc, data.Descriptor));
buf = new byte[data.Stream.Length];
await data.Stream.ReadExactlyAsync(buf, cancellationToken);
Assert.Equal(index, buf);
}
/// <summary>
/// Repository_TagsAsync tests the TagsAsync method of the Repository
/// to check if the tags are returned correctly
/// </summary>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[Fact]
public async Task Repository_TagsAsync()
{
var tagSet = new List<List<string>>()
{
new() {"the", "quick", "brown", "fox"},
new() {"jumps", "over", "the", "lazy"},
new() {"dog"}
};
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Get ||
req.RequestUri?.AbsolutePath != "/v2/test/tags/list"
)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var q = req.RequestUri.Query;
try
{
var n = int.Parse(Regex.Match(q, @"(?<=n=)\d+").Value);
if (n != 4) throw new Exception();
}
catch
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
var tags = new List<string>();
var serverUrl = "http://localhost:5000";
var matched = Regex.Match(q, @"(?<=test=)\w+").Value;
switch (matched)
{
case "foo":
tags = tagSet[1];
res.Headers.Add("Link", $"<{serverUrl}/v2/test/tags/list?n=4&test=bar>; rel=\"next\"");
break;
case "bar":
tags = tagSet[2];
break;
default:
tags = tagSet[0];
res.Headers.Add("Link", $"</v2/test/tags/list?n=4&test=foo>; rel=\"next\"");
break;
}
var listOfTags = new Repository.TagList
{
Tags = [.. tags]
};
res.Content = new StringContent(JsonSerializer.Serialize(listOfTags));
return res;
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
TagListPageSize = 4,
});
var cancellationToken = new CancellationToken();
var wantTags = new List<string>();
foreach (var set in tagSet)
{
wantTags.AddRange(set);
}
var gotTags = new List<string>();
await foreach (var tag in repo.ListTagsAsync().WithCancellation(cancellationToken))
{
gotTags.Add(tag);
}
Assert.Equal(wantTags, gotTags);
}
/// <summary>
/// Repository_TagsAsync tests the TagsAsync method of the Repository returning null tags
/// (this is the case of ghcr.io/oras-project/registry).
/// </summary>
/// <returns></returns>
/// <exception cref="Exception"></exception>
[Fact]
public async Task Repository_TagsAsync_Empty()
{
HttpResponseMessage func(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Get ||
req.RequestUri?.AbsolutePath != "/v2/test/tags/list"
)
{
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var q = req.RequestUri.Query;
try
{
var n = int.Parse(Regex.Match(q, @"(?<=n=)\d+").Value);
if (n != 4) throw new Exception();
}
catch
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
var listOfTags = new Repository.TagList
{
Tags = null!
};
res.Content = new StringContent(JsonSerializer.Serialize(listOfTags));
return res;
}
IRepository repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(func),
PlainHttp = true,
TagListPageSize = 4,
});
var cancellationToken = new CancellationToken();
var wantTags = new List<string>();
var gotTags = new List<string>();
await foreach (var tag in repo.ListTagsAsync().WithCancellation(cancellationToken))
{
gotTags.Add(tag);
}
Assert.Equal(wantTags, gotTags);
}
/// <summary>
/// BlobStore_FetchAsync tests the FetchAsync method of the BlobStore
/// </summary>
/// <returns></returns>
[Fact]
public async Task BlobStore_FetchAsync()
{
var blob = "hello world"u8.ToArray();
var blobDesc = new Descriptor()
{
MediaType = "test",
Digest = ComputeSha256(blob),
Size = blob.Length
};
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Get)
{
return new HttpResponseMessage(HttpStatusCode.MethodNotAllowed);
}
if (req.RequestUri?.AbsolutePath == $"/v2/test/blobs/{blobDesc.Digest}")
{
res.Content = new ByteArrayContent(blob);
res.Content.Headers.Add("Content-Type", "application/octet-stream");
res.Headers.Add(_dockerContentDigestHeader, blobDesc.Digest);
return res;
}
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
var repo = new Repository(new RepositoryOptions()
{
Reference = Reference.Parse("localhost:5000/test"),
Client = CustomClient(MockHandler),
PlainHttp = true,
});
var cancellationToken = new CancellationToken();
var store = new BlobStore(repo);
var stream = await store.FetchAsync(blobDesc, cancellationToken);
var buf = new byte[stream.Length];
await stream.ReadExactlyAsync(buf, cancellationToken);
Assert.Equal(blob, buf);
}
/// <summary>
/// BlobStore_FetchAsync_CanSeek tests the FetchAsync method of the BlobStore for a stream that can seek
/// </summary>
/// <returns></returns>
[Fact]
public async Task BlobStore_FetchAsync_CanSeek()
{
var blob = "hello world"u8.ToArray();
var blobDesc = new Descriptor()
{
MediaType = "test",
Digest = ComputeSha256(blob),
Size = blob.Length
};
var seekable = false;
HttpResponseMessage MockHandler(HttpRequestMessage req, CancellationToken cancellationToken = default)
{
var res = new HttpResponseMessage
{
RequestMessage = req
};
if (req.Method != HttpMethod.Get)