Просмотр исходного кода

Fix Phone Auth via APNS for Sandbox Tokens and update Sample's Firebase app (#13539)

Co-authored-by: Nick Cooke <nickcooke@google.com>
Paul Beusterien 1 год назад
Родитель
Сommit
f71480cd9d

+ 1 - 0
FirebaseAuth/CHANGELOG.md

@@ -1,6 +1,7 @@
 # 11.2.0
 - [Fixed] Fixed crashes that could occur in Swift continuation blocks running in the Xcode 16
   betas. (#13480)
+- [Fixed] Fixed Phone Auth via Sandbox APNS tokens that broke in 11.0.0. (#13479)
 
 # 11.1.0
 - [fixed] Fixed `Swift.error` conformance for `AuthErrorCode`. (#13430)

+ 5 - 4
FirebaseAuth/Sources/Swift/Backend/VerifyClientRequest.swift

@@ -32,7 +32,9 @@ class VerifyClientRequest: IdentityToolkitRequest, AuthRPCRequest {
     if let appToken = appToken {
       postBody[Self.appTokenKey] = appToken
     }
-    postBody[Self.isSandboxKey] = isSandbox
+    if isSandbox {
+      postBody[Self.isSandboxKey] = true
+    }
     return postBody
   }
 
@@ -42,11 +44,10 @@ class VerifyClientRequest: IdentityToolkitRequest, AuthRPCRequest {
   /// The flag that denotes if the appToken  pertains to Sandbox or Production.
   private(set) var isSandbox: Bool
 
-  init(withAppToken: String?,
+  init(withAppToken appToken: String?,
        isSandbox: Bool,
        requestConfiguration: AuthRequestConfiguration) {
-    appToken = withAppToken
-    self.isSandbox = isSandbox
+    self.appToken = appToken
     self.isSandbox = isSandbox
     super.init(endpoint: Self.verifyClientEndpoint, requestConfiguration: requestConfiguration)
   }

+ 6 - 12
FirebaseAuth/Sources/Swift/SystemService/AuthAPNSTokenManager.swift

@@ -143,18 +143,11 @@
       }
 
       // TODO: resolve https://github.com/firebase/firebase-ios-sdk/issues/10921
-      if Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" {
-        // Distributed via TestFlight
-        return defaultAppTypeProd
-      }
+      // to support TestFlight
 
-      let path = Bundle.main.bundlePath + "embedded.mobileprovision"
-      guard let url = URL(string: path) else {
-        AuthLog.logInfo(code: "I-AUT000007", message: "\(path) does not exist")
-        return defaultAppTypeProd
-      }
+      let path = Bundle.main.bundlePath + "/" + "embedded.mobileprovision"
       do {
-        let profileData = try Data(contentsOf: url)
+        let profileData = try NSData(contentsOfFile: path) as Data
 
         // The "embedded.mobileprovision" sometimes contains characters with value 0, which signals
         // the end of a c-string and halts the ASCII parser, or with value > 127, which violates
@@ -177,7 +170,7 @@
 
         let scanner = Scanner(string: embeddedProfile)
         if scanner.scanUpToString("<plist") != nil {
-          guard let plistContents = scanner.scanUpToString("</plist>"),
+          guard let plistContents = scanner.scanUpToString("</plist>")?.appending("</plist>"),
                 let data = plistContents.data(using: .utf8) else {
             return defaultAppTypeProd
           }
@@ -194,7 +187,8 @@
                               message: "Provisioning profile has specifically provisioned devices, " +
                                 "most likely a Dev profile.")
             }
-            guard let apsEnvironment = plistMap["Entitlements.aps-environment"] as? String else {
+            guard let entitlements = plistMap["Entitlements"] as? [String: Any],
+                  let apsEnvironment = entitlements["aps-environment"] as? String else {
               AuthLog.logInfo(code: "I-AUT000013",
                               message: "No aps-environment set. If testing on a device APNS is not " +
                                 "correctly configured. Please recheck your provisioning profiles.")

+ 2 - 2
FirebaseAuth/Tests/SampleSwift/AuthenticationExample.xcodeproj/project.pbxproj

@@ -794,7 +794,7 @@
 					"$(inherited)",
 					"@executable_path/Frameworks",
 				);
-				PRODUCT_BUNDLE_IDENTIFIER = com.google.FirebaseExperimental1;
+				PRODUCT_BUNDLE_IDENTIFIER = com.google.firebaseAuthSDKSampleApp.dev;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				PROVISIONING_PROFILE_SPECIFIER = "";
 				SWIFT_VERSION = 5.0;
@@ -817,7 +817,7 @@
 					"$(inherited)",
 					"@executable_path/Frameworks",
 				);
-				PRODUCT_BUNDLE_IDENTIFIER = com.google.FirebaseExperimental1;
+				PRODUCT_BUNDLE_IDENTIFIER = com.google.firebaseAuthSDKSampleApp.dev;
 				PRODUCT_NAME = "$(TARGET_NAME)";
 				PROVISIONING_PROFILE_SPECIFIER = "";
 				SWIFT_VERSION = 5.0;

+ 6 - 0
FirebaseAuth/Tests/SampleSwift/AuthenticationExample.xcodeproj/xcshareddata/xcschemes/AuthenticationExample.xcscheme

@@ -81,6 +81,12 @@
             ReferencedContainer = "container:AuthenticationExample.xcodeproj">
          </BuildableReference>
       </BuildableProductRunnable>
+      <CommandLineArguments>
+         <CommandLineArgument
+            argument = "-FIRDebugEnabled"
+            isEnabled = "YES">
+         </CommandLineArgument>
+      </CommandLineArguments>
    </LaunchAction>
    <ProfileAction
       buildConfiguration = "Release"

+ 2 - 2
FirebaseAuth/Tests/SampleSwift/AuthenticationExampleUITests/SettingsUITests.swift

@@ -50,11 +50,11 @@ class SettingsUITests: XCTestCase {
 
     // Swap Firebase App
     let appCell = app.cells.containing(.staticText, identifier: "Active App").element
-    XCTAssertTrue(appCell.staticTexts["gcip-ios-test"].exists)
+    XCTAssertTrue(appCell.staticTexts["fir-ios-auth-sample"].exists)
     appCell.tap()
     XCTAssertTrue(appCell.staticTexts["fb-sa-upgraded"].exists)
     appCell.tap()
-    XCTAssertTrue(appCell.staticTexts["gcip-ios-test"].exists)
+    XCTAssertTrue(appCell.staticTexts["fir-ios-auth-sample"].exists)
 
     // Current Access Group
     let accessCell = app.cells.containing(.staticText, identifier: "Current Access Group").element

+ 1 - 38
FirebaseAuth/Tests/SampleSwift/ObjCApiTests/AccountInfoTests.m

@@ -51,52 +51,15 @@ static NSString *const kNewUserEmail = @"user+user_new_email@example.com";
     XCTFail(@"Could not obtain auth object.");
   }
 
-  __block NSError *apiError;
   XCTestExpectation *expectation =
       [self expectationWithDescription:@"Created account with email and password."];
   [auth createUserWithEmail:kOldUserEmail
                    password:@"password"
                  completion:^(FIRAuthDataResult *user, NSError *error) {
-                   if (error.code != FIRAuthErrorCodeEmailAlreadyInUse) {
-                     apiError = error;
-                   }
+                   XCTAssertEqual(error.code, FIRAuthErrorCodeEmailAlreadyInUse);
                    [expectation fulfill];
                  }];
   [self waitForExpectationsWithTimeout:kExpectationsTimeout handler:nil];
 }
 
-- (void)testUpdatingUsersEmail {
-  SKIP_IF_ON_MOBILE_HARNESS
-  FIRAuth *auth = [FIRAuth auth];
-  if (!auth) {
-    XCTFail(@"Could not obtain auth object.");
-  }
-
-  __block NSError *apiError;
-  XCTestExpectation *expectation = [self expectationWithDescription:@"Updating email"];
-  [auth signInWithEmail:kOldUserEmail
-               password:@"password"
-             completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
-               apiError = error;
-               [expectation fulfill];
-             }];
-  [self waitForExpectationsWithTimeout:kExpectationsTimeout handler:nil];
-
-  XCTAssertEqualObjects(auth.currentUser.email, kOldUserEmail);
-  XCTAssertNil(apiError);
-
-  expectation = [self expectationWithDescription:@"Update email address."];
-  [auth.currentUser updateEmail:kNewUserEmail
-                     completion:^(NSError *_Nullable error) {
-                       apiError = error;
-                       [expectation fulfill];
-                     }];
-  [self waitForExpectationsWithTimeout:kExpectationsTimeout handler:nil];
-  XCTAssertNil(apiError);
-  XCTAssertEqualObjects(auth.currentUser.email, kNewUserEmail);
-
-  // Clean up the created Firebase user for future runs.
-  [self deleteCurrentUser];
-}
-
 @end

+ 0 - 15
FirebaseAuth/Tests/SampleSwift/SwiftApiTests/AccountInfoTests.swift

@@ -63,16 +63,6 @@ class AccountInfoTests: TestsBase {
       expectation2.fulfill()
     }
     waitForExpectations(timeout: TestsBase.kExpectationsTimeout)
-
-    let expectation3 = expectation(description: "Update email address.")
-    auth.currentUser?.updateEmail(to: kNewUserEmail) { error in
-      XCTAssertNil(error)
-      XCTAssertEqual(auth.currentUser?.email,
-                     self.kNewUserEmail,
-                     "Signed user does not match change.")
-      expectation3.fulfill()
-    }
-    waitForExpectations(timeout: TestsBase.kExpectationsTimeout)
   }
 
   func testUpdatingUsersEmailAsync() async throws {
@@ -91,10 +81,5 @@ class AccountInfoTests: TestsBase {
     XCTAssertEqual(auth.currentUser?.email,
                    kOldUserEmail,
                    "Signed user does not match request.")
-
-    try await auth.currentUser?.updateEmail(to: kNewUserEmail)
-    XCTAssertEqual(auth.currentUser?.email,
-                   kNewUserEmail,
-                   "Signed user does not match change.")
   }
 }

+ 11 - 0
FirebaseAuth/Tests/SampleSwift/SwiftApiTests/Credentials.swift

@@ -49,8 +49,19 @@ import Foundation
  */
 
 enum Credentials {
+  /// The `CLIENT_ID` key from a`GoogleService-Info.plist`. If this cannot be
+  /// found, enable Google Sign In enabled as an authentication provider in the
+  /// corresponding Firebase project and re-download the
+  /// `GoogleService-Info.plist`.
   static let kGoogleClientID = KGOOGLE_CLIENT_ID
+  /// This is the refresh token associated with the
+  /// `firebase.ios.testing@gmail.com` test acount.
+  /// In the event this token needs to be generated, this refresh token is
+  /// returned upon successful sign-in via GSI via the `GIDSignInResult`'s
+  /// `user.refreshToken.tokenString` property.
   static let kGoogleTestAccountRefreshToken = KGOOGLE_TEST_ACCOUNT_REFRESH_TOKEN
+  /// This is the display name for the `firebase.ios.testing@gmail.com` test
+  /// account.
   static let kGoogleUserName = KGOOGLE_USER_NAME
   static let kFacebookAppID = KFACEBOOK_APP_ID
   static let kFacebookAppAccessToken = KFACEBOOK_APP_ACCESS_TOKEN

+ 1 - 1
FirebaseAuth/Tests/SampleSwift/SwiftApiTests/GoogleTests.swift

@@ -47,7 +47,7 @@ class GoogleTests: TestsBase {
                                                    accessToken: googleAccessToken)
     _ = try await auth.signIn(with: credential)
     let displayName = try XCTUnwrap(auth.currentUser?.displayName)
-    XCTAssertEqual(displayName, "apitests ios")
+    XCTAssertEqual(displayName, Credentials.kGoogleUserName)
   }
 
   /// Sends http request to Google OAuth2 token server to use refresh token to exchange for Google

BIN
scripts/gha-encrypted/AuthSample/AuthCredentials.h.gpg


BIN
scripts/gha-encrypted/AuthSample/Credentials.swift.gpg


BIN
scripts/gha-encrypted/AuthSample/GoogleService-Info.plist.gpg


BIN
scripts/gha-encrypted/AuthSample/SwiftApplication.plist.gpg