Skip to content

Commit 2808c4f

Browse files
authored
Close connection if requestTLS fails (vapor#134)
* Close connection if requestTLS fails * Add test to ensure we don't hit assert from leaking connection
1 parent 2334eab commit 2808c4f

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

Sources/PostgresNIO/Connection/PostgresConnection+Connect.swift

+5-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@ extension PostgresConnection {
2626
using: tlsConfiguration,
2727
serverHostname: serverHostname,
2828
logger: logger
29-
).map { conn }
29+
).flatMapError { error in
30+
conn.close().flatMapThrowing {
31+
throw error
32+
}
33+
}.map { conn }
3034
} else {
3135
return eventLoop.makeSucceededFuture(conn)
3236
}

Tests/PostgresNIOTests/PostgresNIOTests.swift

+23
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,29 @@ final class PostgresNIOTests: XCTestCase {
619619
let version = rows[0].column("version")?.string
620620
XCTAssertEqual(version?.contains("PostgreSQL"), true)
621621
}
622+
623+
func testFailingTLSConnectionClosesConnection() throws {
624+
// There was a bug (https://github.com/vapor/postgres-nio/issues/133) where we would hit
625+
// an assert because we didn't close the connection. This test should succeed without hitting
626+
// the assert
627+
628+
// postgres://uymgphwj:7_tHbREdRwkqAdu4KoIS7hQnNxr8J1LA@elmer.db.elephantsql.com:5432/uymgphwj
629+
let elg = MultiThreadedEventLoopGroup(numberOfThreads: 1)
630+
defer { try! elg.syncShutdownGracefully() }
631+
632+
// We should get an error because you can't use an IP address for SNI, but we shouldn't bomb out by
633+
// hitting the assert
634+
XCTAssertThrowsError(
635+
try PostgresConnection.connect(
636+
to: SocketAddress.makeAddressResolvingHost("elmer.db.elephantsql.com", port: 5432),
637+
tlsConfiguration: .forClient(certificateVerification: .fullVerification),
638+
serverHostname: "34.228.73.168",
639+
on: elg.next()
640+
).wait()
641+
)
642+
// If we hit this, we're all good
643+
XCTAssertTrue(true)
644+
}
622645

623646
func testInvalidPassword() throws {
624647
let conn = try PostgresConnection.testUnauthenticated(on: eventLoop).wait()

0 commit comments

Comments
 (0)