|
| 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