-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathOciRegistryClient.cs
More file actions
290 lines (258 loc) · 12.6 KB
/
OciRegistryClient.cs
File metadata and controls
290 lines (258 loc) · 12.6 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
// --------------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
// --------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Microsoft.Oryx.BuildScriptGenerator
{
/// <summary>
/// HTTP client for the OCI Distribution API. Enables Oryx to discover SDK versions
/// and download SDK tarballs from an OCI-compliant container registry (e.g. Azure Container Registry)
/// using only HttpClient — no external tools (docker, crane, oras) required.
/// All SDK images are public, so no authentication is needed.
/// </summary>
public class OciRegistryClient
{
private readonly HttpClient httpClient;
private readonly string registryUrl;
private readonly ILogger logger;
public OciRegistryClient(string registryUrl, IHttpClientFactory httpClientFactory, ILoggerFactory loggerFactory)
{
this.registryUrl = registryUrl.TrimEnd('/');
this.httpClient = httpClientFactory.CreateClient("general");
this.logger = loggerFactory.CreateLogger<OciRegistryClient>();
}
/// <summary>
/// Gets the first layer digest from a manifest (SDK images are single-layer FROM scratch images).
/// </summary>
public static string GetFirstLayerDigest(OciManifest manifest)
{
return manifest?.Layers?.FirstOrDefault()?.Digest;
}
/// <summary>
/// Lists all tags for a repository, handling Link-header pagination.
/// </summary>
public async Task<List<string>> GetAllTagsAsync(string repository)
{
var allTags = new List<string>();
var url = $"{this.registryUrl}/v2/{repository}/tags/list";
while (!string.IsNullOrEmpty(url))
{
this.logger.LogDebug("Fetching tags from {url}", url);
using (var response = await this.httpClient.GetAsync(url))
{
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Request to {url} failed with status code {response.StatusCode}");
}
var json = await response.Content.ReadAsStringAsync();
var tagList = JsonSerializer.Deserialize<OciTagList>(json);
if (tagList?.Tags != null)
{
allTags.AddRange(tagList.Tags);
}
// Handle OCI pagination via Link header (RFC 5988)
url = null;
if (response.Headers.TryGetValues("Link", out var linkValues))
{
var linkHeader = linkValues.FirstOrDefault();
if (linkHeader != null)
{
var match = Regex.Match(linkHeader, @"<([^>]+)>;\s*rel=""next""");
if (match.Success)
{
url = match.Groups[1].Value;
if (!url.StartsWith("http"))
{
url = $"{this.registryUrl}{url}";
}
}
}
}
}
}
return allTags;
}
/// <summary>
/// Fetches an OCI image manifest for the given repository and tag.
/// Tries OCI manifest format first, falls back to Docker manifest v2.
/// </summary>
public async Task<OciManifest> GetManifestAsync(string repository, string tag)
{
var url = $"{this.registryUrl}/v2/{repository}/manifests/{tag}";
using (var request = new HttpRequestMessage(HttpMethod.Get, url))
{
request.Headers.Add("Accept", "application/vnd.oci.image.manifest.v1+json");
using (var response = await this.httpClient.SendAsync(request))
{
if (!response.IsSuccessStatusCode)
{
// Fall back to Docker manifest v2
using (var fallbackRequest = new HttpRequestMessage(HttpMethod.Get, url))
{
fallbackRequest.Headers.Add("Accept", "application/vnd.docker.distribution.manifest.v2+json");
using (var fallbackResponse = await this.httpClient.SendAsync(fallbackRequest))
{
if (!fallbackResponse.IsSuccessStatusCode)
{
throw new HttpRequestException($"Fallback request to {url} failed with status code {fallbackResponse.StatusCode}");
}
var fallbackJson = await fallbackResponse.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<OciManifest>(fallbackJson);
}
}
}
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<OciManifest>(json);
}
}
}
/// <summary>
/// Fetches the image config blob (contains Labels) for the given repository and digest.
/// </summary>
public async Task<OciImageConfig> GetImageConfigAsync(string repository, string configDigest)
{
var url = $"{this.registryUrl}/v2/{repository}/blobs/{configDigest}";
using (var response = await this.httpClient.GetAsync(url))
{
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Request to {url} failed with status code {response.StatusCode}");
}
var json = await response.Content.ReadAsStringAsync();
return JsonSerializer.Deserialize<OciImageConfig>(json);
}
}
/// <summary>
/// Gets the default version for a platform from the "-default" tag's image config labels.
/// </summary>
public async Task<string> GetDefaultVersionAsync(string repository, string osFlavor)
{
var tag = $"{osFlavor}-default";
this.logger.LogDebug("Fetching default version from {repository}:{tag}", repository, tag);
try
{
var manifest = await this.GetManifestAsync(repository, tag);
var configDigest = manifest.Config?.Digest;
if (string.IsNullOrEmpty(configDigest))
{
this.logger.LogWarning("No config digest found in manifest for {repository}:{tag}", repository, tag);
return null;
}
var config = await this.GetImageConfigAsync(repository, configDigest);
if (config?.Config?.Labels != null &&
config.Config.Labels.TryGetValue(Common.SdkStorageConstants.AcrVersionLabelName, out var version))
{
return version;
}
this.logger.LogWarning("Version label not found in config for {repository}:{tag}", repository, tag);
return null;
}
catch (Exception ex)
{
this.logger.LogError(ex, "Failed to get default version from {repository}:{tag}", repository, tag);
throw;
}
}
/// <summary>
/// Downloads a layer blob (the SDK tarball) to disk and verifies its SHA256 digest.
/// The digest in the manifest IS the content hash — no separate checksum metadata needed.
/// </summary>
public async Task<bool> DownloadLayerBlobAsync(string repository, string layerDigest, string outputPath)
{
var url = $"{this.registryUrl}/v2/{repository}/blobs/{layerDigest}";
this.logger.LogDebug("Downloading layer blob {digest} from {repository}", layerDigest, repository);
using (var response = await this.httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
if (!response.IsSuccessStatusCode)
{
throw new HttpRequestException($"Request to {url} failed with status code {response.StatusCode}");
}
using (var stream = await response.Content.ReadAsStreamAsync())
using (var fileStream = File.Create(outputPath))
{
await stream.CopyToAsync(fileStream);
}
}
// Verify SHA256 digest
var expectedSha = layerDigest.StartsWith("sha256:")
? layerDigest.Substring("sha256:".Length)
: layerDigest;
using (var fileStream = File.OpenRead(outputPath))
using (var sha256 = SHA256.Create())
{
var hashBytes = sha256.ComputeHash(fileStream);
var actualSha = BitConverter.ToString(hashBytes).Replace("-", string.Empty).ToLowerInvariant();
if (!string.Equals(actualSha, expectedSha, StringComparison.OrdinalIgnoreCase))
{
this.logger.LogError(
"SHA256 digest mismatch for {repository} blob {digest}. Expected: {expected}, Actual: {actual}",
repository,
layerDigest,
expectedSha,
actualSha);
File.Delete(outputPath);
return false;
}
}
this.logger.LogDebug("Successfully downloaded and verified layer blob {digest}", layerDigest);
return true;
}
/// <summary>
/// Pulls an SDK tarball from an OCI image built with <c>FROM scratch; COPY sdk.tar.gz /</c>.
/// Because the image contains a single layer, that layer IS the SDK tarball.
/// Flow: fetch manifest → extract single layer digest → download blob → verify SHA256.
/// </summary>
/// <param name="repository">The repository name, e.g. "sdks/python".</param>
/// <param name="tag">The image tag, e.g. "bookworm-3.11.0".</param>
/// <param name="outputFilePath">The full path where the downloaded tarball should be saved.</param>
/// <returns>True if the SDK was pulled and verified successfully.</returns>
public async Task<bool> PullSdkAsync(string repository, string tag, string outputFilePath)
{
this.logger.LogInformation(
"Pulling SDK directly from ACR: {repository}:{tag} -> {outputPath}",
repository,
tag,
outputFilePath);
// Step 1: Fetch the OCI manifest
var manifest = await this.GetManifestAsync(repository, tag);
if (manifest == null)
{
this.logger.LogError("Failed to get manifest for {repository}:{tag}", repository, tag);
return false;
}
// Step 2: Get the single layer digest (FROM scratch images have exactly 1 layer)
var layerDigest = GetFirstLayerDigest(manifest);
if (string.IsNullOrEmpty(layerDigest))
{
this.logger.LogError(
"No layer found in manifest for {repository}:{tag}. Expected a single-layer FROM scratch image.",
repository,
tag);
return false;
}
this.logger.LogDebug(
"Manifest for {repository}:{tag} has layer digest: {digest}",
repository,
tag,
layerDigest);
// Ensure the output directory exists
var outputDir = Path.GetDirectoryName(outputFilePath);
if (!string.IsNullOrEmpty(outputDir))
{
Directory.CreateDirectory(outputDir);
}
// Step 3: Download the layer blob (this IS the SDK tarball) and verify SHA256
return await this.DownloadLayerBlobAsync(repository, layerDigest, outputFilePath);
}
}
}