Repository navigation
Expand file tree
/
Copy pathLocalOCILayoutClient.swift
More file actions
230 lines (203 loc) · 9.77 KB
/
Copy pathLocalOCILayoutClient.swift
File metadata and controls
230 lines (203 loc) · 9.77 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
//===----------------------------------------------------------------------===//
// Copyright © 2025-2026 Apple Inc. and the Containerization project 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
//
// https://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.
//===----------------------------------------------------------------------===//
import ContainerizationError
import ContainerizationExtras
import Crypto
import Foundation
import NIOCore
import NIOFoundationCompat
package final class LocalOCILayoutClient: ContentClient {
let cs: LocalContentStore
package init(root: URL) throws {
self.cs = try LocalContentStore(path: root)
}
private func _fetch(digest: String) async throws -> Content {
guard let c: Content = try await self.cs.get(digest: digest) else {
throw Error.missingContent(digest)
}
return c
}
package func fetch<T: Codable>(name: String, descriptor: Descriptor) async throws -> T {
let c = try await self._fetch(digest: descriptor.digest)
return try c.decode()
}
package func fetchBlob(name: String, descriptor: Descriptor, into file: URL, progress: ProgressHandler?) async throws -> (Int64, SHA256Digest) {
let c = try await self._fetch(digest: descriptor.digest)
let fileManager = FileManager.default
let filePath = file.absolutePath()
let (size, digest) = try ContentWriter.copy(from: c.path, destination: file)
if let progress, let fileSize = fileManager.fileSize(atPath: filePath) {
await progress([
.addSize(fileSize)
])
}
return (size, digest)
}
package func fetchData(name: String, descriptor: Descriptor) async throws -> Data {
let c = try await self._fetch(digest: descriptor.digest)
return try c.data()
}
package func push<T: Sendable & AsyncSequence>(
name: String,
ref: String,
descriptor: Descriptor,
streamGenerator: () throws -> T,
progress: ProgressHandler?
) async throws where T.Element == ByteBuffer {
let input = try streamGenerator()
let (id, dir) = try await self.cs.newIngestSession()
do {
let expected = try ParsedDigest(parsingPathComponent: descriptor.digest)
let into = try expected.path(in: dir)
guard FileManager.default.createFile(atPath: into.path, contents: nil) else {
throw Error.cannotCreateFile
}
let fd = try FileHandle(forWritingTo: into)
defer {
try? fd.close()
}
var wrote = 0
var hasher = SHA256()
for try await buffer in input {
wrote += buffer.readableBytes
try fd.write(contentsOf: buffer.readableBytesView)
hasher.update(data: buffer.readableBytesView)
}
let actual = ParsedDigest(hasher.finalize())
guard actual == expected else {
throw ContainerizationError(
.internalError,
message: "content digest mismatch")
}
try await self.cs.completeIngestSession(id)
} catch {
try? await self.cs.cancelIngestSession(id)
throw error
}
}
}
extension LocalOCILayoutClient {
private static let ociLayoutFileName = "oci-layout"
private static let ociLayoutVersionString = "imageLayoutVersion"
private static let ociLayoutIndexFileName = "index.json"
package func loadIndexFromOCILayout(directory: URL) throws -> ContainerizationOCI.Index {
let decoder = JSONDecoder()
let ociLayoutFile = directory.appendingPathComponent(Self.ociLayoutFileName)
var data = try Self.readControlFile(at: ociLayoutFile)
let ociLayout = try decoder.decode([String: String].self, from: data)
guard ociLayout[Self.ociLayoutVersionString] != nil else {
throw ContainerizationError(.empty, message: "missing key \(Self.ociLayoutVersionString) in \(ociLayoutFile.absolutePath())")
}
let indexFile = directory.appendingPathComponent(Self.ociLayoutIndexFileName)
data = try Self.readControlFile(at: indexFile)
let index = try decoder.decode(ContainerizationOCI.Index.self, from: data)
return index
}
/// Read a layout control file.
/// File must be a regular file and cannot be larger than `maxDecodedSize`.
///
/// `oci-layout` and `index.json` are read straight out of a caller-supplied
/// directory before any digest in them has been looked at. Without the
/// `O_NOFOLLOW`/regular-file check, a crafted archive could place either name
/// as a symlink and without the size cap, an unbounded read here is a
/// memory-exhaustion primitive reachable from `ImageStore.load(from:)`.
private static func readControlFile(at url: URL) throws -> Data {
let fd = open(url.path, O_RDONLY | O_NOFOLLOW)
guard fd >= 0 else {
let errCode = POSIXErrorCode(rawValue: errno) ?? .EINVAL
let err = POSIXError(errCode)
throw ContainerizationError(.internalError, message: "failed to open \(url.absolutePath())", cause: err)
}
let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true)
defer { try? handle.close() }
var st = stat()
guard fstat(fd, &st) == 0 else {
let errCode = POSIXErrorCode(rawValue: errno) ?? .EINVAL
let err = POSIXError(errCode)
throw ContainerizationError(.internalError, message: "failed to stat \(url.absolutePath())", cause: err)
}
guard (st.st_mode & S_IFMT) == S_IFREG else {
throw ContainerizationError(.internalError, message: "refusing to read non-regular file at \(url.absolutePath())")
}
let limit = LocalContent.maxDecodedSize
let data = try handle.read(upToCount: limit + 1) ?? Data()
guard data.count <= limit else {
throw ContainerizationError(
.invalidArgument,
message: "\(url.absolutePath()) exceeds the \(limit) byte limit for OCI layout control files")
}
return data
}
package func createOCILayoutStructure(directory: URL, manifests: [Descriptor]) throws {
let fm = FileManager.default
let encoder = JSONEncoder()
encoder.outputFormatting = [.withoutEscapingSlashes]
let ingestDir = directory.appendingPathComponent("ingest")
try? fm.removeItem(at: ingestDir)
let ociLayoutContent: [String: String] = [
Self.ociLayoutVersionString: "1.0.0"
]
var data = try encoder.encode(ociLayoutContent)
var p = directory.appendingPathComponent(Self.ociLayoutFileName).absolutePath()
guard fm.createFile(atPath: p, contents: data) else {
throw ContainerizationError(.internalError, message: "failed to create file \(p)")
}
let idx = ContainerizationOCI.Index(schemaVersion: 2, manifests: manifests)
data = try encoder.encode(idx)
p = directory.appendingPathComponent(Self.ociLayoutIndexFileName).absolutePath()
guard fm.createFile(atPath: p, contents: data) else {
throw ContainerizationError(.internalError, message: "failed to create file \(p)")
}
}
package func setImageReferenceAnnotation(descriptor: inout Descriptor, reference: String) {
var annotations = descriptor.annotations ?? [:]
annotations[AnnotationKeys.containerizationImageName] = reference
annotations[AnnotationKeys.containerdImageName] = reference
annotations[AnnotationKeys.openContainersImageName] = reference
descriptor.annotations = annotations
}
package func getImageReferencefromDescriptor(descriptor: Descriptor) -> String {
let annotations = descriptor.annotations
// Annotations here do not conform to the OCI image specification.
// The interpretation of the annotations "org.opencontainers.image.ref.name" and
// "io.containerd.image.name" is under debate:
// - OCI spec examples suggest it should be the image tag:
// https://github.com/opencontainers/image-spec/blob/fbb4662eb53b80bd38f7597406cf1211317768f0/image-layout.md?plain=1#L175
// - Buildkitd maintainers argue it should represent the full image name:
// https://github.com/moby/buildkit/issues/4615#issuecomment-2521810830
// Until a consensus is reached, the preference is given to "com.apple.containerization.image.name" and then to
// using "io.containerd.image.name" as it is the next safest choice
if let annotations {
if let name = annotations[AnnotationKeys.containerizationImageName] {
return name
}
if let name = annotations[AnnotationKeys.containerdImageName] {
return name
}
if let name = annotations[AnnotationKeys.openContainersImageName] {
return name
}
}
// Fallback: Generate digest-based reference for images without annotations
// This makes sure OCI spec compliance as annotations are optional
return "untagged@\(descriptor.digest)"
}
package enum Error: Swift.Error {
case missingContent(_ digest: String)
case unsupportedInput
case cannotCreateFile
}
}