AuthWebUtils.swift 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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. backend: AuthBackend)
  91. async throws -> String {
  92. if let emulatorHostAndPort = requestConfiguration.emulatorHostAndPort {
  93. // If we are using the auth emulator, we do not want to call the GetProjectConfig endpoint.
  94. // The widget is hosted on the emulator host and port, so we can return that directly.
  95. return emulatorHostAndPort
  96. }
  97. let request = GetProjectConfigRequest(requestConfiguration: requestConfiguration)
  98. let response = try await backend.call(with: request)
  99. // Look up an authorized domain ends with one of the supportedAuthDomains.
  100. // The sequence of supportedAuthDomains matters. ("firebaseapp.com", "web.app")
  101. // The searching ends once the first valid supportedAuthDomain is found.
  102. var authDomain: String?
  103. if let customAuthDomain = requestConfiguration.auth?.customAuthDomain {
  104. if let customDomain = AuthWebUtils.extractDomain(urlString: customAuthDomain) {
  105. for domain in response.authorizedDomains ?? [] {
  106. if domain == customDomain {
  107. return domain
  108. }
  109. }
  110. }
  111. throw AuthErrorUtils.unauthorizedDomainError(
  112. message: "Error while validating application identity: The " +
  113. "configured custom domain is not allowlisted."
  114. )
  115. }
  116. for supportedAuthDomain in Self.supportedAuthDomains {
  117. for domain in response.authorizedDomains ?? [] {
  118. let index = domain.count - supportedAuthDomain.count
  119. if index >= 2, domain.hasSuffix(supportedAuthDomain),
  120. domain.count >= supportedAuthDomain.count + 2 {
  121. authDomain = domain
  122. break
  123. }
  124. }
  125. if authDomain != nil {
  126. break
  127. }
  128. }
  129. guard let authDomain = authDomain, !authDomain.isEmpty else {
  130. throw AuthErrorUtils.unexpectedErrorResponse(deserializedResponse: response)
  131. }
  132. return authDomain
  133. }
  134. static func queryItemValue(name: String, from queryList: [URLQueryItem]) -> String? {
  135. for item in queryList where item.name == name {
  136. return item.value
  137. }
  138. return nil
  139. }
  140. static func dictionary(withHttpArgumentsString argString: String?) -> [String: String] {
  141. guard let argString else {
  142. return [:]
  143. }
  144. var ret = [String: String]()
  145. let components = argString.components(separatedBy: "&")
  146. // Use reverse order so that the first occurrence of a key replaces
  147. // those subsequent.
  148. for component in components.reversed() {
  149. if component.isEmpty { continue }
  150. let pos = component.firstIndex(of: "=")
  151. var key: String
  152. var val: String
  153. if pos == nil {
  154. key = string(byUnescapingFromURLArgument: component)
  155. val = ""
  156. } else {
  157. let index = component.index(after: pos!)
  158. key = string(byUnescapingFromURLArgument: String(component[..<pos!]))
  159. val = string(byUnescapingFromURLArgument: String(component[index...]))
  160. }
  161. if key.isEmpty { key = "" }
  162. if val.isEmpty { val = "" }
  163. ret[key] = val
  164. }
  165. return ret
  166. }
  167. static func string(byUnescapingFromURLArgument argument: String) -> String {
  168. return argument
  169. .replacingOccurrences(of: "+", with: " ")
  170. .removingPercentEncoding ?? ""
  171. }
  172. static func parseURL(_ urlString: String) -> [String: String] {
  173. let urlComponents = URLComponents(string: urlString)
  174. guard let linkURL = urlComponents?.query else {
  175. return [:]
  176. }
  177. let queryComponents = linkURL.components(separatedBy: "&")
  178. var queryItems = [String: String]()
  179. for component in queryComponents {
  180. if let equalRange = component.range(of: "=") {
  181. let queryItemKey = component[..<equalRange.lowerBound].removingPercentEncoding
  182. let queryItemValue = component[equalRange.upperBound...].removingPercentEncoding
  183. if let queryItemKey = queryItemKey, let queryItemValue = queryItemValue {
  184. queryItems[queryItemKey] = queryItemValue
  185. }
  186. }
  187. }
  188. return queryItems
  189. }
  190. static var supportedAuthDomains: [String] {
  191. return ["firebaseapp.com", "web.app"]
  192. }
  193. }