Skip to content

Commit 836080d

Browse files
authored
Content hash validation fixes in registry client. (#77) (#973)
- When calling `RegistryClient.resolve()` with a pinned hash value, ensure that the caller's hash matches the `Docker-Content-Digest` header in the HEAD response, or fail the call. - Verify content digests in `RegistryClient` `fetch()`, `fetchData()`, and `fetchBlob()`. - Updates swift-service-lifecycle dependency from 2.11.0 to 2.12.0.
1 parent 6adea56 commit 836080d

8 files changed

Lines changed: 447 additions & 7 deletions

File tree

‎Package.resolved‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Package.swift‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,8 @@ let package = Package(
208208
.product(name: "NIO", package: "swift-nio"),
209209
.product(name: "NIOSSL", package: "swift-nio-ssl"),
210210
.product(name: "X509", package: "swift-certificates"),
211+
.product(name: "NIOCore", package: "swift-nio"),
212+
.product(name: "NIOPosix", package: "swift-nio"),
211213
.product(name: "NIOHTTP1", package: "swift-nio"),
212214
.product(name: "Crypto", package: "swift-crypto"),
213215
]

‎Sources/ContainerizationOCI/Client/RegistryClient+Fetch.swift‎

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,17 @@ extension RegistryClient {
8080
throw ContainerizationError(.invalidArgument, message: "invalid Content-Length \(sizeStr)")
8181
}
8282

83+
// `tag` is sometimes actually a caller-pinned digest (see `ImageStore.pull`,
84+
// which passes `ref.tag ?? ref.digest`). A registry is untrusted input: if the
85+
// caller asked to resolve a specific digest, the registry doesn't get to answer
86+
// with a different one. Mutable tags carry no such promise, so they're exempt.
87+
if tag.isDigest, digest.lowercased() != tag.lowercased() {
88+
throw ContainerizationError(
89+
.internalError,
90+
message: "registry returned digest \(digest) for pinned reference \(tag), refusing to accept substituted content"
91+
)
92+
}
93+
8394
return Descriptor(mediaType: type, digest: digest, size: size)
8495
}
8596
}
@@ -109,7 +120,9 @@ extension RegistryClient {
109120
("Accept", mediaType)
110121
]
111122

112-
return try await requestJSON(components: components, headers: headers)
123+
let data = try await requestData(components: components, headers: headers)
124+
try Self.verifyContentDigest(data, matches: descriptor)
125+
return try JSONDecoder().decode(T.self, from: data)
113126
}
114127

115128
/// Fetch resource (either manifest or blob) to memory as raw `Data`.
@@ -137,7 +150,30 @@ extension RegistryClient {
137150
("Accept", mediaType)
138151
]
139152

140-
return try await requestData(components: components, headers: headers)
153+
let data = try await requestData(components: components, headers: headers)
154+
try Self.verifyContentDigest(data, matches: descriptor)
155+
return data
156+
}
157+
158+
/// Verifies that `data`'s SHA-256 hash matches the digest `descriptor` claims to be.
159+
/// Every caller of `fetch`/`fetchData`/`fetchBlob` already supplies the digest it expects
160+
/// (from a manifest it previously trusted, or from a caller-pinned reference resolved via
161+
/// `resolve`), so this is the one place that has to hold for any of those callers to be
162+
/// safe against a registry that serves different bytes than the digest it declared.
163+
fileprivate static func verifyContentDigest(_ data: Data, matches descriptor: Descriptor) throws {
164+
try verifyContentDigest(SHA256.hash(data: data), matches: descriptor)
165+
}
166+
167+
/// Same check as above, for callers that already hashed the content while streaming it
168+
/// rather than holding the whole thing in memory as `Data`.
169+
fileprivate static func verifyContentDigest(_ digest: SHA256.Digest, matches descriptor: Descriptor) throws {
170+
let computed = digest.digestString
171+
guard computed.lowercased() == descriptor.digest.lowercased() else {
172+
throw ContainerizationError(
173+
.internalError,
174+
message: "content digest mismatch: expected \(descriptor.digest)"
175+
)
176+
}
141177
}
142178

143179
/// Fetch a blob from remote registry.
@@ -231,6 +267,7 @@ extension RegistryClient {
231267
throw error
232268
}
233269
let computedDigest = hasher.finalize()
270+
try Self.verifyContentDigest(computedDigest, matches: descriptor)
234271
return (received, computedDigest)
235272
}
236273
#else
@@ -259,6 +296,7 @@ extension RegistryClient {
259296
}
260297
}
261298
let computedDigest = hasher.finalize()
299+
try Self.verifyContentDigest(computedDigest, matches: descriptor)
262300
return (received, computedDigest)
263301
}
264302
#endif

‎Sources/ContainerizationOCI/Content/String+Extension.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,14 @@ extension String {
3232
}
3333
return self
3434
}
35+
36+
/// True if this string has the shape of a content digest (`sha256:<64 hex characters>`),
37+
/// as opposed to a mutable tag name. Used to tell a digest-pinned reference apart from a
38+
/// tag reference before trusting anything a registry claims about it.
39+
var isDigest: Bool {
40+
guard let regex = try? Regex(Reference.digestPattern) else {
41+
return false
42+
}
43+
return (try? regex.wholeMatch(in: self)) != nil
44+
}
3545
}

‎Sources/ContainerizationOCI/Reference.swift‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ public class Reference: CustomStringConvertible {
9595
}()
9696

9797
static let pathPattern = "(?<path>(?:[a-z0-9]+(?:[._]|__|-|/)?)*[a-z0-9]+)"
98-
static let tagPattern = "(?::(?<tag>[\\w][\\w.-]{0,127}))?(?:@(?<digest>sha256:[0-9a-fA-F]{64}))?"
98+
/// A content digest, e.g. `sha256:<64 lowercase or uppercase hex characters>`.
99+
static let digestPattern = "sha256:[0-9a-fA-F]{64}"
100+
static let tagPattern = "(?::(?<tag>[\\w][\\w.-]{0,127}))?(?:@(?<digest>\(digestPattern)))?"
99101
static let pathTagPattern = "\(pathPattern)\(tagPattern)"
100102

101103
public init(path: String, domain: String? = nil, tag: String? = nil, digest: String? = nil) throws {
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
//===----------------------------------------------------------------------===//
2+
// Copyright © 2026 Apple Inc. and the Containerization project authors.
3+
//
4+
// Licensed under the Apache License, Version 2.0 (the "License");
5+
// you may not use this file except in compliance with the License.
6+
// You may obtain a copy of the License at
7+
//
8+
// https://www.apache.org/licenses/LICENSE-2.0
9+
//
10+
// Unless required by applicable law or agreed to in writing, software
11+
// distributed under the License is distributed on an "AS IS" BASIS,
12+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
// See the License for the specific language governing permissions and
14+
// limitations under the License.
15+
//===----------------------------------------------------------------------===//
16+
17+
import Foundation
18+
import NIOCore
19+
import NIOHTTP1
20+
import NIOPosix
21+
22+
// MARK: - MockRegistryRequest / MockRegistryResponse
23+
24+
/// An inbound HTTP request captured by the mock registry server.
25+
struct MockRegistryRequest: Sendable {
26+
let method: HTTPMethod
27+
let uri: String
28+
let headers: HTTPHeaders
29+
}
30+
31+
/// A canned HTTP response produced by the mock registry server.
32+
struct MockRegistryResponse: Sendable {
33+
let status: HTTPResponseStatus
34+
let body: Data
35+
let headers: HTTPHeaders
36+
37+
static func status(_ status: HTTPResponseStatus, headers: HTTPHeaders = [:], body: Data = .init()) -> MockRegistryResponse {
38+
MockRegistryResponse(status: status, body: body, headers: headers)
39+
}
40+
}
41+
42+
// MARK: - MockRegistryServer
43+
44+
/// An in-process HTTP/1.1 server bound to `127.0.0.1` on an OS-assigned port,
45+
/// used to stand in for a registry (honest or malicious) in `RegistryClient` tests.
46+
///
47+
/// Modeled on `Tests/CloudHypervisorTests/StubHTTPServer.swift`, which binds to a
48+
/// Unix domain socket instead — `RegistryClient` talks real HTTP over TCP, so this
49+
/// variant binds a TCP listener rather than reusing that one directly.
50+
final class MockRegistryServer: Sendable {
51+
/// The port this server is listening on.
52+
let port: Int
53+
54+
private let channel: Channel
55+
56+
init(
57+
eventLoopGroup: any EventLoopGroup,
58+
handler: @escaping @Sendable (MockRegistryRequest) -> MockRegistryResponse
59+
) async throws {
60+
let bootstrap = ServerBootstrap(group: eventLoopGroup)
61+
.serverChannelOption(.backlog, value: 256)
62+
.serverChannelOption(.socketOption(.so_reuseaddr), value: 1)
63+
.childChannelInitializer { channel in
64+
channel.eventLoop.makeCompletedFuture {
65+
try channel.pipeline.syncOperations.configureHTTPServerPipeline(
66+
withPipeliningAssistance: false
67+
)
68+
try channel.pipeline.syncOperations.addHandler(
69+
MockRegistryRequestHandler(userHandler: handler)
70+
)
71+
}
72+
}
73+
74+
let boundChannel =
75+
try await bootstrap
76+
.bind(host: "127.0.0.1", port: 0)
77+
.get()
78+
79+
guard let port = boundChannel.localAddress?.port else {
80+
try await boundChannel.close().get()
81+
fatalError("bound channel has no local port")
82+
}
83+
84+
self.port = port
85+
self.channel = boundChannel
86+
}
87+
88+
/// Stop accepting connections and close the listening socket.
89+
func shutdown() async throws {
90+
try await channel.close().get()
91+
}
92+
}
93+
94+
// MARK: - MockRegistryRequestHandler
95+
96+
/// Handles a single inbound HTTP/1.1 request and writes back the user handler's response.
97+
private final class MockRegistryRequestHandler: ChannelInboundHandler, @unchecked Sendable {
98+
typealias InboundIn = HTTPServerRequestPart
99+
typealias OutboundOut = HTTPServerResponsePart
100+
101+
private let userHandler: @Sendable (MockRegistryRequest) -> MockRegistryResponse
102+
103+
// Mutable inbound state — only touched on the event loop.
104+
private var pendingMethod: HTTPMethod?
105+
private var pendingURI: String?
106+
private var pendingHeaders: HTTPHeaders = [:]
107+
108+
init(userHandler: @escaping @Sendable (MockRegistryRequest) -> MockRegistryResponse) {
109+
self.userHandler = userHandler
110+
}
111+
112+
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
113+
switch unwrapInboundIn(data) {
114+
case .head(let head):
115+
pendingMethod = head.method
116+
pendingURI = head.uri
117+
pendingHeaders = head.headers
118+
case .body:
119+
break
120+
case .end:
121+
guard let method = pendingMethod, let uri = pendingURI else {
122+
context.close(promise: nil)
123+
return
124+
}
125+
let request = MockRegistryRequest(method: method, uri: uri, headers: pendingHeaders)
126+
let response = userHandler(request)
127+
writeResponse(context: context, method: method, response: response)
128+
}
129+
}
130+
131+
private func writeResponse(context: ChannelHandlerContext, method: HTTPMethod, response: MockRegistryResponse) {
132+
var respHeaders = response.headers
133+
respHeaders.replaceOrAdd(name: "Content-Length", value: "\(response.body.count)")
134+
respHeaders.replaceOrAdd(name: "Connection", value: "close")
135+
136+
let head = HTTPResponseHead(version: .http1_1, status: response.status, headers: respHeaders)
137+
context.write(wrapOutboundOut(.head(head)), promise: nil)
138+
139+
// HEAD responses never carry a body, matching a real registry's HEAD /manifests/<ref>.
140+
if method != .HEAD, !response.body.isEmpty {
141+
var buf = context.channel.allocator.buffer(capacity: response.body.count)
142+
buf.writeBytes(response.body)
143+
context.write(wrapOutboundOut(.body(.byteBuffer(buf))), promise: nil)
144+
}
145+
146+
let boundContext = NIOLoopBound(context, eventLoop: context.eventLoop)
147+
context.writeAndFlush(wrapOutboundOut(.end(nil))).whenComplete { _ in
148+
boundContext.value.close(promise: nil)
149+
}
150+
}
151+
152+
func errorCaught(context: ChannelHandlerContext, error: any Error) {
153+
context.close(promise: nil)
154+
}
155+
}

0 commit comments

Comments
 (0)