-
Notifications
You must be signed in to change notification settings - Fork 5
Allow NIOHTTPServer to use NIOAsyncTestingChannel for tests #39
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
a519062
Add tests using NIOAsyncTestingChannel
aryan-25 5388c1a
Update swift-nio dependency
aryan-25 b4a5b33
Merge branch 'main' into async-testing-channel
aryan-25 572f6ba
Merge branch 'main' into async-testing-channel
aryan-25 b51d124
Merge branch 'main' into async-testing-channel
aryan-25 a6a795f
Run formatter
aryan-25 c78e31a
Fix license headers
aryan-25 473c5a4
Address feedback from review
aryan-25 a89511e
Merge branch 'main' into async-testing-channel
aryan-25 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift HTTP Server open source project | ||
| // | ||
| // Copyright (c) 2026 Apple Inc. and the Swift HTTP Server project authors | ||
| // Licensed under Apache License v2.0 | ||
| // | ||
| // See LICENSE.txt for license information | ||
| // See CONTRIBUTORS.txt for the list of Swift HTTP Server project authors | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import NIOCore | ||
| import NIOEmbedded | ||
| import NIOHTTP1 | ||
| import NIOHTTPTypes | ||
| import NIOHTTPTypesHTTP1 | ||
| import NIOPosix | ||
|
|
||
| @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) | ||
| extension NIOHTTPServer { | ||
| func serveInsecureHTTP1_1( | ||
| bindTarget: NIOHTTPServerConfiguration.BindTarget, | ||
| handler: some HTTPServerRequestHandler<RequestReader, ResponseWriter>, | ||
| asyncChannelConfiguration: NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>.Configuration | ||
| ) async throws { | ||
| let serverChannel = try await self.setupHTTP1_1ServerChannel( | ||
| bindTarget: bindTarget, | ||
| asyncChannelConfiguration: asyncChannelConfiguration | ||
| ) | ||
|
|
||
| try await _serveInsecureHTTP1_1(serverChannel: serverChannel, handler: handler) | ||
| } | ||
|
|
||
| private func setupHTTP1_1ServerChannel( | ||
| bindTarget: NIOHTTPServerConfiguration.BindTarget, | ||
| asyncChannelConfiguration: NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>.Configuration | ||
| ) async throws -> NIOAsyncChannel<NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>, Never> { | ||
| switch bindTarget.backing { | ||
| case .hostAndPort(let host, let port): | ||
| let serverChannel = try await ServerBootstrap(group: .singletonMultiThreadedEventLoopGroup) | ||
| .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) | ||
| .bind(host: host, port: port) { channel in | ||
| self.setupHTTP1_1ConnectionChildChannel( | ||
| channel: channel, | ||
| asyncChannelConfiguration: asyncChannelConfiguration | ||
| ) | ||
| } | ||
|
|
||
| try self.addressBound(serverChannel.channel.localAddress) | ||
|
|
||
| return serverChannel | ||
| } | ||
| } | ||
|
|
||
| func setupHTTP1_1ConnectionChildChannel( | ||
| channel: any Channel, | ||
| asyncChannelConfiguration: NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>.Configuration | ||
| ) -> EventLoopFuture<NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>> { | ||
| channel.pipeline.configureHTTPServerPipeline().flatMapThrowing { | ||
| try channel.pipeline.syncOperations.addHandler(HTTP1ToHTTPServerCodec(secure: false)) | ||
|
|
||
| return try NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>( | ||
| wrappingChannelSynchronously: channel, | ||
| configuration: asyncChannelConfiguration | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| func _serveInsecureHTTP1_1( | ||
| serverChannel: NIOAsyncChannel<NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>, Never>, | ||
| handler: some HTTPServerRequestHandler<RequestReader, ResponseWriter> | ||
| ) async throws { | ||
| try await withThrowingDiscardingTaskGroup { group in | ||
| try await serverChannel.executeThenClose { inbound in | ||
| for try await http1Channel in inbound { | ||
| group.addTask { | ||
| try await self.handleRequestChannel( | ||
| channel: http1Channel, | ||
| handler: handler | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,212 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift HTTP Server open source project | ||
| // | ||
| // Copyright (c) 2026 Apple Inc. and the Swift HTTP Server project authors | ||
| // Licensed under Apache License v2.0 | ||
| // | ||
| // See LICENSE.txt for license information | ||
| // See CONTRIBUTORS.txt for the list of Swift HTTP Server project authors | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import Logging | ||
| import NIOCore | ||
| import NIOEmbedded | ||
| import NIOHTTP2 | ||
| import NIOHTTPTypes | ||
| import NIOHTTPTypesHTTP1 | ||
| import NIOHTTPTypesHTTP2 | ||
| import NIOPosix | ||
| import NIOSSL | ||
| import X509 | ||
|
|
||
| @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) | ||
| extension NIOHTTPServer { | ||
| func serveSecureUpgrade( | ||
| bindTarget: NIOHTTPServerConfiguration.BindTarget, | ||
| tlsConfiguration: TLSConfiguration, | ||
| handler: some HTTPServerRequestHandler<RequestReader, ResponseWriter>, | ||
| asyncChannelConfiguration: NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>.Configuration, | ||
| http2Configuration: NIOHTTP2Handler.Configuration, | ||
| verificationCallback: (@Sendable ([X509.Certificate]) async throws -> CertificateVerificationResult)? = nil | ||
| ) async throws { | ||
| let serverChannel = try await self.setupSecureUpgradeServerChannel( | ||
| bindTarget: bindTarget, | ||
| tlsConfiguration: tlsConfiguration, | ||
| asyncChannelConfiguration: asyncChannelConfiguration, | ||
| http2Configuration: http2Configuration, | ||
| verificationCallback: verificationCallback | ||
| ) | ||
|
|
||
| try await self._serveSecureUpgrade(serverChannel: serverChannel, handler: handler) | ||
| } | ||
|
|
||
| typealias NegotiatedChannel = NIONegotiatedHTTPVersion< | ||
| NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>, | ||
| (any Channel, NIOHTTP2Handler.AsyncStreamMultiplexer<NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>>) | ||
| > | ||
|
|
||
| private func setupSecureUpgradeServerChannel( | ||
| bindTarget: NIOHTTPServerConfiguration.BindTarget, | ||
| tlsConfiguration: TLSConfiguration, | ||
| asyncChannelConfiguration: NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>.Configuration, | ||
| http2Configuration: NIOHTTP2Handler.Configuration, | ||
| verificationCallback: (@Sendable ([X509.Certificate]) async throws -> CertificateVerificationResult)? | ||
| ) async throws -> NIOAsyncChannel<EventLoopFuture<NegotiatedChannel>, Never> { | ||
| switch bindTarget.backing { | ||
| case .hostAndPort(let host, let port): | ||
| let serverChannel = try await ServerBootstrap(group: .singletonMultiThreadedEventLoopGroup) | ||
| .serverChannelOption(.socketOption(.so_reuseaddr), value: 1) | ||
| .bind(host: host, port: port) { channel in | ||
| self.setupSecureUpgradeConnectionChildChannel( | ||
| channel: channel, | ||
| tlsConfiguration: tlsConfiguration, | ||
| asyncChannelConfiguration: asyncChannelConfiguration, | ||
| http2Configuration: http2Configuration, | ||
| verificationCallback: verificationCallback | ||
| ) | ||
| } | ||
|
|
||
| try self.addressBound(serverChannel.channel.localAddress) | ||
|
|
||
| return serverChannel | ||
| } | ||
| } | ||
|
|
||
| func setupSecureUpgradeConnectionChildChannel( | ||
| channel: any Channel, | ||
| tlsConfiguration: TLSConfiguration, | ||
| asyncChannelConfiguration: NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>.Configuration, | ||
| http2Configuration: NIOHTTP2Handler.Configuration, | ||
| verificationCallback: (@Sendable ([X509.Certificate]) async throws -> CertificateVerificationResult)? | ||
| ) -> EventLoopFuture<EventLoopFuture<NegotiatedChannel>> { | ||
| channel.eventLoop.makeCompletedFuture { | ||
| try channel.pipeline.syncOperations.addHandler( | ||
| self.makeSSLServerHandler(tlsConfiguration, verificationCallback) | ||
| ) | ||
| }.flatMap { | ||
| channel.configureAsyncHTTPServerPipeline( | ||
| http2Configuration: http2Configuration, | ||
| http1ConnectionInitializer: { channel in | ||
| channel.eventLoop.makeCompletedFuture { | ||
| try channel.pipeline.syncOperations.addHandler(HTTP1ToHTTPServerCodec(secure: true)) | ||
|
|
||
| return try NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>( | ||
| wrappingChannelSynchronously: channel, | ||
| configuration: asyncChannelConfiguration | ||
| ) | ||
| } | ||
| }, | ||
| http2ConnectionInitializer: { channel in channel.eventLoop.makeCompletedFuture(.success(channel)) }, | ||
| http2StreamInitializer: { channel in | ||
| channel.eventLoop.makeCompletedFuture { | ||
| try channel.pipeline.syncOperations | ||
| .addHandler( | ||
| HTTP2FramePayloadToHTTPServerCodec() | ||
| ) | ||
|
|
||
| return try NIOAsyncChannel<HTTPRequestPart, HTTPResponsePart>( | ||
| wrappingChannelSynchronously: channel, | ||
| configuration: asyncChannelConfiguration | ||
| ) | ||
| } | ||
| } | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| func _serveSecureUpgrade( | ||
| serverChannel: NIOAsyncChannel<EventLoopFuture<NegotiatedChannel>, Never>, | ||
| handler: some HTTPServerRequestHandler<RequestReader, ResponseWriter> | ||
| ) async throws { | ||
| try await withThrowingDiscardingTaskGroup { group in | ||
| try await serverChannel.executeThenClose { inbound in | ||
| for try await upgradeResult in inbound { | ||
| group.addTask { | ||
| do { | ||
| try await withThrowingDiscardingTaskGroup { connectionGroup in | ||
| switch try await upgradeResult.get() { | ||
| case .http1_1(let http1Channel): | ||
| let chainFuture = http1Channel.channel.nioSSL_peerValidatedCertificateChain() | ||
| Self.$connectionContext.withValue(ConnectionContext(chainFuture)) { | ||
| connectionGroup.addTask { | ||
| try await self.handleRequestChannel( | ||
| channel: http1Channel, | ||
| handler: handler | ||
| ) | ||
| } | ||
| } | ||
| case .http2((let http2Connection, let http2Multiplexer)): | ||
| do { | ||
| let chainFuture = http2Connection.nioSSL_peerValidatedCertificateChain() | ||
| try await Self.$connectionContext.withValue(ConnectionContext(chainFuture)) { | ||
| for try await http2StreamChannel in http2Multiplexer.inbound { | ||
| connectionGroup.addTask { | ||
| try await self.handleRequestChannel( | ||
| channel: http2StreamChannel, | ||
| handler: handler | ||
| ) | ||
| } | ||
| } | ||
| } | ||
| } catch { | ||
| self.logger.debug("HTTP2 connection closed: \(error)") | ||
| } | ||
| } | ||
| } | ||
| } catch { | ||
| self.logger.debug("Negotiating ALPN failed: \(error)") | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| @available(macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0, *) | ||
| extension NIOHTTPServer { | ||
| func makeSSLServerHandler( | ||
| _ tlsConfiguration: TLSConfiguration, | ||
| _ customVerificationCallback: (@Sendable ([X509.Certificate]) async throws -> CertificateVerificationResult)? | ||
| ) throws -> NIOSSLServerHandler { | ||
| if let customVerificationCallback { | ||
| return try NIOSSLServerHandler( | ||
| context: .init(configuration: tlsConfiguration), | ||
| customVerificationCallbackWithMetadata: { certificates, promise in | ||
| promise.completeWithTask { | ||
| // Convert input [NIOSSLCertificate] to [X509.Certificate] | ||
| let x509Certs = try certificates.map { try Certificate($0) } | ||
|
|
||
| let callbackResult = try await customVerificationCallback(x509Certs) | ||
|
|
||
| switch callbackResult { | ||
| case .certificateVerified(let verificationMetadata): | ||
| guard let peerChain = verificationMetadata.validatedCertificateChain else { | ||
| return .certificateVerified(.init(nil)) | ||
| } | ||
|
|
||
| // Convert the result into [NIOSSLCertificate] | ||
| let nioSSLCerts = try peerChain.map { try NIOSSLCertificate($0) } | ||
| return .certificateVerified(.init(.init(nioSSLCerts))) | ||
|
|
||
| case .failed(let error): | ||
| self.logger.error( | ||
| "Custom certificate verification failed", | ||
| metadata: [ | ||
| "failure-reason": .string(error.reason) | ||
| ] | ||
| ) | ||
| return .failed | ||
| } | ||
| } | ||
| } | ||
| ) | ||
| } else { | ||
| return try NIOSSLServerHandler(context: .init(configuration: tlsConfiguration)) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.