From 358201c7f871bd4fce3051f96ba774389f036ff3 Mon Sep 17 00:00:00 2001 From: Maximilian Blochberger Date: Mon, 1 Oct 2018 11:33:38 +0200 Subject: [PATCH] Keep original headers of Shalon URL requests --- PrivacyKit/ShalonURLProtocol.swift | 9 +++++- PrivacyKitTests/ShalonTest.swift | 44 ++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/PrivacyKit/ShalonURLProtocol.swift b/PrivacyKit/ShalonURLProtocol.swift index 030c50f..90c8a5b 100644 --- a/PrivacyKit/ShalonURLProtocol.swift +++ b/PrivacyKit/ShalonURLProtocol.swift @@ -255,7 +255,14 @@ public class ShalonURLProtocol : URLProtocol { httpBody = Data() } - shalon.issue(request: Http.Request(withMethod: method, andUrl: shalonParameters.requestUrl, andBody: httpBody)!) { + let actualRequest = Http.Request( + withMethod: method, + andUrl: shalonParameters.requestUrl, + andHeaders: request.allHTTPHeaderFields ?? [:], + andBody: httpBody + )! + + shalon.issue(request: actualRequest) { optionalResponse, optionalError in assert((optionalResponse != nil) != (optionalError != nil)) diff --git a/PrivacyKitTests/ShalonTest.swift b/PrivacyKitTests/ShalonTest.swift index a3ac24b..43ef91d 100644 --- a/PrivacyKitTests/ShalonTest.swift +++ b/PrivacyKitTests/ShalonTest.swift @@ -252,4 +252,48 @@ class ShalonTest: XCTestCase { XCTAssertEqual(retrievedData, data) } } + + func testShalonHeaders() { + let url = URL(string: "httpss://shalon1.jondonym.net:443/httpbin.org/headers")! + + let sessionConfiguration = URLSessionConfiguration.ephemeral + sessionConfiguration.protocolClasses?.append(ShalonURLProtocol.self) + let session = URLSession(configuration: sessionConfiguration) + var request = URLRequest(url: url) + request.set(method: .get) + request.add(value: "1", for: .badProvider) + + let responseExpectation = expectation(description: "responseExpectation") + + var response: URLResponse? = nil + var responseBody : Data? = nil + + let task = session.dataTask(with: request) { + (potentialData, potentialResponse, potentialError) in + + response = potentialResponse + responseBody = potentialData + + responseExpectation.fulfill() + } + task.resume() + + waitForExpectations(timeout: 25/*seconds*/) { + optionalExpectationError in + + XCTAssertNil(optionalExpectationError, "Expectation handled erroneously") + XCTAssertNotNil(response) + XCTAssertNotNil(responseBody) + + let json = try! JSONSerialization.jsonObject(with: responseBody!) as! [String: Any] + let retrievedHeaders = json["headers"] as! [String: String] + var headers: [String: String] = [:] + for (key, value) in retrievedHeaders { + headers[key.lowercased()] = value + } + + XCTAssertEqual(headers[Http.Header.badProvider.rawValue.lowercased()], "1") + } + } + }