AuthenticationInterceptorTests.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. //
  2. // AuthenticationInterceptorTests.swift
  3. //
  4. // Copyright (c) 2020 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. @testable import Alamofire
  25. import Foundation
  26. import XCTest
  27. final class AuthenticationInterceptorTestCase: BaseTestCase {
  28. // MARK: - Helper Types
  29. struct TestCredential: AuthenticationCredential {
  30. let accessToken: String
  31. let refreshToken: String
  32. let userID: String
  33. let expiration: Date
  34. let requiresRefresh: Bool
  35. init(accessToken: String = "a0",
  36. refreshToken: String = "r0",
  37. userID: String = "u0",
  38. expiration: Date = Date(),
  39. requiresRefresh: Bool = false) {
  40. self.accessToken = accessToken
  41. self.refreshToken = refreshToken
  42. self.userID = userID
  43. self.expiration = expiration
  44. self.requiresRefresh = requiresRefresh
  45. }
  46. }
  47. enum TestAuthError: Error {
  48. case refreshNetworkFailure
  49. }
  50. final class TestAuthenticator: Authenticator {
  51. private(set) var applyCount = 0
  52. private(set) var refreshCount = 0
  53. private(set) var didRequestFailDueToAuthErrorCount = 0
  54. private(set) var isRequestAuthenticatedWithCredentialCount = 0
  55. let shouldRefreshAsynchronously: Bool
  56. let refreshResult: Result<TestCredential, Error>?
  57. let lock = NSLock()
  58. init(shouldRefreshAsynchronously: Bool = true, refreshResult: Result<TestCredential, Error>? = nil) {
  59. self.shouldRefreshAsynchronously = shouldRefreshAsynchronously
  60. self.refreshResult = refreshResult
  61. }
  62. func apply(_ credential: TestCredential, to urlRequest: inout URLRequest) {
  63. lock.lock(); defer { lock.unlock() }
  64. applyCount += 1
  65. urlRequest.headers.add(.authorization(credential.accessToken))
  66. }
  67. func refresh(_ credential: TestCredential,
  68. for session: Session,
  69. completion: @escaping (Result<TestCredential, Error>) -> Void) {
  70. lock.lock()
  71. refreshCount += 1
  72. let result = refreshResult ?? .success(
  73. TestCredential(accessToken: "a\(refreshCount)",
  74. refreshToken: "a\(refreshCount)",
  75. userID: "u1",
  76. expiration: Date())
  77. )
  78. if shouldRefreshAsynchronously {
  79. // The 10 ms delay here is important to allow multiple requests to queue up while refreshing.
  80. DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + 0.01) { completion(result) }
  81. lock.unlock()
  82. } else {
  83. lock.unlock()
  84. completion(result)
  85. }
  86. }
  87. func didRequest(_ urlRequest: URLRequest,
  88. with response: HTTPURLResponse,
  89. failDueToAuthenticationError error: Error)
  90. -> Bool {
  91. lock.lock(); defer { lock.unlock() }
  92. didRequestFailDueToAuthErrorCount += 1
  93. return response.statusCode == 401
  94. }
  95. func isRequest(_ urlRequest: URLRequest, authenticatedWith credential: TestCredential) -> Bool {
  96. lock.lock(); defer { lock.unlock() }
  97. isRequestAuthenticatedWithCredentialCount += 1
  98. return urlRequest.headers["Authorization"] == credential.accessToken
  99. }
  100. }
  101. final class PathAdapter: RequestAdapter {
  102. var paths: [String]
  103. init(paths: [String]) {
  104. self.paths = paths
  105. }
  106. func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
  107. var request = urlRequest
  108. var urlComponents = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)!
  109. urlComponents.path = paths.removeFirst()
  110. request.url = urlComponents.url
  111. completion(.success(request))
  112. }
  113. }
  114. // MARK: - Tests - Adapt
  115. func testThatInterceptorCanAdaptURLRequest() {
  116. // Given
  117. let credential = TestCredential()
  118. let authenticator = TestAuthenticator()
  119. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  120. let session = Session()
  121. let expect = expectation(description: "request should complete")
  122. var response: AFDataResponse<Data?>?
  123. // When
  124. let request = session.request(.default, interceptor: interceptor).validate().response {
  125. response = $0
  126. expect.fulfill()
  127. }
  128. waitForExpectations(timeout: timeout)
  129. // Then
  130. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  131. XCTAssertEqual(response?.result.isSuccess, true)
  132. XCTAssertEqual(authenticator.applyCount, 1)
  133. XCTAssertEqual(authenticator.refreshCount, 0)
  134. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  135. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  136. XCTAssertEqual(request.retryCount, 0)
  137. }
  138. func testThatInterceptorQueuesAdaptOperationWhenRefreshing() {
  139. // Given
  140. let credential = TestCredential(requiresRefresh: true)
  141. let authenticator = TestAuthenticator()
  142. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  143. let session = Session()
  144. let expect = expectation(description: "both requests should complete")
  145. expect.expectedFulfillmentCount = 2
  146. var response1: AFDataResponse<Data?>?
  147. var response2: AFDataResponse<Data?>?
  148. // When
  149. let request1 = session.request(.status(200), interceptor: interceptor).validate().response {
  150. response1 = $0
  151. expect.fulfill()
  152. }
  153. let request2 = session.request(.status(202), interceptor: interceptor).validate().response {
  154. response2 = $0
  155. expect.fulfill()
  156. }
  157. waitForExpectations(timeout: timeout)
  158. // Then
  159. XCTAssertEqual(response1?.request?.headers["Authorization"], "a1")
  160. XCTAssertEqual(response2?.request?.headers["Authorization"], "a1")
  161. XCTAssertEqual(response1?.result.isSuccess, true)
  162. XCTAssertEqual(response2?.result.isSuccess, true)
  163. XCTAssertEqual(authenticator.applyCount, 2)
  164. XCTAssertEqual(authenticator.refreshCount, 1)
  165. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  166. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  167. XCTAssertEqual(request1.retryCount, 0)
  168. XCTAssertEqual(request2.retryCount, 0)
  169. }
  170. func testThatInterceptorThrowsMissingCredentialErrorWhenCredentialIsNil() {
  171. // Given
  172. let authenticator = TestAuthenticator()
  173. let interceptor = AuthenticationInterceptor(authenticator: authenticator)
  174. let session = Session()
  175. let expect = expectation(description: "request should complete")
  176. var response: AFDataResponse<Data?>?
  177. // When
  178. let request = session.request(.default, interceptor: interceptor).validate().response {
  179. response = $0
  180. expect.fulfill()
  181. }
  182. waitForExpectations(timeout: timeout)
  183. // Then
  184. XCTAssertEqual(response?.request?.headers.count, 0)
  185. XCTAssertEqual(response?.result.isFailure, true)
  186. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestAdaptationError, true)
  187. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .missingCredential)
  188. XCTAssertEqual(authenticator.applyCount, 0)
  189. XCTAssertEqual(authenticator.refreshCount, 0)
  190. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  191. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  192. XCTAssertEqual(request.retryCount, 0)
  193. }
  194. func testThatInterceptorRethrowsRefreshErrorFromAdapt() {
  195. // Given
  196. let credential = TestCredential(requiresRefresh: true)
  197. let authenticator = TestAuthenticator(refreshResult: .failure(TestAuthError.refreshNetworkFailure))
  198. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  199. let session = Session()
  200. let expect = expectation(description: "request should complete")
  201. var response: AFDataResponse<Data?>?
  202. // When
  203. let request = session.request(.default, interceptor: interceptor).validate().response {
  204. response = $0
  205. expect.fulfill()
  206. }
  207. waitForExpectations(timeout: timeout)
  208. // Then
  209. XCTAssertEqual(response?.request?.headers.count, 0)
  210. XCTAssertEqual(response?.result.isFailure, true)
  211. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestAdaptationError, true)
  212. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? TestAuthError, .refreshNetworkFailure)
  213. if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  214. XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  215. XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  216. }
  217. XCTAssertEqual(authenticator.applyCount, 0)
  218. XCTAssertEqual(authenticator.refreshCount, 1)
  219. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  220. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  221. XCTAssertEqual(request.retryCount, 0)
  222. }
  223. // MARK: - Tests - Retry
  224. #if !(os(Linux) || os(Windows)) // URLRequest to /invalid/path is a fatal error.
  225. func testThatInterceptorDoesNotRetryWithoutResponse() {
  226. // Given
  227. let credential = TestCredential()
  228. let authenticator = TestAuthenticator()
  229. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  230. let urlRequest = URLRequest(url: URL(string: "/invalid/path")!)
  231. let session = Session()
  232. let expect = expectation(description: "request should complete")
  233. var response: AFDataResponse<Data?>?
  234. // When
  235. let request = session.request(urlRequest, interceptor: interceptor).validate().response {
  236. response = $0
  237. expect.fulfill()
  238. }
  239. waitForExpectations(timeout: timeout)
  240. // Then
  241. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  242. XCTAssertEqual(response?.result.isFailure, true)
  243. XCTAssertEqual(response?.result.failure?.asAFError?.isSessionTaskError, true)
  244. XCTAssertEqual(authenticator.applyCount, 1)
  245. XCTAssertEqual(authenticator.refreshCount, 0)
  246. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  247. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  248. XCTAssertEqual(request.retryCount, 0)
  249. }
  250. #endif
  251. func testThatInterceptorDoesNotRetryWhenRequestDoesNotFailDueToAuthError() {
  252. // Given
  253. let credential = TestCredential()
  254. let authenticator = TestAuthenticator()
  255. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  256. let session = Session()
  257. let expect = expectation(description: "request should complete")
  258. var response: AFDataResponse<Data?>?
  259. // When
  260. let request = session.request(.status(500), interceptor: interceptor).validate().response {
  261. response = $0
  262. expect.fulfill()
  263. }
  264. waitForExpectations(timeout: timeout)
  265. // Then
  266. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  267. XCTAssertEqual(response?.result.isFailure, true)
  268. XCTAssertEqual(response?.result.failure?.asAFError?.isResponseValidationError, true)
  269. XCTAssertEqual(response?.result.failure?.asAFError?.responseCode, 500)
  270. XCTAssertEqual(authenticator.applyCount, 1)
  271. XCTAssertEqual(authenticator.refreshCount, 0)
  272. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  273. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  274. XCTAssertEqual(request.retryCount, 0)
  275. }
  276. func testThatInterceptorThrowsMissingCredentialErrorWhenCredentialIsNilAndRequestShouldBeRetried() {
  277. // Given
  278. let credential = TestCredential()
  279. let authenticator = TestAuthenticator()
  280. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  281. let session = stored(Session())
  282. let expect = expectation(description: "request should complete")
  283. var response: AFDataResponse<Data?>?
  284. // When
  285. let request = session.request(.status(401), interceptor: interceptor)
  286. .validate {
  287. interceptor.credential = nil
  288. }
  289. .response {
  290. response = $0
  291. expect.fulfill()
  292. }
  293. waitForExpectations(timeout: timeout)
  294. // Then
  295. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  296. XCTAssertEqual(response?.result.isFailure, true)
  297. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  298. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .missingCredential)
  299. if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  300. XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  301. XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  302. }
  303. XCTAssertEqual(authenticator.applyCount, 1)
  304. XCTAssertEqual(authenticator.refreshCount, 0)
  305. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  306. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  307. XCTAssertEqual(request.retryCount, 0)
  308. }
  309. func testThatInterceptorRetriesRequestThatFailedWithOutdatedCredential() {
  310. // Given
  311. let credential = TestCredential()
  312. let authenticator = TestAuthenticator()
  313. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  314. let session = stored(Session())
  315. let pathAdapter = PathAdapter(paths: ["/status/401", "/status/200"])
  316. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  317. let expect = expectation(description: "request should complete")
  318. var response: AFDataResponse<Data?>?
  319. // When
  320. let request = session.request(.default, interceptor: compositeInterceptor)
  321. .validate {
  322. interceptor.credential = TestCredential(accessToken: "a1",
  323. refreshToken: "r1",
  324. userID: "u0",
  325. expiration: Date(),
  326. requiresRefresh: false)
  327. }
  328. .response {
  329. response = $0
  330. expect.fulfill()
  331. }
  332. waitForExpectations(timeout: timeout)
  333. // Then
  334. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  335. XCTAssertEqual(response?.result.isSuccess, true)
  336. XCTAssertEqual(authenticator.applyCount, 2)
  337. XCTAssertEqual(authenticator.refreshCount, 0)
  338. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  339. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  340. XCTAssertEqual(request.retryCount, 1)
  341. }
  342. // Produces double lock reported in https://github.com/Alamofire/Alamofire/issues/3294#issuecomment-703241558
  343. func testThatInterceptorDoesNotDeadlockWhenAuthenticatorCallsRefreshCompletionSynchronouslyOnCallingQueue() {
  344. // Given
  345. let credential = TestCredential(requiresRefresh: true)
  346. let authenticator = TestAuthenticator(shouldRefreshAsynchronously: false)
  347. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  348. let eventMonitor = ClosureEventMonitor()
  349. eventMonitor.requestDidCreateTask = { _, _ in
  350. interceptor.credential = TestCredential(accessToken: "a1",
  351. refreshToken: "r1",
  352. userID: "u0",
  353. expiration: Date(),
  354. requiresRefresh: false)
  355. }
  356. let session = Session(eventMonitors: [eventMonitor])
  357. let pathAdapter = PathAdapter(paths: ["/status/200"])
  358. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  359. let expect = expectation(description: "request should complete")
  360. var response: AFDataResponse<Data?>?
  361. // When
  362. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  363. response = $0
  364. expect.fulfill()
  365. }
  366. waitForExpectations(timeout: timeout)
  367. // Then
  368. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  369. XCTAssertEqual(response?.result.isSuccess, true)
  370. XCTAssertEqual(authenticator.applyCount, 1)
  371. XCTAssertEqual(authenticator.refreshCount, 1)
  372. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  373. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  374. XCTAssertEqual(request.retryCount, 0)
  375. }
  376. func testThatInterceptorRetriesRequestAfterRefresh() {
  377. // Given
  378. let credential = TestCredential()
  379. let authenticator = TestAuthenticator()
  380. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  381. let pathAdapter = PathAdapter(paths: ["/status/401", "/status/200"])
  382. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  383. let session = Session()
  384. let expect = expectation(description: "request should complete")
  385. var response: AFDataResponse<Data?>?
  386. // When
  387. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  388. response = $0
  389. expect.fulfill()
  390. }
  391. waitForExpectations(timeout: timeout)
  392. // Then
  393. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  394. XCTAssertEqual(response?.result.isSuccess, true)
  395. XCTAssertEqual(authenticator.applyCount, 2)
  396. XCTAssertEqual(authenticator.refreshCount, 1)
  397. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  398. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  399. XCTAssertEqual(request.retryCount, 1)
  400. }
  401. func testThatInterceptorRethrowsRefreshErrorFromRetry() {
  402. // Given
  403. let credential = TestCredential()
  404. let authenticator = TestAuthenticator(refreshResult: .failure(TestAuthError.refreshNetworkFailure))
  405. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  406. let session = Session()
  407. let expect = expectation(description: "request should complete")
  408. var response: AFDataResponse<Data?>?
  409. // When
  410. let request = session.request(.status(401), interceptor: interceptor).validate().response {
  411. response = $0
  412. expect.fulfill()
  413. }
  414. waitForExpectations(timeout: timeout)
  415. // Then
  416. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  417. XCTAssertEqual(response?.result.isFailure, true)
  418. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  419. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? TestAuthError, .refreshNetworkFailure)
  420. if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  421. XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  422. XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  423. }
  424. XCTAssertEqual(authenticator.applyCount, 1)
  425. XCTAssertEqual(authenticator.refreshCount, 1)
  426. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  427. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  428. XCTAssertEqual(request.retryCount, 0)
  429. }
  430. func testThatInterceptorTriggersRefreshWithMultipleParallelRequestsReturning401Responses() {
  431. // Given
  432. let credential = TestCredential()
  433. let authenticator = TestAuthenticator()
  434. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  435. let requestCount = 6
  436. let session = stored(Session())
  437. let expect = expectation(description: "both requests should complete")
  438. expect.expectedFulfillmentCount = requestCount
  439. var requests: [Int: Request] = [:]
  440. var responses: [Int: AFDataResponse<Data?>] = [:]
  441. for index in 0..<requestCount {
  442. let pathAdapter = PathAdapter(paths: ["/status/401", "/status/20\(index)"])
  443. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  444. // When
  445. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  446. responses[index] = $0
  447. expect.fulfill()
  448. }
  449. requests[index] = request
  450. }
  451. waitForExpectations(timeout: timeout)
  452. // Then
  453. for index in 0..<requestCount {
  454. let response = responses[index]
  455. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  456. XCTAssertEqual(response?.result.isSuccess, true)
  457. let request = requests[index]
  458. XCTAssertEqual(request?.retryCount, 1)
  459. }
  460. XCTAssertEqual(authenticator.applyCount, 12)
  461. XCTAssertEqual(authenticator.refreshCount, 1)
  462. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 6)
  463. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 6)
  464. }
  465. // MARK: - Tests - Excessive Refresh
  466. func testThatInterceptorIgnoresExcessiveRefreshWhenRefreshWindowIsNil() {
  467. // Given
  468. let credential = TestCredential()
  469. let authenticator = TestAuthenticator()
  470. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  471. let pathAdapter = PathAdapter(paths: ["/status/401",
  472. "/status/401",
  473. "/status/401",
  474. "/status/401",
  475. "/status/401",
  476. "/status/200"])
  477. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  478. let session = Session()
  479. let expect = expectation(description: "request should complete")
  480. var response: AFDataResponse<Data?>?
  481. // When
  482. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  483. response = $0
  484. expect.fulfill()
  485. }
  486. waitForExpectations(timeout: timeout)
  487. // Then
  488. XCTAssertEqual(response?.request?.headers["Authorization"], "a5")
  489. XCTAssertEqual(response?.result.isSuccess, true)
  490. XCTAssertEqual(authenticator.applyCount, 6)
  491. XCTAssertEqual(authenticator.refreshCount, 5)
  492. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 5)
  493. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 5)
  494. XCTAssertEqual(request.retryCount, 5)
  495. }
  496. func testThatInterceptorThrowsExcessiveRefreshErrorWhenExcessiveRefreshOccurs() {
  497. // Given
  498. let credential = TestCredential()
  499. let authenticator = TestAuthenticator()
  500. let interceptor = AuthenticationInterceptor(authenticator: authenticator,
  501. credential: credential,
  502. refreshWindow: .init(interval: 30, maximumAttempts: 2))
  503. let session = Session()
  504. let expect = expectation(description: "request should complete")
  505. var response: AFDataResponse<Data?>?
  506. // When
  507. let request = session.request(.status(401), interceptor: interceptor).validate().response {
  508. response = $0
  509. expect.fulfill()
  510. }
  511. waitForExpectations(timeout: timeout)
  512. // Then
  513. XCTAssertEqual(response?.request?.headers["Authorization"], "a2")
  514. XCTAssertEqual(response?.result.isFailure, true)
  515. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  516. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .excessiveRefresh)
  517. if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  518. XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  519. XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  520. }
  521. XCTAssertEqual(authenticator.applyCount, 3)
  522. XCTAssertEqual(authenticator.refreshCount, 2)
  523. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 3)
  524. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 3)
  525. XCTAssertEqual(request.retryCount, 2)
  526. }
  527. }