Skip to content
Open
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
19 changes: 19 additions & 0 deletions AudioStreaming/Core/Network/NetworkSessionDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@
import Foundation
import OSLog

/// Provides a `URLCredential` in response to a client-certificate authentication challenge,
/// or `nil` to fall back to the system's default handling. Used to support mutual TLS (mTLS)
/// against servers that sit behind a client-certificate-authenticated proxy.
public typealias ClientCertificateProvider = (URLAuthenticationChallenge) -> URLCredential?

final class NetworkSessionDelegate: NSObject, URLSessionDataDelegate {
weak var taskProvider: StreamTaskProvider?
var clientCertificateProvider: ClientCertificateProvider?

func stream(for task: URLSessionTask) -> NetworkDataStream? {
guard let taskProvider = taskProvider else {
Expand Down Expand Up @@ -50,4 +56,17 @@ final class NetworkSessionDelegate: NSObject, URLSessionDataDelegate {
stream.didReceive(response: response as? HTTPURLResponse)
completionHandler(.allow)
}

func urlSession(_: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate,
let credential = clientCertificateProvider?(challenge)
else {
completionHandler(.performDefaultHandling, nil)
return
}
completionHandler(.useCredential, credential)
}
}
4 changes: 3 additions & 1 deletion AudioStreaming/Core/Network/NetworkingClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,10 @@ final class NetworkingClient {

init(configuration: URLSessionConfiguration = .networkingConfiguration,
delegate: NetworkSessionDelegate = NetworkSessionDelegate(),
networkQueue: DispatchQueue = DispatchQueue(label: "audio.streaming.session.network.queue"))
networkQueue: DispatchQueue = DispatchQueue(label: "audio.streaming.session.network.queue"),
clientCertificateProvider: ClientCertificateProvider? = nil)
{
delegate.clientCertificateProvider = clientCertificateProvider
let delegateQueue = operationQueue(underlyingQueue: networkQueue)
let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: delegateQueue)
self.session = session
Expand Down
5 changes: 3 additions & 2 deletions AudioStreaming/Streaming/AudioPlayer/AudioPlayer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ open class AudioPlayer {
/// Tracks the current loop iteration (how many times we've looped so far)
private var currentLoopIteration: Int = 0

public init(configuration: AudioPlayerConfiguration = .default) {
public init(configuration: AudioPlayerConfiguration = .default,
clientCertificateProvider: ClientCertificateProvider? = nil) {
self.configuration = configuration.normalizeValues()
let engine = AVAudioEngine()
audioEngine = engine
Expand All @@ -195,7 +196,7 @@ open class AudioPlayer {
sourceQueue = DispatchQueue(label: "source.queue", qos: .default)

entryProvider = AudioEntryProvider(
networkingClient: NetworkingClient(),
networkingClient: NetworkingClient(clientCertificateProvider: clientCertificateProvider),
underlyingQueue: sourceQueue,
outputAudioFormat: outputAudioFormat
)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import XCTest
@testable import AudioStreaming

final class ClientCertificateChallengeTests: XCTestCase {
private final class NoopChallengeSender: NSObject, URLAuthenticationChallengeSender {
func use(_ credential: URLCredential, for challenge: URLAuthenticationChallenge) {}
func continueWithoutCredential(for challenge: URLAuthenticationChallenge) {}
func cancel(_ challenge: URLAuthenticationChallenge) {}
}

private func makeChallenge(authenticationMethod: String) -> URLAuthenticationChallenge {
let space = URLProtectionSpace(host: "localhost", port: 443, protocol: "https",
realm: nil, authenticationMethod: authenticationMethod)
return URLAuthenticationChallenge(protectionSpace: space, proposedCredential: nil,
previousFailureCount: 0, failureResponse: nil,
error: nil, sender: NoopChallengeSender())
}

private func respond(_ delegate: NetworkSessionDelegate,
to challenge: URLAuthenticationChallenge)
-> (URLSession.AuthChallengeDisposition, URLCredential?) {
var disposition: URLSession.AuthChallengeDisposition!
var credential: URLCredential?
delegate.urlSession(URLSession.shared, didReceive: challenge) { d, c in
disposition = d
credential = c
}
return (disposition, credential)
}

func test_clientCertificateChallenge_usesProvidedCredential() {
let expected = URLCredential(user: "u", password: "p", persistence: .forSession)
let delegate = NetworkSessionDelegate()
delegate.clientCertificateProvider = { _ in expected }

let (disposition, credential) = respond(delegate,
to: makeChallenge(authenticationMethod: NSURLAuthenticationMethodClientCertificate))

XCTAssertEqual(disposition, .useCredential)
XCTAssertTrue(credential === expected)
}

func test_clientCertificateChallenge_providerReturnsNil_fallsBackToDefault() {
let delegate = NetworkSessionDelegate()
delegate.clientCertificateProvider = { _ in nil }

let (disposition, credential) = respond(delegate,
to: makeChallenge(authenticationMethod: NSURLAuthenticationMethodClientCertificate))

XCTAssertEqual(disposition, .performDefaultHandling)
XCTAssertNil(credential)
}

func test_noProvider_fallsBackToDefault() {
let delegate = NetworkSessionDelegate()

let (disposition, credential) = respond(delegate,
to: makeChallenge(authenticationMethod: NSURLAuthenticationMethodClientCertificate))

XCTAssertEqual(disposition, .performDefaultHandling)
XCTAssertNil(credential)
}

func test_serverTrustChallenge_doesNotConsultProvider() {
var providerCalled = false
let delegate = NetworkSessionDelegate()
delegate.clientCertificateProvider = { _ in
providerCalled = true
return URLCredential(user: "u", password: "p", persistence: .forSession)
}

let (disposition, credential) = respond(delegate,
to: makeChallenge(authenticationMethod: NSURLAuthenticationMethodServerTrust))

XCTAssertEqual(disposition, .performDefaultHandling)
XCTAssertNil(credential)
XCTAssertFalse(providerCalled)
}
}
51 changes: 51 additions & 0 deletions AudioStreamingTests/Core/Network/MockHTTPServer.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import Foundation
import Network

/// A minimal local HTTP/1.1 server for tests: binds an ephemeral loopback port
/// and answers every request with 200 OK and a small JSON body. Plain HTTP (no
/// TLS) so requests through the production `NetworkingClient` connect without a
/// server-trust challenge.
final class MockHTTPServer {
private let listener: NWListener
private let queue = DispatchQueue(label: "mock.http.server")
private let body: String
private(set) var port: UInt16 = 0

init(body: String = #"{"status":"ok"}"#) throws {
self.body = body
let params = NWParameters.tcp
params.allowLocalEndpointReuse = true
listener = try NWListener(using: params, on: .any)
}

func start() throws {
let ready = DispatchSemaphore(value: 0)
listener.stateUpdateHandler = { state in
if case .ready = state { ready.signal() }
}
listener.newConnectionHandler = { [weak self] connection in
self?.handle(connection)
}
listener.start(queue: queue)
_ = ready.wait(timeout: .now() + 5)
port = listener.port?.rawValue ?? 0
}

func stop() {
listener.cancel()
}

private func handle(_ connection: NWConnection) {
connection.start(queue: queue)
connection.receive(minimumIncompleteLength: 1, maximumLength: 65536) { [body, weak connection] _, _, _, _ in
guard let connection else { return }
let response = "HTTP/1.1 200 OK\r\n"
+ "Content-Type: application/json\r\n"
+ "Content-Length: \(body.utf8.count)\r\n"
+ "Connection: close\r\n\r\n"
+ body
connection.send(content: response.data(using: .utf8),
completion: .contentProcessed { _ in connection.cancel() })
}
}
}
75 changes: 75 additions & 0 deletions AudioStreamingTests/Core/Network/MutualTLSIntegrationTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import XCTest
import Security
@testable import AudioStreaming

final class MutualTLSIntegrationTests: XCTestCase {
private var bundle: TestCertificateBundle!
private var server: MockMutualTLSServer!

override func setUpWithError() throws {
try XCTSkipUnless(TestCertificateBundle.isOpenSSLAvailable,
"openssl not available at /usr/bin/openssl")
bundle = try TestCertificateBundle.generate()
server = try MockMutualTLSServer(serverIdentity: bundle.serverIdentity,
caCertificate: bundle.caCertificate)
try server.start()
XCTAssertGreaterThan(server.port, 0, "server failed to bind a port")
}

override func tearDownWithError() throws {
server?.stop()
bundle?.cleanup()
}

func test_certificateBundle_importsIdentities() throws {
XCTAssertNotNil(bundle.clientCredential.identity)
}

func test_requestSucceeds_whenClientCertificateProvided() throws {
let inner = NetworkSessionDelegate()
let credential = bundle.clientCredential
inner.clientCertificateProvider = { _ in credential }
let delegate = TrustingSessionDelegate(caCertificate: bundle.caCertificate, inner: inner)
let session = URLSession(configuration: .ephemeral, delegate: delegate, delegateQueue: nil)
defer { session.invalidateAndCancel() }

let url = URL(string: "https://localhost:\(server.port)/")!
let done = expectation(description: "request completes")
var statusCode: Int?
var body: String?
var requestError: Error?
session.dataTask(with: url) { data, response, error in
statusCode = (response as? HTTPURLResponse)?.statusCode
body = data.flatMap { String(data: $0, encoding: .utf8) }
requestError = error
done.fulfill()
}.resume()
wait(for: [done], timeout: 15)

XCTAssertNil(requestError)
XCTAssertEqual(statusCode, 200)
XCTAssertEqual(body, "ok")
}

func test_requestFails_whenClientCertificateMissing() throws {
let inner = NetworkSessionDelegate()
inner.clientCertificateProvider = { _ in nil }
let delegate = TrustingSessionDelegate(caCertificate: bundle.caCertificate, inner: inner)
let session = URLSession(configuration: .ephemeral, delegate: delegate, delegateQueue: nil)
defer { session.invalidateAndCancel() }

let url = URL(string: "https://localhost:\(server.port)/")!
let done = expectation(description: "request completes")
var statusCode: Int?
var requestError: Error?
session.dataTask(with: url) { _, response, error in
statusCode = (response as? HTTPURLResponse)?.statusCode
requestError = error
done.fulfill()
}.resume()
wait(for: [done], timeout: 15)

XCTAssertNotNil(requestError, "handshake should fail without a client certificate")
XCTAssertNotEqual(statusCode, 200)
}
}
23 changes: 19 additions & 4 deletions AudioStreamingTests/Core/Network/NetworkingClientTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,22 @@
import XCTest
@testable import AudioStreaming

class NetworkingClientTests: XCTestCase {
final class NetworkingClientTests: XCTestCase {
private var server: MockHTTPServer!

override func setUpWithError() throws {
try super.setUpWithError()
server = try MockHTTPServer()
try server.start()
XCTAssertGreaterThan(server.port, 0, "server failed to bind a port")
}

override func tearDownWithError() throws {
server?.stop()
server = nil
try super.tearDownWithError()
}

func testInitialiseCorrectly() throws {
let networking = NetworkingClient()

Expand All @@ -28,9 +43,9 @@ class NetworkingClientTests: XCTestCase {
XCTAssertTrue(networking.networkQueue == queue)
}

func testShouldStartRequestImmediatelly() {
func testShouldStartRequestImmediatelly() throws {
let networking = NetworkingClient()
let url = URL(string: "https://httpbun.com/get")!
let url = URL(string: "http://127.0.0.1:\(server.port)/get")!
let request = URLRequest(url: url)

let expectation = self.expectation(description: "\(url)")
Expand Down Expand Up @@ -58,8 +73,8 @@ class NetworkingClientTests: XCTestCase {

waitForExpectations(timeout: 10, handler: nil)

XCTAssertEqual(responseCompletion?.response?.statusCode, 200)
XCTAssertNotNil(responseCompletion)
XCTAssertEqual(responseCompletion?.response?.statusCode, 200)
XCTAssertNotNil(receivedData)
}
}
Loading