Подклассы URLProtectionSpace - PullRequest
       54

Подклассы URLProtectionSpace

0 голосов
/ 26 сентября 2018

Цель:

Тестирование закрепления SSL с помощью URLProtocol.

Проблема:

Невозможно создать подкласс URLProtectionSpace в ожидаемомманера.Свойство доверия сервера никогда не вызывается, и обратный вызов alamofire auth получает только тип класса URLProtectionSpace вместо моего класса, даже если вызывается инициализатор моего пользовательского класса.

Конфигурация: [использование Alamofire]

let sessionConfiguration: URLSessionConfiguration = .default
    sessionConfiguration.protocolClasses?.insert(BaseURLProtocol.self, at: 0)
    let sessionManager = AlamofireSessionBuilderImpl(configuration: sessionConfiguration).default
    // overriding the auth challenge in Alamofire in order to test what is being called
    sessionManager.delegate.sessionDidReceiveChallengeWithCompletion = { session, challenge, completionHandler in
        let protectionSpace = challenge.protectionSpace

        guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
            protectionSpace.host.contains("myDummyURL.com") else {
                // otherwise it means a different challenge is encountered and we are only interested in certificate validation
                completionHandler(.performDefaultHandling, nil)
                return
        }

        guard let serverTrust = protectionSpace.serverTrust else {
            completionHandler(.performDefaultHandling, nil)
            return
        }

        guard let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) else {
            return completionHandler(.cancelAuthenticationChallenge, nil)
        }

        let serverCertificateData = SecCertificateCopyData(serverCertificate) as Data

        // cannot find the local certificate
        guard let localCertPath = Bundle.main.path(forResource: "cert", ofType: "der"),
            let localCertificateData = NSData(contentsOfFile: localCertPath) else {
                return completionHandler(.cancelAuthenticationChallenge, nil)
        }

        guard localCertificateData.isEqual(to: serverCertificateData) else {
            // the certificate received from the server is invalid
            completionHandler(.cancelAuthenticationChallenge, nil)
            return
        }

        let credential = URLCredential(trust: serverTrust)

        completionHandler(.useCredential, credential)
    }

Определение BaseURLProtocol:

class BaseURLProtocol: URLProtocol {
override class func canInit(with request: URLRequest) -> Bool {
    return true
}

override class func canonicalRequest(for request: URLRequest) -> URLRequest {
    return request
}

override func startLoading() {
    debugPrint("--- request loading \(request)")

    guard request.url?.host?.contains("myDummyURL.com") ?? false else {
        debugPrint("--- caught untargetted request --- skipping ---host is \(request.url?.host)")
        return
    }

    let protectionSpace = CertificatePinningMockURLProtectionSpace(host: "https://myDummyURL.com", port: 443, protocol: nil, realm: nil, authenticationMethod: NSURLAuthenticationMethodServerTrust)

    let challenge = URLAuthenticationChallenge(protectionSpace: protectionSpace, proposedCredential: nil, previousFailureCount: 0, failureResponse: nil, error: nil, sender: self)

    client?.urlProtocol(self, didReceive: challenge)
}

}

CertificatePinningMockURLProtectionSpace: [использование Alamofire ServerTrustPolicy для полученияcerts]

- Свойство serverTrust никогда не вызывается.Я также переопределил все другие свойства URLProtectionSpace, и не вызывается ничего, кроме init.

class CertificatePinningMockURLProtectionSpace: URLProtectionSpace {
private static let expectedHost = "myDummyURL.com"

override init(host: String, port: Int, protocol: String?, realm: String?, authenticationMethod: String?) {
    debugPrint("--- super init will be called")
    super.init(host: host, port: port, protocol: `protocol`, realm: realm, authenticationMethod: authenticationMethod)
}

override var serverTrust: SecTrust? {
    guard let certificate = ServerTrustPolicy.certificates(in: .main).first else {
        return nil
    }

    let policy: SecPolicy = SecPolicyCreateSSL(true, CertificatePinningMockURLProtectionSpace.expectedHost as CFString)

    var serverTrust: SecTrust?

    SecTrustCreateWithCertificates(certificate, policy, &serverTrust)

    return serverTrust
}

}

Тестовый оператор:

sessionManager.request("https://myDummyURL.com").responseString(completionHandler: { response in
                        debugPrint("--- response is \(response)")
                        done()
                    })

Может ли URLProtectionSpace успешно быть переопределено и предоставлено как макет для URLProtocolClient внутри URLProtocol?

...