Validation.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. //
  2. // Validation.swift
  3. //
  4. // Copyright (c) 2014-2018 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. import Foundation
  25. extension Request {
  26. // MARK: Helper Types
  27. fileprivate typealias ErrorReason = AFError.ResponseValidationFailureReason
  28. /// Used to represent whether a validation succeeded or failed.
  29. public typealias ValidationResult = Result<Void, any(Error & Sendable)>
  30. fileprivate struct MIMEType {
  31. let type: String
  32. let subtype: String
  33. var isWildcard: Bool { type == "*" && subtype == "*" }
  34. init?(_ string: String) {
  35. let components: [String] = {
  36. let stripped = string.trimmingCharacters(in: .whitespacesAndNewlines)
  37. let split = stripped[..<(stripped.range(of: ";")?.lowerBound ?? stripped.endIndex)]
  38. return split.components(separatedBy: "/")
  39. }()
  40. if let type = components.first, let subtype = components.last {
  41. self.type = type
  42. self.subtype = subtype
  43. } else {
  44. return nil
  45. }
  46. }
  47. func matches(_ mime: MIMEType) -> Bool {
  48. switch (type, subtype) {
  49. case (mime.type, mime.subtype), (mime.type, "*"), ("*", mime.subtype), ("*", "*"):
  50. true
  51. default:
  52. false
  53. }
  54. }
  55. }
  56. // MARK: Properties
  57. fileprivate var acceptableStatusCodes: Range<Int> { 200..<300 }
  58. fileprivate var acceptableContentTypes: [String] {
  59. if let accept = request?.value(forHTTPHeaderField: "Accept") {
  60. return accept.components(separatedBy: ",")
  61. }
  62. return ["*/*"]
  63. }
  64. // MARK: Status Code
  65. fileprivate func validate<S: Sequence>(statusCode acceptableStatusCodes: S,
  66. response: HTTPURLResponse)
  67. -> ValidationResult
  68. where S.Iterator.Element == Int {
  69. if acceptableStatusCodes.contains(response.statusCode) {
  70. return .success(())
  71. } else {
  72. let reason: ErrorReason = .unacceptableStatusCode(code: response.statusCode)
  73. return .failure(AFError.responseValidationFailed(reason: reason))
  74. }
  75. }
  76. // MARK: Content Type
  77. fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
  78. response: HTTPURLResponse,
  79. isEmpty: Bool)
  80. -> ValidationResult
  81. where S.Iterator.Element == String {
  82. guard !isEmpty else { return .success(()) }
  83. return validate(contentType: acceptableContentTypes, response: response)
  84. }
  85. fileprivate func validate<S: Sequence>(contentType acceptableContentTypes: S,
  86. response: HTTPURLResponse)
  87. -> ValidationResult
  88. where S.Iterator.Element == String {
  89. guard
  90. let responseContentType = response.mimeType,
  91. let responseMIMEType = MIMEType(responseContentType)
  92. else {
  93. for contentType in acceptableContentTypes {
  94. if let mimeType = MIMEType(contentType), mimeType.isWildcard {
  95. return .success(())
  96. }
  97. }
  98. let error: AFError = {
  99. let reason: ErrorReason = .missingContentType(acceptableContentTypes: acceptableContentTypes.sorted())
  100. return AFError.responseValidationFailed(reason: reason)
  101. }()
  102. return .failure(error)
  103. }
  104. for contentType in acceptableContentTypes {
  105. if let acceptableMIMEType = MIMEType(contentType), acceptableMIMEType.matches(responseMIMEType) {
  106. return .success(())
  107. }
  108. }
  109. let error: AFError = {
  110. let reason: ErrorReason = .unacceptableContentType(acceptableContentTypes: acceptableContentTypes.sorted(),
  111. responseContentType: responseContentType)
  112. return AFError.responseValidationFailed(reason: reason)
  113. }()
  114. return .failure(error)
  115. }
  116. }
  117. // MARK: -
  118. extension DataRequest {
  119. /// A closure used to validate a request that takes a URL request, a URL response and data, and returns whether the
  120. /// request was valid.
  121. public typealias Validation = @Sendable (URLRequest?, HTTPURLResponse, Data?) -> ValidationResult
  122. /// Validates that the response has a status code in the specified sequence.
  123. ///
  124. /// If validation fails, subsequent calls to response handlers will have an associated error.
  125. ///
  126. /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
  127. ///
  128. /// - Returns: The instance.
  129. @preconcurrency
  130. @discardableResult
  131. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int, S: Sendable {
  132. validate { [unowned self] _, response, _ in
  133. self.validate(statusCode: acceptableStatusCodes, response: response)
  134. }
  135. }
  136. /// Validates that the response has a content type in the specified sequence.
  137. ///
  138. /// If validation fails, subsequent calls to response handlers will have an associated error.
  139. ///
  140. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  141. ///
  142. /// - returns: The request.
  143. @preconcurrency
  144. @discardableResult
  145. public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @Sendable @autoclosure () -> S) -> Self where S.Iterator.Element == String, S: Sendable {
  146. validate { [unowned self] _, response, data in
  147. self.validate(contentType: acceptableContentTypes(), response: response, isEmpty: (data == nil || data?.isEmpty == true))
  148. }
  149. }
  150. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  151. /// type matches any specified in the Accept HTTP header field.
  152. ///
  153. /// If validation fails, subsequent calls to response handlers will have an associated error.
  154. ///
  155. /// - returns: The request.
  156. @discardableResult
  157. public func validate() -> Self {
  158. let contentTypes: @Sendable () -> [String] = { [unowned self] in
  159. acceptableContentTypes
  160. }
  161. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  162. }
  163. }
  164. extension DataStreamRequest {
  165. /// A closure used to validate a request that takes a `URLRequest` and `HTTPURLResponse` and returns whether the
  166. /// request was valid.
  167. public typealias Validation = @Sendable (_ request: URLRequest?, _ response: HTTPURLResponse) -> ValidationResult
  168. /// Validates that the response has a status code in the specified sequence.
  169. ///
  170. /// If validation fails, subsequent calls to response handlers will have an associated error.
  171. ///
  172. /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
  173. ///
  174. /// - Returns: The instance.
  175. @preconcurrency
  176. @discardableResult
  177. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int, S: Sendable {
  178. validate { [unowned self] _, response in
  179. self.validate(statusCode: acceptableStatusCodes, response: response)
  180. }
  181. }
  182. /// Validates that the response has a content type in the specified sequence.
  183. ///
  184. /// If validation fails, subsequent calls to response handlers will have an associated error.
  185. ///
  186. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  187. ///
  188. /// - returns: The request.
  189. @preconcurrency
  190. @discardableResult
  191. public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @Sendable @autoclosure () -> S) -> Self where S.Iterator.Element == String, S: Sendable {
  192. validate { [unowned self] _, response in
  193. self.validate(contentType: acceptableContentTypes(), response: response)
  194. }
  195. }
  196. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  197. /// type matches any specified in the Accept HTTP header field.
  198. ///
  199. /// If validation fails, subsequent calls to response handlers will have an associated error.
  200. ///
  201. /// - Returns: The instance.
  202. @discardableResult
  203. public func validate() -> Self {
  204. let contentTypes: @Sendable () -> [String] = { [unowned self] in
  205. acceptableContentTypes
  206. }
  207. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  208. }
  209. }
  210. // MARK: -
  211. extension DownloadRequest {
  212. /// A closure used to validate a request that takes a URL request, a URL response, a temporary URL and a
  213. /// destination URL, and returns whether the request was valid.
  214. public typealias Validation = @Sendable (_ request: URLRequest?,
  215. _ response: HTTPURLResponse,
  216. _ fileURL: URL?)
  217. -> ValidationResult
  218. /// Validates that the response has a status code in the specified sequence.
  219. ///
  220. /// If validation fails, subsequent calls to response handlers will have an associated error.
  221. ///
  222. /// - Parameter acceptableStatusCodes: `Sequence` of acceptable response status codes.
  223. ///
  224. /// - Returns: The instance.
  225. @preconcurrency
  226. @discardableResult
  227. public func validate<S: Sequence>(statusCode acceptableStatusCodes: S) -> Self where S.Iterator.Element == Int, S: Sendable {
  228. validate { [unowned self] _, response, _ in
  229. self.validate(statusCode: acceptableStatusCodes, response: response)
  230. }
  231. }
  232. /// Validates that the response has a `Content-Type` in the specified sequence.
  233. ///
  234. /// If validation fails, subsequent calls to response handlers will have an associated error.
  235. ///
  236. /// - parameter contentType: The acceptable content types, which may specify wildcard types and/or subtypes.
  237. ///
  238. /// - returns: The request.
  239. @preconcurrency
  240. @discardableResult
  241. public func validate<S: Sequence>(contentType acceptableContentTypes: @escaping @Sendable @autoclosure () -> S) -> Self where S.Iterator.Element == String, S: Sendable {
  242. validate { [unowned self] _, response, fileURL in
  243. guard let fileURL else {
  244. return .failure(AFError.responseValidationFailed(reason: .dataFileNil))
  245. }
  246. do {
  247. let isEmpty = try (fileURL.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0) == 0
  248. return self.validate(contentType: acceptableContentTypes(), response: response, isEmpty: isEmpty)
  249. } catch {
  250. return .failure(AFError.responseValidationFailed(reason: .dataFileReadFailed(at: fileURL)))
  251. }
  252. }
  253. }
  254. /// Validates that the response has a status code in the default acceptable range of 200...299, and that the content
  255. /// type matches any specified in the Accept HTTP header field.
  256. ///
  257. /// If validation fails, subsequent calls to response handlers will have an associated error.
  258. ///
  259. /// - returns: The request.
  260. @discardableResult
  261. public func validate() -> Self {
  262. let contentTypes: @Sendable () -> [String] = { [unowned self] in
  263. acceptableContentTypes
  264. }
  265. return validate(statusCode: acceptableStatusCodes).validate(contentType: contentTypes())
  266. }
  267. }