Skip to content

Fix leaked TLS handshake promise #180

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 1 commit into from
Mar 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 19 additions & 18 deletions Sources/AsyncHTTPClient/ConnectionPool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -383,32 +383,33 @@ final class ConnectionPool {
}

return channel.flatMap { channel -> EventLoopFuture<ConnectionPool.Connection> in
channel.pipeline.addSSLHandlerIfNeeded(for: self.key, tlsConfiguration: self.configuration.tlsConfiguration, handshakePromise: handshakePromise).flatMap {
channel.pipeline.addSSLHandlerIfNeeded(for: self.key, tlsConfiguration: self.configuration.tlsConfiguration, handshakePromise: handshakePromise)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The promise and returned future were redundant IMO so this only makes use of handshakePromise now

return handshakePromise.futureResult.flatMap {
channel.pipeline.addHTTPClientHandlers(leftOverBytesStrategy: .forwardBytes)
}.map {
let connection = Connection(key: self.key, channel: channel, parentPool: self.parentPool)
connection.isLeased = true
return connection
}
}.flatMap { connection in
handshakePromise.futureResult.map {
self.configureCloseCallback(of: connection)
return connection
}.flatMapError { error in
connection.closePromise.succeed(())
let action = self.parentPool.connectionProvidersLock.withLock {
self.stateLock.withLock {
self.state.failedConnectionAction()
}
}
switch action {
case .makeConnectionAndComplete(let el, let promise):
self.makeConnection(on: el).cascade(to: promise)
case .none:
break
}.map { connection in
self.configureCloseCallback(of: connection)
return connection
}.flatMapError { error in
// This promise may not have been completed if we reach this
// so we fail it to avoid any leak
handshakePromise.fail(error)
let action = self.parentPool.connectionProvidersLock.withLock {
self.stateLock.withLock {
self.state.failedConnectionAction()
}
return self.eventLoop.makeFailedFuture(error)
}
switch action {
case .makeConnectionAndComplete(let el, let promise):
self.makeConnection(on: el).cascade(to: promise)
case .none:
break
}
return self.eventLoop.makeFailedFuture(error)
}
}

Expand Down
9 changes: 4 additions & 5 deletions Sources/AsyncHTTPClient/HTTPClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -625,10 +625,10 @@ extension ChannelPipeline {
return addHandlers([encoder, decoder, handler])
}

func addSSLHandlerIfNeeded(for key: ConnectionPool.Key, tlsConfiguration: TLSConfiguration?, handshakePromise: EventLoopPromise<Void>) -> EventLoopFuture<Void> {
func addSSLHandlerIfNeeded(for key: ConnectionPool.Key, tlsConfiguration: TLSConfiguration?, handshakePromise: EventLoopPromise<Void>) {
guard key.scheme == .https else {
handshakePromise.succeed(())
return self.eventLoop.makeSucceededFuture(())
return
}

do {
Expand All @@ -638,10 +638,9 @@ extension ChannelPipeline {
try NIOSSLClientHandler(context: context, serverHostname: key.host.isIPAddress ? nil : key.host),
TLSEventsHandler(completionPromise: handshakePromise),
]

return self.addHandlers(handlers)
self.addHandlers(handlers).cascadeFailure(to: handshakePromise)
} catch {
return self.eventLoop.makeFailedFuture(error)
handshakePromise.fail(error)
}
}
}
Expand Down
1 change: 1 addition & 0 deletions Tests/AsyncHTTPClientTests/HTTPClientTests+XCTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ extension HTTPClientTests {
("testWeRecoverFromServerThatClosesTheConnectionOnUs", testWeRecoverFromServerThatClosesTheConnectionOnUs),
("testPoolClosesIdleConnections", testPoolClosesIdleConnections),
("testRacePoolIdleConnectionsAndGet", testRacePoolIdleConnectionsAndGet),
("testAvoidLeakingTLSHandshakeCompletionPromise", testAvoidLeakingTLSHandshakeCompletionPromise),
]
}
}
17 changes: 17 additions & 0 deletions Tests/AsyncHTTPClientTests/HTTPClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1656,4 +1656,21 @@ class HTTPClientTests: XCTestCase {
Thread.sleep(forTimeInterval: 0.01 + .random(in: -0.05...0.05))
}
}

func testAvoidLeakingTLSHandshakeCompletionPromise() {
let httpClient = HTTPClient(eventLoopGroupProvider: .createNew)
let httpBin = HTTPBin()
let port = httpBin.port
XCTAssertNoThrow(try httpBin.shutdown())
defer {
XCTAssertNoThrow(try httpClient.syncShutdown(requiresCleanClose: true))
}

XCTAssertThrowsError(try httpClient.get(url: "http://localhost:\(port)").wait()) { error in
guard error is NIOConnectionError else {
XCTFail("Unexpected error: \(error)")
return
}
}
}
}