AuthWebUtils.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  16. class AuthWebUtils {
  17. static func randomString(withLength length: Int) -> String {
  18. var randomString = ""
  19. for _ in 0 ..< length {
  20. let randomValue = UInt32(arc4random_uniform(26) + 65)
  21. guard let randomCharacter = Unicode.Scalar(randomValue) else { continue }
  22. randomString += String(Character(randomCharacter))
  23. }
  24. return randomString
  25. }
  26. static func isCallbackSchemeRegistered(forCustomURLScheme scheme: String,
  27. urlTypes: [[String: Any]]) -> Bool {
  28. let expectedCustomScheme = scheme.lowercased()
  29. for urlType in urlTypes {
  30. guard let urlTypeSchemes = urlType["CFBundleURLSchemes"] else {
  31. continue
  32. }
  33. if let schemes = urlTypeSchemes as? [String] {
  34. for urlTypeScheme in schemes {
  35. if urlTypeScheme.lowercased() == expectedCustomScheme {
  36. return true
  37. }
  38. }
  39. }
  40. }
  41. return false
  42. }
  43. static func isExpectedCallbackURL(_ url: URL?, eventID: String, authType: String,
  44. callbackScheme: String) -> Bool {
  45. guard let url else {
  46. return false
  47. }
  48. var actualURLComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
  49. actualURLComponents?.query = nil
  50. actualURLComponents?.fragment = nil
  51. var expectedURLComponents = URLComponents()
  52. expectedURLComponents.scheme = callbackScheme
  53. expectedURLComponents.host = "firebaseauth"
  54. expectedURLComponents.path = "/link"
  55. guard let actualURL = actualURLComponents?.url,
  56. let expectedURL = expectedURLComponents.url else {
  57. return false
  58. }
  59. if expectedURL != actualURL {
  60. return false
  61. }
  62. let urlQueryItems = dictionary(withHttpArgumentsString: url.query)
  63. guard let deeplinkURLString = urlQueryItems["deep_link_id"],
  64. let deeplinkURL = URL(string: deeplinkURLString) else {
  65. return false
  66. }
  67. let deeplinkQueryItems = dictionary(withHttpArgumentsString: deeplinkURL.query)
  68. if deeplinkQueryItems["authType"] == authType, deeplinkQueryItems["eventId"] == eventID {
  69. return true
  70. }
  71. return false
  72. }
  73. /// Strips url of scheme and path string to extract domain name
  74. /// - Parameter urlString: URL string for domain
  75. static func extractDomain(urlString: String) -> String? {
  76. var domain = urlString
  77. // Check for the presence of a scheme (e.g., http:// or https://)
  78. if domain.prefix(7).caseInsensitiveCompare("http://") == .orderedSame {
  79. domain = String(domain.dropFirst(7))
  80. } else if domain.prefix(8).caseInsensitiveCompare("https://") == .orderedSame {
  81. domain = String(domain.dropFirst(8))
  82. }
  83. // Remove trailing slashes
  84. domain = (domain as NSString).standardizingPath as String
  85. // Split the URL by "/". The domain is the first component after removing the scheme.
  86. let urlComponents = domain.components(separatedBy: "/")
  87. return urlComponents.first
  88. }
  89. static func fetchAuthDomain(withRequestConfiguration requestConfiguration: AuthRequestConfiguration)
  90. async throws -> String {
  91. if let emulatorHostAndPort = requestConfiguration.emulatorHostAndPort {
  92. // If we are using the auth emulator, we do not want to call the GetProjectConfig endpoint.
  93. // The widget is hosted on the emulator host and port, so we can return that directly.
  94. return emulatorHostAndPort
  95. }
  96. let request = GetProjectConfigRequest(requestConfiguration: requestConfiguration)
  97. let response = try await AuthBackend.call(with: request)
  98. // Look up an authorized domain ends with one of the supportedAuthDomains.
  99. // The sequence of supportedAuthDomains matters. ("firebaseapp.com", "web.app")
  100. // The searching ends once the first valid supportedAuthDomain is found.
  101. var authDomain: String?
  102. if let customAuthDomain = requestConfiguration.auth?.customAuthDomain {
  103. if let customDomain = AuthWebUtils.extractDomain(urlString: customAuthDomain) {
  104. for domain in response.authorizedDomains ?? [] {
  105. if domain == customDomain {
  106. return domain
  107. }
  108. }
  109. }
  110. throw AuthErrorUtils.unauthorizedDomainError(
  111. message: "Error while validating application identity: The " +
  112. "configured custom domain is not allowlisted."
  113. )
  114. }
  115. for supportedAuthDomain in Self.supportedAuthDomains {
  116. for domain in response.authorizedDomains ?? [] {
  117. let index = domain.count - supportedAuthDomain.count
  118. if index >= 2, domain.hasSuffix(supportedAuthDomain),
  119. domain.count >= supportedAuthDomain.count + 2 {
  120. authDomain = domain
  121. break
  122. }
  123. }
  124. if authDomain != nil {
  125. break
  126. }
  127. }
  128. guard let authDomain = authDomain, !authDomain.isEmpty else {
  129. throw AuthErrorUtils.unexpectedErrorResponse(deserializedResponse: response)
  130. }
  131. return authDomain
  132. }
  133. static func queryItemValue(name: String, from queryList: [URLQueryItem]) -> String? {
  134. for item in queryList where item.name == name {
  135. return item.value
  136. }
  137. return nil
  138. }
  139. static func dictionary(withHttpArgumentsString argString: String?) -> [String: String] {
  140. guard let argString else {
  141. return [:]
  142. }
  143. var ret = [String: String]()
  144. let components = argString.components(separatedBy: "&")
  145. // Use reverse order so that the first occurrence of a key replaces
  146. // those subsequent.
  147. for component in components.reversed() {
  148. if component.isEmpty { continue }
  149. let pos = component.firstIndex(of: "=")
  150. var key: String
  151. var val: String
  152. if pos == nil {
  153. key = string(byUnescapingFromURLArgument: component)
  154. val = ""
  155. } else {
  156. let index = component.index(after: pos!)
  157. key = string(byUnescapingFromURLArgument: String(component[..<pos!]))
  158. val = string(byUnescapingFromURLArgument: String(component[index...]))
  159. }
  160. if key.isEmpty { key = "" }
  161. if val.isEmpty { val = "" }
  162. ret[key] = val
  163. }
  164. return ret
  165. }
  166. static func string(byUnescapingFromURLArgument argument: String) -> String {
  167. return argument
  168. .replacingOccurrences(of: "+", with: " ")
  169. .removingPercentEncoding ?? ""
  170. }
  171. static func parseURL(_ urlString: String) -> [String: String] {
  172. let urlComponents = URLComponents(string: urlString)
  173. guard let linkURL = urlComponents?.query else {
  174. return [:]
  175. }
  176. let queryComponents = linkURL.components(separatedBy: "&")
  177. var queryItems = [String: String]()
  178. for component in queryComponents {
  179. if let equalRange = component.range(of: "=") {
  180. let queryItemKey = component[..<equalRange.lowerBound].removingPercentEncoding
  181. let queryItemValue = component[equalRange.upperBound...].removingPercentEncoding
  182. if let queryItemKey = queryItemKey, let queryItemValue = queryItemValue {
  183. queryItems[queryItemKey] = queryItemValue
  184. }
  185. }
  186. }
  187. return queryItems
  188. }
  189. static var supportedAuthDomains: [String] {
  190. return ["firebaseapp.com", "web.app"]
  191. }
  192. }