2
0

AuthenticationInterceptorTests.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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 we not using swift-corelibs-foundation where URLRequest to /invalid/path is a fatal error.
  225. #if !canImport(FoundationNetworking)
  226. func testThatInterceptorDoesNotRetryWithoutResponse() {
  227. // Given
  228. let credential = TestCredential()
  229. let authenticator = TestAuthenticator()
  230. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  231. let urlRequest = URLRequest(url: URL(string: "/invalid/path")!)
  232. let session = Session()
  233. let expect = expectation(description: "request should complete")
  234. var response: AFDataResponse<Data?>?
  235. // When
  236. let request = session.request(urlRequest, interceptor: interceptor).validate().response {
  237. response = $0
  238. expect.fulfill()
  239. }
  240. waitForExpectations(timeout: timeout)
  241. // Then
  242. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  243. XCTAssertEqual(response?.result.isFailure, true)
  244. XCTAssertEqual(response?.result.failure?.asAFError?.isSessionTaskError, true)
  245. XCTAssertEqual(authenticator.applyCount, 1)
  246. XCTAssertEqual(authenticator.refreshCount, 0)
  247. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  248. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  249. XCTAssertEqual(request.retryCount, 0)
  250. }
  251. #endif
  252. func testThatInterceptorDoesNotRetryWhenRequestDoesNotFailDueToAuthError() {
  253. // Given
  254. let credential = TestCredential()
  255. let authenticator = TestAuthenticator()
  256. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  257. let session = Session()
  258. let expect = expectation(description: "request should complete")
  259. var response: AFDataResponse<Data?>?
  260. // When
  261. let request = session.request(.status(500), interceptor: interceptor).validate().response {
  262. response = $0
  263. expect.fulfill()
  264. }
  265. waitForExpectations(timeout: timeout)
  266. // Then
  267. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  268. XCTAssertEqual(response?.result.isFailure, true)
  269. XCTAssertEqual(response?.result.failure?.asAFError?.isResponseValidationError, true)
  270. XCTAssertEqual(response?.result.failure?.asAFError?.responseCode, 500)
  271. XCTAssertEqual(authenticator.applyCount, 1)
  272. XCTAssertEqual(authenticator.refreshCount, 0)
  273. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  274. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  275. XCTAssertEqual(request.retryCount, 0)
  276. }
  277. func testThatInterceptorThrowsMissingCredentialErrorWhenCredentialIsNilAndRequestShouldBeRetried() {
  278. // Given
  279. let credential = TestCredential()
  280. let authenticator = TestAuthenticator()
  281. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  282. let session = stored(Session())
  283. let expect = expectation(description: "request should complete")
  284. var response: AFDataResponse<Data?>?
  285. // When
  286. let request = session.request(.status(401), interceptor: interceptor)
  287. .validate {
  288. interceptor.credential = nil
  289. }
  290. .response {
  291. response = $0
  292. expect.fulfill()
  293. }
  294. waitForExpectations(timeout: timeout)
  295. // Then
  296. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  297. XCTAssertEqual(response?.result.isFailure, true)
  298. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  299. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .missingCredential)
  300. if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  301. XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  302. XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  303. }
  304. XCTAssertEqual(authenticator.applyCount, 1)
  305. XCTAssertEqual(authenticator.refreshCount, 0)
  306. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  307. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  308. XCTAssertEqual(request.retryCount, 0)
  309. }
  310. func testThatInterceptorRetriesRequestThatFailedWithOutdatedCredential() {
  311. // Given
  312. let credential = TestCredential()
  313. let authenticator = TestAuthenticator()
  314. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  315. let session = stored(Session())
  316. let pathAdapter = PathAdapter(paths: ["/status/401", "/status/200"])
  317. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  318. let expect = expectation(description: "request should complete")
  319. var response: AFDataResponse<Data?>?
  320. // When
  321. let request = session.request(.default, interceptor: compositeInterceptor)
  322. .validate {
  323. interceptor.credential = TestCredential(accessToken: "a1",
  324. refreshToken: "r1",
  325. userID: "u0",
  326. expiration: Date(),
  327. requiresRefresh: false)
  328. }
  329. .response {
  330. response = $0
  331. expect.fulfill()
  332. }
  333. waitForExpectations(timeout: timeout)
  334. // Then
  335. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  336. XCTAssertEqual(response?.result.isSuccess, true)
  337. XCTAssertEqual(authenticator.applyCount, 2)
  338. XCTAssertEqual(authenticator.refreshCount, 0)
  339. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  340. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  341. XCTAssertEqual(request.retryCount, 1)
  342. }
  343. // Produces double lock reported in https://github.com/Alamofire/Alamofire/issues/3294#issuecomment-703241558
  344. func testThatInterceptorDoesNotDeadlockWhenAuthenticatorCallsRefreshCompletionSynchronouslyOnCallingQueue() {
  345. // Given
  346. let credential = TestCredential(requiresRefresh: true)
  347. let authenticator = TestAuthenticator(shouldRefreshAsynchronously: false)
  348. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  349. let eventMonitor = ClosureEventMonitor()
  350. eventMonitor.requestDidCreateTask = { _, _ in
  351. interceptor.credential = TestCredential(accessToken: "a1",
  352. refreshToken: "r1",
  353. userID: "u0",
  354. expiration: Date(),
  355. requiresRefresh: false)
  356. }
  357. let session = Session(eventMonitors: [eventMonitor])
  358. let pathAdapter = PathAdapter(paths: ["/status/200"])
  359. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  360. let expect = expectation(description: "request should complete")
  361. var response: AFDataResponse<Data?>?
  362. // When
  363. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  364. response = $0
  365. expect.fulfill()
  366. }
  367. waitForExpectations(timeout: timeout)
  368. // Then
  369. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  370. XCTAssertEqual(response?.result.isSuccess, true)
  371. XCTAssertEqual(authenticator.applyCount, 1)
  372. XCTAssertEqual(authenticator.refreshCount, 1)
  373. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 0)
  374. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 0)
  375. XCTAssertEqual(request.retryCount, 0)
  376. }
  377. func testThatInterceptorRetriesRequestAfterRefresh() {
  378. // Given
  379. let credential = TestCredential()
  380. let authenticator = TestAuthenticator()
  381. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  382. let pathAdapter = PathAdapter(paths: ["/status/401", "/status/200"])
  383. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  384. let session = Session()
  385. let expect = expectation(description: "request should complete")
  386. var response: AFDataResponse<Data?>?
  387. // When
  388. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  389. response = $0
  390. expect.fulfill()
  391. }
  392. waitForExpectations(timeout: timeout)
  393. // Then
  394. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  395. XCTAssertEqual(response?.result.isSuccess, true)
  396. XCTAssertEqual(authenticator.applyCount, 2)
  397. XCTAssertEqual(authenticator.refreshCount, 1)
  398. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  399. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  400. XCTAssertEqual(request.retryCount, 1)
  401. }
  402. func testThatInterceptorRethrowsRefreshErrorFromRetry() {
  403. // Given
  404. let credential = TestCredential()
  405. let authenticator = TestAuthenticator(refreshResult: .failure(TestAuthError.refreshNetworkFailure))
  406. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  407. let session = Session()
  408. let expect = expectation(description: "request should complete")
  409. var response: AFDataResponse<Data?>?
  410. // When
  411. let request = session.request(.status(401), interceptor: interceptor).validate().response {
  412. response = $0
  413. expect.fulfill()
  414. }
  415. waitForExpectations(timeout: timeout)
  416. // Then
  417. XCTAssertEqual(response?.request?.headers["Authorization"], "a0")
  418. XCTAssertEqual(response?.result.isFailure, true)
  419. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  420. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? TestAuthError, .refreshNetworkFailure)
  421. if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  422. XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  423. XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  424. }
  425. XCTAssertEqual(authenticator.applyCount, 1)
  426. XCTAssertEqual(authenticator.refreshCount, 1)
  427. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 1)
  428. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 1)
  429. XCTAssertEqual(request.retryCount, 0)
  430. }
  431. func testThatInterceptorTriggersRefreshWithMultipleParallelRequestsReturning401Responses() {
  432. // Given
  433. let credential = TestCredential()
  434. let authenticator = TestAuthenticator()
  435. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  436. let requestCount = 6
  437. let session = stored(Session())
  438. let expect = expectation(description: "both requests should complete")
  439. expect.expectedFulfillmentCount = requestCount
  440. var requests: [Int: Request] = [:]
  441. var responses: [Int: AFDataResponse<Data?>] = [:]
  442. for index in 0..<requestCount {
  443. let pathAdapter = PathAdapter(paths: ["/status/401", "/status/20\(index)"])
  444. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  445. // When
  446. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  447. responses[index] = $0
  448. expect.fulfill()
  449. }
  450. requests[index] = request
  451. }
  452. waitForExpectations(timeout: timeout)
  453. // Then
  454. for index in 0..<requestCount {
  455. let response = responses[index]
  456. XCTAssertEqual(response?.request?.headers["Authorization"], "a1")
  457. XCTAssertEqual(response?.result.isSuccess, true)
  458. let request = requests[index]
  459. XCTAssertEqual(request?.retryCount, 1)
  460. }
  461. XCTAssertEqual(authenticator.applyCount, 12)
  462. XCTAssertEqual(authenticator.refreshCount, 1)
  463. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 6)
  464. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 6)
  465. }
  466. // MARK: - Tests - Excessive Refresh
  467. func testThatInterceptorIgnoresExcessiveRefreshWhenRefreshWindowIsNil() {
  468. // Given
  469. let credential = TestCredential()
  470. let authenticator = TestAuthenticator()
  471. let interceptor = AuthenticationInterceptor(authenticator: authenticator, credential: credential)
  472. let pathAdapter = PathAdapter(paths: ["/status/401",
  473. "/status/401",
  474. "/status/401",
  475. "/status/401",
  476. "/status/401",
  477. "/status/200"])
  478. let compositeInterceptor = Interceptor(adapters: [pathAdapter, interceptor], retriers: [interceptor])
  479. let session = Session()
  480. let expect = expectation(description: "request should complete")
  481. var response: AFDataResponse<Data?>?
  482. // When
  483. let request = session.request(.default, interceptor: compositeInterceptor).validate().response {
  484. response = $0
  485. expect.fulfill()
  486. }
  487. waitForExpectations(timeout: timeout)
  488. // Then
  489. XCTAssertEqual(response?.request?.headers["Authorization"], "a5")
  490. XCTAssertEqual(response?.result.isSuccess, true)
  491. XCTAssertEqual(authenticator.applyCount, 6)
  492. XCTAssertEqual(authenticator.refreshCount, 5)
  493. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 5)
  494. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 5)
  495. XCTAssertEqual(request.retryCount, 5)
  496. }
  497. func testThatInterceptorThrowsExcessiveRefreshErrorWhenExcessiveRefreshOccurs() {
  498. // Given
  499. let credential = TestCredential()
  500. let authenticator = TestAuthenticator()
  501. let interceptor = AuthenticationInterceptor(authenticator: authenticator,
  502. credential: credential,
  503. refreshWindow: .init(interval: 30, maximumAttempts: 2))
  504. let session = Session()
  505. let expect = expectation(description: "request should complete")
  506. var response: AFDataResponse<Data?>?
  507. // When
  508. let request = session.request(.status(401), interceptor: interceptor).validate().response {
  509. response = $0
  510. expect.fulfill()
  511. }
  512. waitForExpectations(timeout: timeout)
  513. // Then
  514. XCTAssertEqual(response?.request?.headers["Authorization"], "a2")
  515. XCTAssertEqual(response?.result.isFailure, true)
  516. XCTAssertEqual(response?.result.failure?.asAFError?.isRequestRetryError, true)
  517. XCTAssertEqual(response?.result.failure?.asAFError?.underlyingError as? AuthenticationError, .excessiveRefresh)
  518. if case let .requestRetryFailed(_, originalError) = response?.result.failure {
  519. XCTAssertEqual(originalError.asAFError?.isResponseValidationError, true)
  520. XCTAssertEqual(originalError.asAFError?.responseCode, 401)
  521. }
  522. XCTAssertEqual(authenticator.applyCount, 3)
  523. XCTAssertEqual(authenticator.refreshCount, 2)
  524. XCTAssertEqual(authenticator.didRequestFailDueToAuthErrorCount, 3)
  525. XCTAssertEqual(authenticator.isRequestAuthenticatedWithCredentialCount, 3)
  526. XCTAssertEqual(request.retryCount, 2)
  527. }
  528. }