diff --git a/Package.swift b/Package.swift index 755b40342..10c895f1b 100644 --- a/Package.swift +++ b/Package.swift @@ -59,6 +59,7 @@ let package = Package( .package(url: "https://github.com/awslabs/aws-crt-swift.git", exact: "0.54.2"), .package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"), .package(url: "https://github.com/open-telemetry/opentelemetry-swift", from: "1.13.0"), + .package(url: "https://github.com/swift-server/async-http-client.git", from: "1.26.0"), ] let isDocCEnabled = ProcessInfo.processInfo.environment["AWS_SWIFT_SDK_ENABLE_DOCC"] != nil @@ -97,6 +98,7 @@ let package = Package( "SmithyChecksums", "SmithyCBOR", .product(name: "AwsCommonRuntimeKit", package: "aws-crt-swift"), + .product(name: "AsyncHTTPClient", package: "async-http-client"), // Only include these on macOS, iOS, tvOS, watchOS, and macCatalyst (visionOS and Linux are excluded) .product( name: "InMemoryExporter", diff --git a/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClient.swift b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClient.swift new file mode 100644 index 000000000..90dd1c6f0 --- /dev/null +++ b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClient.swift @@ -0,0 +1,249 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AsyncHTTPClient +import NIOCore +import NIOHTTP1 +import NIOPosix +import NIOSSL +import struct Smithy.Attributes +import struct Smithy.SwiftLogger +import protocol Smithy.LogAgent +import struct SmithyHTTPAPI.Headers +import struct SmithyHTTPAPI.Header +import protocol SmithyHTTPAPI.HTTPClient +import class SmithyHTTPAPI.HTTPResponse +import class SmithyHTTPAPI.HTTPRequest +import enum SmithyHTTPAPI.HTTPStatusCode +import enum SmithyHTTPAPI.HTTPMethodType +import protocol Smithy.ReadableStream +import enum Smithy.ByteStream +import class SmithyStreams.BufferedStream +import struct Foundation.Date +import struct Foundation.URLComponents +import struct Foundation.URLQueryItem +import AwsCommonRuntimeKit + +/// AsyncHTTPClient-based HTTP client implementation that conforms to SmithyHTTPAPI.HTTPClient +/// This implementation is thread-safe and supports concurrent request execution. +public final class NIOHTTPClient: SmithyHTTPAPI.HTTPClient { + public static let noOpNIOHTTPClientTelemetry = HttpTelemetry( + httpScope: "NIOHTTPClient", + telemetryProvider: DefaultTelemetry.provider + ) + + private let client: AsyncHTTPClient.HTTPClient + private let config: HttpClientConfiguration + private let tlsConfiguration: NIOHTTPClientTLSOptions? + private let allocator: ByteBufferAllocator + + /// HTTP Client Telemetry + private let telemetry: HttpTelemetry + + /// Logger for HTTP-related events. + private var logger: LogAgent + + /// Creates a new `NIOHTTPClient`. + /// + /// The client is created with its own internal `AsyncHTTPClient`, which is configured with system defaults. + /// - Parameters: + /// - httpClientConfiguration: The configuration to use for the client's `AsyncHTTPClient` setup. + /// - eventLoopGroup: The `EventLoopGroup` that the ``HTTPClient`` will use. + public init( + httpClientConfiguration: HttpClientConfiguration, + eventLoopGroup: (any NIOCore.EventLoopGroup)? = nil + ) { + self.config = httpClientConfiguration + self.telemetry = httpClientConfiguration.telemetry ?? NIOHTTPClient.noOpNIOHTTPClientTelemetry + self.logger = self.telemetry.loggerProvider.getLogger(name: "NIOHTTPClient") + self.tlsConfiguration = httpClientConfiguration.tlsConfiguration as? NIOHTTPClientTLSOptions + self.allocator = ByteBufferAllocator() + + var clientConfig = AsyncHTTPClient.HTTPClient.Configuration.from( + httpClientConfiguration: httpClientConfiguration + ) + + // Configure TLS if options are provided + if let tlsOptions = tlsConfiguration { + do { + clientConfig.tlsConfiguration = try tlsOptions.makeNIOSSLConfiguration() + } catch { + // Log TLS configuration error but continue with default TLS settings + self.logger.error( + "Failed to configure TLS: \(String(describing: error)). Using default TLS configuration." + ) + } + } + + if let eventLoopGroup { + self.client = AsyncHTTPClient.HTTPClient(eventLoopGroup: eventLoopGroup, configuration: clientConfig) + } else { + self.client = AsyncHTTPClient.HTTPClient(configuration: clientConfig) + } + } + + deinit { + try? client.syncShutdown() + } + + public func send(request: SmithyHTTPAPI.HTTPRequest) async throws -> SmithyHTTPAPI.HTTPResponse { + let telemetryContext = telemetry.contextManager.current() + let tracer = telemetry.tracerProvider.getTracer( + scope: telemetry.tracerScope + ) + + // START - smithy.client.http.requests.queued_duration + let queuedStart = Date().timeIntervalSinceReferenceDate + let span = tracer.createSpan( + name: telemetry.spanName, + initialAttributes: telemetry.spanAttributes, + spanKind: SpanKind.internal, + parentContext: telemetryContext) + defer { + span.end() + } + + // START - smithy.client.http.connections.acquire_duration + let acquireConnectionStart = Date().timeIntervalSinceReferenceDate + + // Convert Smithy HTTPRequest to AsyncHTTPClient HTTPClientRequest + let nioRequest = try await makeNIORequest(from: request) + + let acquireConnectionEnd = Date().timeIntervalSinceReferenceDate + telemetry.connectionsAcquireDuration.record( + value: acquireConnectionEnd - acquireConnectionStart, + attributes: Attributes(), + context: telemetryContext) + // END - smithy.client.http.connections.acquire_duration + + let queuedEnd = acquireConnectionEnd + telemetry.requestsQueuedDuration.record( + value: queuedEnd - queuedStart, + attributes: Attributes(), + context: telemetryContext) + // END - smithy.client.http.requests.queued_duration + + // Update connection and request usage metrics + telemetry.updateHTTPMetricsUsage { httpMetricsUsage in + // TICK - smithy.client.http.connections.limit + // Note: AsyncHTTPClient doesn't expose connection pool configuration publicly + httpMetricsUsage.connectionsLimit = 0 + + // TICK - smithy.client.http.connections.usage + // Note: AsyncHTTPClient doesn't expose current connection counts + httpMetricsUsage.acquiredConnections = 0 + httpMetricsUsage.idleConnections = 0 + + // TICK - smithy.client.http.requests.usage + httpMetricsUsage.inflightRequests = httpMetricsUsage.acquiredConnections + httpMetricsUsage.queuedRequests = httpMetricsUsage.idleConnections + } + + // DURATION - smithy.client.http.connections.uptime + let connectionUptimeStart = acquireConnectionEnd + defer { + telemetry.connectionsUptime.record( + value: Date().timeIntervalSinceReferenceDate - connectionUptimeStart, + attributes: Attributes(), + context: telemetryContext) + } + + let httpMethod = request.method.rawValue + let url = request.destination.url + logger.debug("NIOHTTPClient(\(httpMethod) \(String(describing: url))) started") + logBodyDescription(request.body) + + do { + let timeout: TimeAmount = .seconds(Int64(config.socketTimeout)) + let nioResponse = try await client.execute(nioRequest, timeout: timeout) + + // Convert NIO response to Smithy HTTPResponse + let statusCode = HTTPStatusCode(rawValue: Int(nioResponse.status.code)) ?? .insufficientStorage + var headers = Headers() + for (name, value) in nioResponse.headers { + headers.add(name: name, value: value) + } + + let body = await NIOHTTPClientStreamBridge.convertResponseBody(from: nioResponse) + + let response = HTTPResponse(headers: headers, body: body, statusCode: statusCode) + logger.debug("NIOHTTPClient(\(httpMethod) \(String(describing: url))) succeeded") + + return response + } catch { + let urlDescription = String(describing: url) + let errorDescription = String(describing: error) + logger.error("NIOHTTPClient(\(httpMethod) \(urlDescription)) failed with error: \(errorDescription)") + throw error + } + } + + /// Create an AsyncHTTPClient request from a Smithy HTTPRequest + private func makeNIORequest( + from request: SmithyHTTPAPI.HTTPRequest + ) async throws -> AsyncHTTPClient.HTTPClientRequest { + var components = URLComponents() + components.scheme = config.protocolType?.rawValue ?? request.destination.scheme.rawValue + components.host = request.endpoint.uri.host + components.port = port(for: request) + components.percentEncodedPath = request.destination.path + if let queryItems = request.queryItems, !queryItems.isEmpty { + components.percentEncodedQueryItems = queryItems.map { + URLQueryItem(name: $0.name, value: $0.value) + } + } + guard let url = components.url else { throw NIOHTTPClientError.incompleteHTTPRequest } + + let method = NIOHTTP1.HTTPMethod(rawValue: request.method.rawValue) + var nioRequest = AsyncHTTPClient.HTTPClientRequest(url: url.absoluteString) + nioRequest.method = method + + // request headers will replace default if the same value is present in both + for header in config.defaultHeaders.headers + request.headers.headers { + for value in header.value { + nioRequest.headers.replaceOrAdd(name: header.name, value: value) + } + } + + nioRequest.body = try await NIOHTTPClientStreamBridge.convertRequestBody( + from: request.body, + allocator: allocator + ) + + return nioRequest + } + + private func port(for request: SmithyHTTPAPI.HTTPRequest) -> Int? { + switch (request.destination.scheme, request.destination.port) { + case (.https, 443), (.http, 80): + return nil + default: + return request.destination.port.map { Int($0) } + } + } + + private func logBodyDescription(_ body: ByteStream) { + switch body { + case .stream(let stream): + let lengthString: String + if let length = stream.length { + lengthString = "\(length) bytes" + } else { + lengthString = "unknown length" + } + logger.debug("body is Stream (\(lengthString))") + case .data(let data): + if let data { + logger.debug("body is Data (\(data.count) bytes)") + } else { + logger.debug("body is empty") + } + case .noStream: + logger.debug("body is empty") + } + } +} diff --git a/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientConfiguration+HTTPClientConfiguration.swift b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientConfiguration+HTTPClientConfiguration.swift new file mode 100644 index 000000000..2d6df4e77 --- /dev/null +++ b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientConfiguration+HTTPClientConfiguration.swift @@ -0,0 +1,40 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AsyncHTTPClient +import NIOCore + +extension HTTPClient.Configuration { + + static func from(httpClientConfiguration: HttpClientConfiguration) -> HTTPClient.Configuration { + let connect: TimeAmount? = httpClientConfiguration.connectTimeout != nil + ? .seconds(Int64(httpClientConfiguration.connectTimeout!)) + : nil + + let read: TimeAmount? = .seconds(Int64(httpClientConfiguration.socketTimeout)) + + let timeout = HTTPClient.Configuration.Timeout( + connect: connect, + read: read + ) + + let pool = HTTPClient.Configuration.ConnectionPool( + idleTimeout: .seconds(60), // default + concurrentHTTP1ConnectionsPerHostSoftLimit: httpClientConfiguration.maxConnections + ) + + return .init( + tlsConfiguration: nil, // TODO + redirectConfiguration: nil, + timeout: timeout, + connectionPool: pool, + proxy: nil, + ignoreUncleanSSLShutdown: false, + decompression: .disabled + ) + } +} diff --git a/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientError.swift b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientError.swift new file mode 100644 index 000000000..90a4660c5 --- /dev/null +++ b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientError.swift @@ -0,0 +1,18 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +/// Errors that are particular to the NIO-based Smithy HTTP client. +public enum NIOHTTPClientError: Error { + + /// A URL could not be formed from the `HTTPRequest`. + /// Please file a bug with aws-sdk-swift if you experience this error. + case incompleteHTTPRequest + + /// An error occurred during streaming operations. + /// Please file a bug with aws-sdk-swift if you experience this error. + case streamingError(Error) +} diff --git a/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientStreamBridge.swift b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientStreamBridge.swift new file mode 100644 index 000000000..89ca5dcea --- /dev/null +++ b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientStreamBridge.swift @@ -0,0 +1,137 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AsyncHTTPClient +import Foundation +import NIO +import Smithy +import SmithyStreams + +/// Handles streaming between Smithy streams and AsyncHTTPClient +final class NIOHTTPClientStreamBridge { + + /// Convert Smithy ByteStream to AsyncHTTPClient request body + static func convertRequestBody( + from body: ByteStream, + allocator: ByteBufferAllocator, + chunkSize: Int = CHUNK_SIZE_BYTES + ) async throws -> AsyncHTTPClient.HTTPClientRequest.Body { + switch body { + case .noStream: + // No body to send + return .bytes(allocator.buffer(capacity: 0)) + + case .data(let data): + // Convert Data to ByteBuffer + if let data = data { + var buffer = allocator.buffer(capacity: data.count) + buffer.writeBytes(data) + return .bytes(buffer) + } else { + return .bytes(allocator.buffer(capacity: 0)) + } + + case .stream(let stream): + // Handle streaming request body + return try await convertStreamToRequestBody(stream: stream, allocator: allocator, chunkSize: chunkSize) + } + } + + /// Convert AsyncHTTPClient response body to Smithy ByteStream + static func convertResponseBody( + from response: AsyncHTTPClient.HTTPClientResponse + ) async -> ByteStream { + let bufferedStream = BufferedStream() + + do { + var iterator = response.body.makeAsyncIterator() + while let buffer = try await iterator.next() { + // Convert ByteBuffer to Data and write to buffered stream + if let bytes = buffer.getBytes(at: buffer.readerIndex, length: buffer.readableBytes) { + let data = Data(bytes) + try bufferedStream.write(contentsOf: data) + } + } + bufferedStream.close() + } catch { + bufferedStream.closeWithError(error) + } + + return .stream(bufferedStream) + } + + /// Convert a Smithy Stream to AsyncHTTPClient request body + private static func convertStreamToRequestBody( + stream: Smithy.Stream, + allocator: ByteBufferAllocator, + chunkSize: Int = CHUNK_SIZE_BYTES + ) async throws -> AsyncHTTPClient.HTTPClientRequest.Body { + let asyncSequence = StreamToAsyncSequence(stream: stream, allocator: allocator, chunkSize: chunkSize) + + // Use known length if available, unless the stream is eligible for chunked streaming. + if let length = stream.length, !stream.isEligibleForChunkedStreaming { + return .stream(asyncSequence, length: .known(Int64(length))) + } else { + return .stream(asyncSequence, length: .unknown) + } + } +} + +/// AsyncSequence adapter that converts a Smithy Stream to ByteBuffer sequence for AsyncHTTPClient +internal struct StreamToAsyncSequence: AsyncSequence, Sendable { + typealias Element = ByteBuffer + + private let stream: Smithy.Stream + private let allocator: ByteBufferAllocator + private let chunkSize: Int + + init(stream: Smithy.Stream, allocator: ByteBufferAllocator, chunkSize: Int = CHUNK_SIZE_BYTES) { + self.stream = stream + self.allocator = allocator + self.chunkSize = chunkSize + } + + func makeAsyncIterator() -> AsyncIterator { + AsyncIterator(stream: stream, allocator: allocator, chunkSize: chunkSize) + } + + struct AsyncIterator: AsyncIteratorProtocol { + private let stream: Smithy.Stream + private let allocator: ByteBufferAllocator + private let chunkSize: Int + private var isFinished = false + + init(stream: Smithy.Stream, allocator: ByteBufferAllocator, chunkSize: Int) { + self.stream = stream + self.allocator = allocator + self.chunkSize = chunkSize + } + + mutating func next() async throws -> ByteBuffer? { + guard !isFinished else { return nil } + + do { + // Read a chunk from the stream (using configurable chunk size) + let data = try await stream.readAsync(upToCount: chunkSize) + + if let data = data, !data.isEmpty { + var buffer = allocator.buffer(capacity: data.count) + buffer.writeBytes(data) + return buffer + } else { + isFinished = true + stream.close() + return nil + } + } catch { + isFinished = true + stream.close() + throw NIOHTTPClientError.streamingError(error) + } + } + } +} diff --git a/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientTLSOptions.swift b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientTLSOptions.swift new file mode 100644 index 000000000..c4b40fe54 --- /dev/null +++ b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientTLSOptions.swift @@ -0,0 +1,52 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import NIOSSL + +public struct NIOHTTPClientTLSOptions: TLSConfiguration, Sendable { + + /// Optional path to a PEM certificate + public var certificate: String? + + /// Optional path to certificate directory + public var certificateDir: String? + + /// Optional path to a PEM format private key + public var privateKey: String? + + /// Optional path to PKCS #12 certificate, in PEM format + public var pkcs12Path: String? + + /// Optional PKCS#12 password + public var pkcs12Password: String? + + /// Information is provided to use custom trust store + public var useSelfSignedCertificate: Bool { + return certificate != nil || certificateDir != nil + } + + /// Information is provided to use custom key store + public var useProvidedKeystore: Bool { + return (pkcs12Path != nil && pkcs12Password != nil) || + (certificate != nil && privateKey != nil) + } + + public init( + certificate: String? = nil, + certificateDir: String? = nil, + privateKey: String? = nil, + pkcs12Path: String? = nil, + pkcs12Password: String? = nil + ) { + self.certificate = certificate + self.certificateDir = certificateDir + self.privateKey = privateKey + self.pkcs12Path = pkcs12Path + self.pkcs12Password = pkcs12Password + } +} diff --git a/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientTLSResolverUtils.swift b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientTLSResolverUtils.swift new file mode 100644 index 000000000..f404d3152 --- /dev/null +++ b/Sources/ClientRuntime/Networking/Http/NIO/NIOHTTPClientTLSResolverUtils.swift @@ -0,0 +1,85 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import NIOSSL + +extension NIOHTTPClientTLSOptions { + + func makeNIOSSLConfiguration() throws -> NIOSSL.TLSConfiguration { + var tlsConfig = NIOSSL.TLSConfiguration.makeClientConfiguration() + + if useSelfSignedCertificate { + if let certificateDir = certificateDir, let certificate = certificate { + let certificatePath = "\(certificateDir)/\(certificate)" + let certificates = try NIOHTTPClientTLSOptions.loadCertificates(from: certificatePath) + tlsConfig.trustRoots = .certificates(certificates) + } else if let certificate = certificate { + let certificates = try NIOHTTPClientTLSOptions.loadCertificates(from: certificate) + tlsConfig.trustRoots = .certificates(certificates) + } + } + + if useProvidedKeystore { + if let pkcs12Path = pkcs12Path, let pkcs12Password = pkcs12Password { + let bundle = try NIOHTTPClientTLSOptions.loadPKCS12Bundle(from: pkcs12Path, password: pkcs12Password) + tlsConfig.certificateChain = bundle.certificateChain.map { .certificate($0) } + tlsConfig.privateKey = .privateKey(bundle.privateKey) + } else if let certificate = certificate, let privateKey = privateKey { + let cert = try NIOHTTPClientTLSOptions.loadCertificate(from: certificate) + let key = try NIOHTTPClientTLSOptions.loadPrivateKey(from: privateKey) + tlsConfig.certificateChain = [.certificate(cert)] + tlsConfig.privateKey = .privateKey(key) + } + } + + return tlsConfig + } +} + +extension NIOHTTPClientTLSOptions { + + static func loadCertificates(from filePath: String) throws -> [NIOSSLCertificate] { + let fileData = try Data(contentsOf: URL(fileURLWithPath: filePath)) + return try NIOSSLCertificate.fromPEMBytes(Array(fileData)) + } + + static func loadCertificate(from filePath: String) throws -> NIOSSLCertificate { + let certificates = try loadCertificates(from: filePath) + guard let certificate = certificates.first else { + throw NIOHTTPClientTLSError.noCertificateFound(filePath) + } + return certificate + } + + static func loadPrivateKey(from filePath: String) throws -> NIOSSLPrivateKey { + let fileData = try Data(contentsOf: URL(fileURLWithPath: filePath)) + return try NIOSSLPrivateKey(bytes: Array(fileData), format: .pem) + } + + static func loadPKCS12Bundle(from filePath: String, password: String) throws -> NIOSSLPKCS12Bundle { + do { + return try NIOSSLPKCS12Bundle(file: filePath, passphrase: password.utf8) + } catch { + throw NIOHTTPClientTLSError.invalidPKCS12(filePath, underlying: error) + } + } +} + +public enum NIOHTTPClientTLSError: Error, LocalizedError { + case noCertificateFound(String) + case invalidPKCS12(String, underlying: Error) + + public var errorDescription: String? { + switch self { + case .noCertificateFound(let path): + return "No certificate found at path: \(path)" + case .invalidPKCS12(let path, let underlying): + return "Failed to load PKCS#12 file at path: \(path). Error: \(String(describing: underlying))" + } + } +} diff --git a/Tests/ClientRuntimeTests/NetworkingTests/Http/NIO/NIOHTTPClientStreamBridgeTests.swift b/Tests/ClientRuntimeTests/NetworkingTests/Http/NIO/NIOHTTPClientStreamBridgeTests.swift new file mode 100644 index 000000000..9f64d9e45 --- /dev/null +++ b/Tests/ClientRuntimeTests/NetworkingTests/Http/NIO/NIOHTTPClientStreamBridgeTests.swift @@ -0,0 +1,148 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import AsyncHTTPClient +import Foundation +import NIO +import SmithyTestUtil +import XCTest +import class SmithyStreams.BufferedStream +import enum Smithy.LogAgentLevel +import protocol Smithy.LogAgent +import enum Smithy.ByteStream +@testable import ClientRuntime + +class NIOHTTPClientStreamBridgeTests: XCTestCase { + let allocator = ByteBufferAllocator() + + func test_convertResponseBody_streamsAllDataCorrectly() async throws { + + // The maximum size of input streaming data in the tests + let maxDataSize = 65_536 // 64 kb + + // Create & fill a buffer with random bytes, for use in later test setup + // Random buffer is reused because creating random data is slow + // We are responsible for deallocating it + let randomBuffer = UnsafeMutablePointer.allocate(capacity: maxDataSize) + defer { randomBuffer.deallocate() } + + for i in 0...allocate(capacity: dataSize) + defer { randomBuffer.deallocate() } + + for i in 0.. Data { + switch byteStream { + case .stream(let stream): + return try await stream.readToEndAsync() ?? Data() + case .data(let data): + return data ?? Data() + case .noStream: + return Data() + } + } +} + +private extension Data { + init(buffer: ByteBuffer) { + if let bytes = buffer.getBytes(at: buffer.readerIndex, length: buffer.readableBytes) { + self.init(bytes) + } else { + self.init() + } + } +} diff --git a/Tests/ClientRuntimeTests/NetworkingTests/Http/NIO/NIOHTTPClientTLSOptionsTests.swift b/Tests/ClientRuntimeTests/NetworkingTests/Http/NIO/NIOHTTPClientTLSOptionsTests.swift new file mode 100644 index 000000000..e26d8db1f --- /dev/null +++ b/Tests/ClientRuntimeTests/NetworkingTests/Http/NIO/NIOHTTPClientTLSOptionsTests.swift @@ -0,0 +1,65 @@ +// +// Copyright Amazon.com Inc. or its affiliates. +// All Rights Reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + +import Foundation +import XCTest +@testable import ClientRuntime + +class NIOHTTPClientTLSOptionsTests: XCTestCase { + + func test_init_withDefaults() { + let tlsOptions = NIOHTTPClientTLSOptions() + + XCTAssertNil(tlsOptions.certificate) + XCTAssertNil(tlsOptions.certificateDir) + XCTAssertNil(tlsOptions.privateKey) + XCTAssertNil(tlsOptions.pkcs12Path) + XCTAssertNil(tlsOptions.pkcs12Password) + XCTAssertFalse(tlsOptions.useSelfSignedCertificate) + XCTAssertFalse(tlsOptions.useProvidedKeystore) + } + + func test_init_withCertificate() { + let tlsOptions = NIOHTTPClientTLSOptions(certificate: "/path/to/cert.pem") + + XCTAssertEqual(tlsOptions.certificate, "/path/to/cert.pem") + XCTAssertTrue(tlsOptions.useSelfSignedCertificate) + XCTAssertFalse(tlsOptions.useProvidedKeystore) + } + + func test_init_withCertificateDir() { + let tlsOptions = NIOHTTPClientTLSOptions(certificateDir: "/path/to/certs/") + + XCTAssertEqual(tlsOptions.certificateDir, "/path/to/certs/") + XCTAssertTrue(tlsOptions.useSelfSignedCertificate) + XCTAssertFalse(tlsOptions.useProvidedKeystore) + } + + func test_init_withPKCS12() { + let tlsOptions = NIOHTTPClientTLSOptions( + pkcs12Path: "/path/to/cert.p12", + pkcs12Password: "password" + ) + + XCTAssertEqual(tlsOptions.pkcs12Path, "/path/to/cert.p12") + XCTAssertEqual(tlsOptions.pkcs12Password, "password") + XCTAssertFalse(tlsOptions.useSelfSignedCertificate) + XCTAssertTrue(tlsOptions.useProvidedKeystore) + } + + func test_init_withCertificateAndPrivateKey() { + let tlsOptions = NIOHTTPClientTLSOptions( + certificate: "/path/to/cert.pem", + privateKey: "/path/to/key.pem" + ) + + XCTAssertEqual(tlsOptions.certificate, "/path/to/cert.pem") + XCTAssertEqual(tlsOptions.privateKey, "/path/to/key.pem") + XCTAssertTrue(tlsOptions.useSelfSignedCertificate) + XCTAssertTrue(tlsOptions.useProvidedKeystore) + } +}