Alamofire 5 alternative to sessionDidReceiveChallenge - ios

I have just shifted to Alamofire 5.
Earlier I used URLSession and Certificate Pinner and to handle auth challenge I used delegate method of URLSessionDelegate with hash values
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
print("being challanged! for \(challenge.protectionSpace.host)")
guard let trust = challenge.protectionSpace.serverTrust else {
print("invalid trust!")
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let credential = URLCredential(trust: trust)
let pinner = setupCertificatePinner(host: challenge.protectionSpace.host)
if (!pinner.validateCertificateTrustChain(trust)) {
print("failed: invalid certificate chain!")
challenge.sender?.cancel(challenge)
}
if (pinner.validateTrustPublicKeys(trust)) {
completionHandler(.useCredential, credential)
} else {
didPinningFailed = true
print("couldn't validate trust for \(challenge.protectionSpace.host)")
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
Having moved to Alamofire 5, there is no method sessionDidReceiveChallenge which was available in earlier version.
I tried:
private let session: Session = {
let manager = ServerTrustManager(allHostsMustBeEvaluated: true, evaluators:
["devDomain.com": DisabledTrustEvaluator(),
"prodDomain.com": PublicKeysTrustEvaluator()])
let configuration = URLSessionConfiguration.af.default
return Session(configuration: configuration, serverTrustManager: manager)
}()
But I get error:
Error Domain=Alamofire.AFError Code=11 "Server trust evaluation failed due to reason: No public keys were found or provided for evaluation."
Update:
I'd still prefer a way to parse it using 256 fingerprint only, as we get domains and its hashes in first api call.

First you need a ServerTrustEvaluating that handle the certificate pinning a simple implement would be something similar to
public final class CertificatePinnerTrustEvaluator: ServerTrustEvaluating {
public init() {}
func setupCertificatePinner(host: String) -> CertificatePinner {
//get the CertificatePinner
}
public func evaluate(_ trust: SecTrust, forHost host: String) throws {
let pinner = setupCertificatePinner(host: host)
if (!pinner.validateCertificateTrustChain(trust)) {
print("failed: invalid certificate chain!")
throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
}
if (!pinner.validateTrustPublicKeys(trust)) {
print ("couldn't validate trust for \(host)")
throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound)
}
}
}
To be able to use the same evaluator I would suggest to subclass ServerTrustManager to return the same evaluator I did it like this:
class CertificatePinnerServerTrustManager: ServerTrustManager {
let evaluator = CertificatePinnerTrustEvaluator()
init() {
super.init(allHostsMustBeEvaluated: true, evaluators: [:])
}
open override func serverTrustEvaluator(forHost host: String) throws -> ServerTrustEvaluating? {
return evaluator
}
}
after that you should be ready to go by creating the session and passing the manager to it
private let session: Session = {
let trustManager = CertificatePinnerServerTrustManager()
return Session(serverTrustManager: trustManager)
}()
My reference was the method urlSession(_:task:didReceive:completionHandler:) in Alamofire source in SessionDelegate.swift at line 86 (Alamofire V5.2.1)

If you want to pin with public keys you need to provide the certificates from which to parse those public keys in the bundle of your app, or otherwise provide them to PublicKeysTrustEvaluator.

Related

How can I retry failed requests using alamofire?

I append failed requests to queue manager (contains array) in case of no connection
I'm presenting a custom pop-up with a retry button. When the retry button is pressed, I want to retry the requests that cannot be sent in the no connection state. There may be more than one request.
When I try the retryRequest method from Alamofire Session class, the task state of the request remains in the initilazed or finished state, but it must be resumed in order to send the request successfully, how can I solve this situation?
InterceptorInterface.swift
public func didGetNoInternetConnection() {
let viewModel = AppPopupViewModel(title: L10n.AppPopUp.areYouOffline, description: L10n.AppPopUp.checkInternetConnection, image: Images.noInternetConnection.image, firstButtonTitle: L10n.General.tryAgain, secondButtonTitle: nil, firstButtonAction: { [weak self] in
guard let self = self else { return }
DispatchQueue.main.async {
self.retry()
}
}, secondButtonAction: nil, dismissCompletion: nil, dimColor: Colors.appGray.color.withAlphaComponent(0.8), showCloseButton: true, customView: nil)
DispatchQueue.main.async {
AppPopupManager.show(with: viewModel, completion: nil)
}
}
private func retry() {
guard let head = NetworkRequestStorage.shared.head else {
return
}
let request = head.request
let session = head.session
session.retryRequest(request, withDelay: nil)
}
APIInterceptor.swift
final class APIInterceptor: Alamofire.RequestInterceptor {
private let configure: NetworkConfigurable
private var lock = NSLock()
// MARK: - Initilize
internal init(configure: NetworkConfigurable) {
self.configure = configure
}
// MARK: - Request Interceptor Method
internal func adapt(_ urlRequest: URLRequest, for session: Session, completion: #escaping (Result<URLRequest, Error>) -> Void) {
lock.lock()
defer {
lock.unlock()
}
var urlRequest = urlRequest
if let token = self.configure.accessToken {
/// Set the Authorization header value using the access token.
urlRequest.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
}
// Set Accept-Language header value using language code
urlRequest.setValue(configure.languageCode, forHTTPHeaderField: "Accept-Language")
// Arrange Request logs for develope and staging environment
if let reachability = NetworkReachabilityManager(), !reachability.isReachable {
configure.didGetNoInternetConnection()
completion(.failure(APIClientError.networkError))
}
completion(.success(urlRequest))
}
// MARK: - Error Retry Method
internal func retry(_ request: Request, for session: Session, dueTo error: Error, completion: #escaping (RetryResult) -> Void) {
// Arrange Error logs for develope and staging environment
if let aError = error as? APIClientError, aError.statusCode == 400 { // no connection state
NetworkRequestStorage.shared.enqueue(request: request, session: session)
completion(.doNotRetryWithError(error))
} else {
request.retryCount <= configure.retryCount ? completion(.retry) : completion(.doNotRetryWithError(error))
}
}
}
If the request is successful or there is no connection error, I remove it from the NetworkRequestStoroge class.

Unable to attach debugger to Network Extension iOS ("Waiting to Attach")

I'm new to iOS development, and am writing a VPN app, using the OpenVPN framework. I'm making use of the Network Extension target to tunnel network traffic to our OpenVPN server. However, when trying to debug, I can't attach the debugger to the Network Extension - it's stuck at "Waiting to Attach" in the Debug Navigator view.
In this blog post by Alex Grebenyuk he gives some recommendations for troubleshooting when you fail to attach the debugger to the extension. I've meticulously checked all of them, and my app correctly uses everything there: Both the app and the network extension have the Packet Tunnel Network Extension capability and bundle names all work out.
Some more info on the bundle names in case it might be relevant:
Bundle name for the app: com.example.Example-App
Bundle name for the Network Extension: com.example.Example-App.Example-VPN
Group name: group.com.example.Example-App
I'm out of ideas here. Could the problem be in the Network Extension never being started? It doesn't seem to be the case, because the startTunnel() function is called. The code for starting the VPN through the extension:
func configureVPN(serverAddress: String) {
guard let configData = readTestFile() else { return }
// Test file with ovpn configuration seems is read in correctly - contents are shown if printed to console.
self.providerManager?.loadFromPreferences { error in
if error == nil {
let tunnelProtocol = NETunnelProviderProtocol()
tunnelProtocol.serverAddress = serverAddress
tunnelProtocol.providerBundleIdentifier = "com.example.Example-App.Example-VPN" // bundle id of the network extension target
tunnelProtocol.providerConfiguration = ["ovpn": configData]
self.providerManager.protocolConfiguration = tunnelProtocol
self.providerManager.localizedDescription = "Example VPN"
self.providerManager.isEnabled = true
self.providerManager.saveToPreferences(completionHandler: { (error) in
if error == nil {
self.providerManager.loadFromPreferences(completionHandler: { (error) in
do {
print("Trying to start connection now") // This line is printed to the Console
try self.providerManager.connection.startVPNTunnel() // start the VPN tunnel.
} catch let error {
print(error.localizedDescription)
}
})
}
})
}
}
}
Not sure if this is relevant information, but I am using the OpenVPNAdapter in the PacketTunnelProvider, following this tutorial:
import NetworkExtension
import OpenVPNAdapter
class PacketTunnelProvider: NEPacketTunnelProvider {
lazy var vpnAdapter: OpenVPNAdapter = {
let adapter = OpenVPNAdapter()
adapter.delegate = self
return adapter
}()
let vpnReachability = OpenVPNReachability()
var startHandler: ((Error?) -> Void)?
var stopHandler: (() -> Void)?
override func startTunnel(
options: [String : NSObject]?,
completionHandler: #escaping (Error?) -> Void
) {
// There are many ways to provide OpenVPN settings to the tunnel provider. For instance,
// you can use `options` argument of `startTunnel(options:completionHandler:)` method or get
// settings from `protocolConfiguration.providerConfiguration` property of `NEPacketTunnelProvider`
// class. Also you may provide just content of a ovpn file or use key:value pairs
// that may be provided exclusively or in addition to file content.
// In our case we need providerConfiguration dictionary to retrieve content
// of the OpenVPN configuration file. Other options related to the tunnel
// provider also can be stored there.
guard
let protocolConfiguration = protocolConfiguration as? NETunnelProviderProtocol,
let providerConfiguration = protocolConfiguration.providerConfiguration
else {
fatalError()
}
guard let ovpnFileContent: Data = providerConfiguration["ovpn"] as? Data else {
fatalError()
}
let configuration = OpenVPNConfiguration()
configuration.fileContent = ovpnFileContent
configuration.settings = [ :
// Additional parameters as key:value pairs may be provided here
]
// Uncomment this line if you want to keep TUN interface active during pauses or reconnections
// configuration.tunPersist = true
// Apply OpenVPN configuration
let evaluation: OpenVPNConfigurationEvaluation
do {
evaluation = try vpnAdapter.apply(configuration: configuration)
} catch {
completionHandler(error)
return
}
// Provide credentials if needed
if !evaluation.autologin {
// If your VPN configuration requires user credentials you can provide them by
// `protocolConfiguration.username` and `protocolConfiguration.passwordReference`
// properties. It is recommended to use persistent keychain reference to a keychain
// item containing the password.
guard let username: String = protocolConfiguration.username else {
fatalError()
}
// Retrieve a password from the keychain
let password: String = "Test"
let credentials = OpenVPNCredentials()
credentials.username = username
credentials.password = password
do {
try vpnAdapter.provide(credentials: credentials)
} catch {
completionHandler(error)
return
}
}
// Checking reachability. In some cases after switching from cellular to
// WiFi the adapter still uses cellular data. Changing reachability forces
// reconnection so the adapter will use actual connection.
vpnReachability.startTracking { [weak self] status in
guard status == .reachableViaWiFi else { return }
self?.vpnAdapter.reconnect(afterTimeInterval: 5)
}
// Establish connection and wait for .connected event
startHandler = completionHandler
vpnAdapter.connect(using: packetFlow as! OpenVPNAdapterPacketFlow)
}
override func stopTunnel(
with reason: NEProviderStopReason,
completionHandler: #escaping () -> Void
) {
stopHandler = completionHandler
if vpnReachability.isTracking {
vpnReachability.stopTracking()
}
vpnAdapter.disconnect()
}
}
extension PacketTunnelProvider: OpenVPNAdapterDelegate {
// OpenVPNAdapter calls this delegate method to configure a VPN tunnel.
// `completionHandler` callback requires an object conforming to `OpenVPNAdapterPacketFlow`
// protocol if the tunnel is configured without errors. Otherwise send nil.
// `OpenVPNAdapterPacketFlow` method signatures are similar to `NEPacketTunnelFlow` so
// you can just extend that class to adopt `OpenVPNAdapterPacketFlow` protocol and
// send `self.packetFlow` to `completionHandler` callback.
func openVPNAdapter(
_ openVPNAdapter: OpenVPNAdapter,
configureTunnelWithNetworkSettings networkSettings: NEPacketTunnelNetworkSettings?,
completionHandler: #escaping (Error?) -> Void
) {
// In order to direct all DNS queries first to the VPN DNS servers before the primary DNS servers
// send empty string to NEDNSSettings.matchDomains
networkSettings?.dnsSettings?.matchDomains = [""]
// Set the network settings for the current tunneling session.
setTunnelNetworkSettings(networkSettings, completionHandler: completionHandler)
}
// Process events returned by the OpenVPN library
func openVPNAdapter(
_ openVPNAdapter: OpenVPNAdapter,
handleEvent event:
OpenVPNAdapterEvent, message: String?
) {
switch event {
case .connected:
if reasserting {
reasserting = false
}
guard let startHandler = startHandler else { return }
startHandler(nil)
self.startHandler = nil
case .disconnected:
guard let stopHandler = stopHandler else { return }
if vpnReachability.isTracking {
vpnReachability.stopTracking()
}
stopHandler()
self.stopHandler = nil
case .reconnecting:
reasserting = true
default:
break
}
}
// Handle errors thrown by the OpenVPN library
func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleError error: Error) {
// Handle only fatal errors
guard let fatal = (error as NSError).userInfo[OpenVPNAdapterErrorFatalKey] as? Bool,
fatal == true else { return }
if vpnReachability.isTracking {
vpnReachability.stopTracking()
}
if let startHandler = startHandler {
startHandler(error)
self.startHandler = nil
} else {
cancelTunnelWithError(error)
}
}
}
Any help with this would be hugely appreciated! Thanks.
You need to attache the bundle name and not the bundle identifier and the bundle name should not be an identifier. The PRODUCT_BUNDLE_IDENTIFIER of your network extension would be something like com.example.my-network-extension-id (it cannot be com.example.Example-App.Example-VPN, as a third period is not allowed for network extension IDs) and the PRODUCT_NAME would be something like My Network Extension, and you would then attach to My Network Extension (yes, with spaces and no extension).

Missing sessionDidReceiveChallenge in Alamofire 5 delegate

I need to migrate from Alamofire 4 to 5 but I'm missing sessionDidReceiveChallenge callback on the delegate
I used before in version 4 something like this:
let manager = Alamofire.SessionManager(
configuration: URLSessionConfiguration.default
)
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
let method = challenge.protectionSpace.authenticationMethod
if method == NSURLAuthenticationMethodClientCertificate {
return (.useCredential, self.cert.urlCredential())
}
if method == NSURLAuthenticationMethodServerTrust {
let trust = challenge.protectionSpace.serverTrust!
let credential = URLCredential(trust: trust)
return (.useCredential, credential)
}
return (.performDefaultHandling, Optional.none)
}
but now is version 5 the delegate has changed to SessionDelegate class without providing a similar function
I tried to use the delegate from the URLSession like this:
let delegate = SomeSessionDelegate()
let delegateQueue: OperationQueue = .init()
delegateQueue.underlyingQueue = .global(qos: .background)
let session = URLSession(
configuration: URLSessionConfiguration.af.default,
delegate: delegate,
delegateQueue: delegateQueue
)
let manager = Alamofire.Session(
session: session,
delegate: SessionDelegate(),
rootQueue: .global(qos: .background)
)
class SomeSessionDelegate: NSObject, URLSessionDelegate {
let cert = ...
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//same impl as before
}
}
I'm guessing that my implementation in version 5 is wrong because I stopped getting response callback
Please advise on how to manage the request challenge properly in version 5
It isn't necessary to override the SessionDelegate to use client certificates. Alamofire will automatically use an attached URLCredential for client certificate challenges. Just attach the credential to the request:
AF.request(...)
.authenticate(with: clientCertCredential)
.response...
Also, your server trust check will return any trust as valid, which could be a security issue. I'd stop using that code immediately.
For a certificate handling on the session level I used URLProtectionSpace on the URLCredentialStorage shared storage and then set that to Alamofire.Session configuration
here is an example to set it up (port 443 might be enough)
fileprivate func registerURLCredential() {
let storage = URLCredentialStorage.shared
do {
let credential: URLCredential = try loadURLCredential("certificate", password: "blablabla")
let url = URL.API
let host = url.host ?? ""
let ports: [Int] = [80, 443, url.port ?? 0]
for port in ports {
let space = URLProtectionSpace(
host: host,
port: port,
protocol: url.scheme,
realm: nil,
authenticationMethod: NSURLAuthenticationMethodClientCertificate
)
storage.set(credential, for: space)
}
} catch {
print(error)
}
}
fileprivate func createSession(_ configurationHandler: ((_ configuration: URLSessionConfiguration) -> Void)? = nil) -> Alamofire.Session {
let configuration = URLSessionConfiguration.af.default
registerURLCredential()
configuration.urlCredentialStorage = .shared
configurationHandler?(configuration)
let session = Session(
configuration: configuration,
requestQueue: .global(qos: .background),
serializationQueue: .global(qos: .background)
)
return session
}
A simple use for that would like:
let sesstion = createSession({ configuration in
configuration.httpMaximumConnectionsPerHost = 1
})

How to mock URLSession.DataTaskPublisher

How can I mock URLSession.DataTaskPublisher? I have a class Proxy that require to inject a URLSessionProtocol
protocol URLSessionProtocol {
func loadData(from url: URL) -> URLSession.DataTaskPublisher
}
class Proxy {
private let urlSession: URLSessionProtocol
init(urlSession: URLSessionProtocol) {
self.urlSession = urlSession
}
func get(url: URL) -> AnyPublisher<Data, ProxyError> {
// Using urlSession.loadData(from: url)
}
}
This code was originally used with the traditional version of URLSession with the completion handler. It was perfect since I could easily mock URLSession for testing like Sundell's solution here: Mocking in Swift.
Is it possible to do the same with the Combine Framework?
In the same way that you can inject a URLSessionProtocol to mock a concrete session, you can also inject a mocked Publisher. For example:
let mockPublisher = Just(MockData()).eraseToAnyPublisher()
However, depending on what you do with this publisher you might have to address some weirdnesses with Combine async publishers, see this post for additional discussion:
Why does Combine's receive(on:) operator swallow errors?
The best way to test your client is to use URLProtocol.
https://developer.apple.com/documentation/foundation/urlprotocol
You can intercept all your request before she performs the real request on the cloud, and so creates your expectation. Once you have done your expectation, she will be destroyed, so you never make real requests.
Tests more reliable, faster, and you got the control!
You got a little example here: https://www.hackingwithswift.com/articles/153/how-to-test-ios-networking-code-the-easy-way
But it's more powerful than just this, you can do everything you want like: Check your Events/Analytics...
I hope it'll help you!
Since DataTaskPublisher uses the URLSession it is created from, you can just mock that. I ended up creating a URLSession subclass, overriding dataTask(...) to return a URLSessionDataTask subclass, which I fed with the data/response/error I needed...
class URLSessionDataTaskMock: URLSessionDataTask {
private let closure: () -> Void
init(closure: #escaping () -> Void) {
self.closure = closure
}
override func resume() {
closure()
}
}
class URLSessionMock: URLSession {
var data: Data?
var response: URLResponse?
var error: Error?
override func dataTask(with request: URLRequest, completionHandler: #escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask {
let data = self.data
let response = self.response
let error = self.error
return URLSessionDataTaskMock {
completionHandler(data, response, error)
}
}
}
Then obviously you just want your networking layer using this URLSession, I went with a factory to do this:
protocol DataTaskPublisherFactory {
func make(for request: URLRequest) -> URLSession.DataTaskPublisher
}
Then in your network layer:
func performRequest<ResponseType>(_ request: URLRequest) -> AnyPublisher<ResponseType, APIError> where ResponseType : Decodable {
Just(request)
.flatMap {
self.dataTaskPublisherFactory.make(for: $0)
.mapError { APIError.urlError($0)} } }
.eraseToAnyPublisher()
}
Now you can just pass a mock factory in the test using the URLSession subclass (this one asserts URLErrors are mapped to a custom error, but you could also assert some other condition given data/response):
func test_performRequest_URLSessionDataTaskThrowsError_throwsAPIError() {
let session = URLSessionMock()
session.error = TestError.test
let dataTaskPublisherFactory = mock(DataTaskPublisherFactory.self)
given(dataTaskPublisherFactory.make(for: any())) ~> {
session.dataTaskPublisher(for: $0)
}
let api = API(dataTaskPublisherFactory: dataTaskPublisherFactory)
let publisher: AnyPublisher<TestCodable, APIError> =
api.performRequest(URLRequest(url: URL(string: "www.someURL.com")!))
let _ = publisher.sink(receiveCompletion: {
switch $0 {
case .failure(let error):
XCTAssertEqual(error, APIError.urlError(URLError(_nsError: NSError(domain: "NSURLErrorDomain", code: -1, userInfo: nil))))
case .finished:
XCTFail()
}
}) { _ in }
}
The one issue with this is that URLSession init() is deprecated from iOS 13, so you have to live with a warning in your test. If anyone can see a way around that I'd greatly appreciate it.
(Note: I'm using Mockingbird for mocks).

Embed SSL root certificate in iOS app instead of installing it for the whole system

How can I embed a custom CA SSL certificate in an application that connects to a local server?
This certificate should work like any CA certificate installed in the system, but embedded in this application instead of requiring the user to install it system-wide, so it won't show a security warning and only works with our local servers through the application
The need for this is to comply with ATS without needing the user to do any further configuration like downloading and installing the CA Certificate manually
I assume you're working with a self-signed certificate, in which case, what you're looking for is SSL pinning.
Depending on whether you're using a network lib or not, this might work differently, but what you want to do is store a public cert, and then handle the authentication challenge manually:
https://developer.apple.com/documentation/foundation/url_loading_system/handling_an_authentication_challenge
For example:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let trust = challenge.protectionSpace.serverTrust, SecTrustGetCertificateCount(trust) > 0 else {
// This case will probably get handled by ATS, but still...
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// Or, compare the public keys
if let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0), let serverCertificateKey = publicKey(for: serverCertificate) {
if pinnedKeys().contains(serverCertificateKey) {
completionHandler(.useCredential, URLCredential(trust: trust))
return
}
}
completionHandler(.cancelAuthenticationChallenge, nil)
}
fileprivate func pinnedKeys() -> [SecKey] {
var publicKeys: [SecKey] = []
if let pinnedCertificateURL = Bundle.main.url(forResource: "infinumco", withExtension: "crt") {
do {
let pinnedCertificateData = try Data(contentsOf: pinnedCertificateURL) as CFData
if let pinnedCertificate = SecCertificateCreateWithData(nil, pinnedCertificateData), let key = publicKey(for: pinnedCertificate) {
publicKeys.append(key)
}
} catch (_) {
// Handle error
}
}
return publicKeys
}
I have a couple of other examples how to handle this scenario here:
https://github.com/Adis/swift-ssl-pin-examples

Resources