-
Notifications
You must be signed in to change notification settings - Fork 1.7k
SwiftAPI Tests in Authentication Example for Passkey #15213
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
srushtisv
wants to merge
4
commits into
passkey-end-to-end-ui-tests
Choose a base branch
from
passkey-integration-tests-sv
base: passkey-end-to-end-ui-tests
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -309,36 +309,39 @@ class AuthenticationExampleUITests: XCTestCase { | |
) | ||
} | ||
|
||
func testPasskeyList() { | ||
signOut() | ||
let testEmail = "[email protected]" | ||
let testPassword = "sample.ios.auth" | ||
let testPasskeyName = "sampleiosauth" | ||
app.staticTexts["Email & Password Login"].tap() | ||
app.textFields["Email"].tap() | ||
app.textFields["Email"].typeText(testEmail) | ||
app.textFields["Password"].tap() | ||
app.textFields["Password"].typeText(testPassword) | ||
app.buttons["Login"].tap() | ||
wait(forElement: app.navigationBars["User"], timeout: 5.0) | ||
XCTAssertTrue(app.navigationBars["User"].exists) | ||
XCTAssertTrue( | ||
app.staticTexts[testEmail].exists, | ||
"The user should be signed in and the email field should display their email." | ||
) | ||
let userTable = app.tables.firstMatch | ||
XCTAssertTrue(userTable.waitForExistence(timeout: 5.0), "User detail list should exist") | ||
let passkeyLabel = userTable.staticTexts[testPasskeyName] | ||
if !passkeyLabel.exists { | ||
for _ in 0 ..< 5 where !passkeyLabel.exists { | ||
userTable.swipeUp() | ||
#if os(iOS) || os(tvOS) || os(macOS) | ||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testPasskeyList() { | ||
signOut() | ||
let testEmail = "[email protected]" | ||
let testPassword = "sample.ios.auth" | ||
let testPasskeyName = "sampleiosauth" | ||
app.staticTexts["Email & Password Login"].tap() | ||
app.textFields["Email"].tap() | ||
app.textFields["Email"].typeText(testEmail) | ||
app.textFields["Password"].tap() | ||
app.textFields["Password"].typeText(testPassword) | ||
app.buttons["Login"].tap() | ||
wait(forElement: app.navigationBars["User"], timeout: 5.0) | ||
XCTAssertTrue(app.navigationBars["User"].exists) | ||
XCTAssertTrue( | ||
app.staticTexts[testEmail].exists, | ||
"The user should be signed in and the email field should display their email." | ||
) | ||
let userTable = app.tables.firstMatch | ||
XCTAssertTrue(userTable.waitForExistence(timeout: 5.0), "User detail list should exist") | ||
let passkeyLabel = userTable.staticTexts[testPasskeyName] | ||
if !passkeyLabel.exists { | ||
for _ in 0 ..< 5 where !passkeyLabel.exists { | ||
userTable.swipeUp() | ||
} | ||
} | ||
XCTAssertTrue( | ||
passkeyLabel.waitForExistence(timeout: 5.0), | ||
"Passkey named '\(testPasskeyName)' should be visible in the Passkeys section." | ||
) | ||
} | ||
XCTAssertTrue( | ||
passkeyLabel.waitForExistence(timeout: 5.0), | ||
"Passkey named '\(testPasskeyName)' should be visible in the Passkeys section." | ||
) | ||
} | ||
#endif | ||
|
||
// MARK: - Private Helpers | ||
|
||
|
270 changes: 270 additions & 0 deletions
270
FirebaseAuth/Tests/SampleSwift/SwiftApiTests/PasskeyTests.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,270 @@ | ||
/* | ||
* Copyright 2025 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
#if os(iOS) || os(tvOS) || os(macOS) | ||
|
||
import AuthenticationServices | ||
@testable import FirebaseAuth | ||
import Foundation | ||
import XCTest | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
class PasskeyTests: TestsBase { | ||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testStartPasskeyEnrollmentResponseSuccess() async throws { | ||
try await signInAnonymouslyAsync() | ||
guard let user = Auth.auth().currentUser else { | ||
XCTFail("Expected a signed-in user") | ||
return | ||
} | ||
try? await user.reload() | ||
let request = try await user.startPasskeyEnrollment(withName: "Test1Passkey") | ||
XCTAssertFalse(request.relyingPartyIdentifier.isEmpty, "rpID should be non-empty") | ||
XCTAssertFalse(request.challenge.isEmpty, "challenge should be non-empty") | ||
XCTAssertNotNil(request.userID, "userID should be present") | ||
XCTAssertNotNil(request as ASAuthorizationPlatformPublicKeyCredentialRegistrationRequest) | ||
try? await deleteCurrentUserAsync() | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testStartPasskeyEnrollmentFailureWithInvalidToken() async throws { | ||
try await signInAnonymouslyAsync() | ||
guard let user = Auth.auth().currentUser else { | ||
XCTFail("Expected a signed-in user") | ||
return | ||
} | ||
let config = user.requestConfiguration | ||
let token = "invalidToken" | ||
let badRequest = StartPasskeyEnrollmentRequest(idToken: token, requestConfiguration: config) | ||
do { | ||
_ = try await user.backend.call(with: badRequest) | ||
XCTFail("Expected .invalidUserToken") | ||
} catch { | ||
let ns = error as NSError | ||
if let code = AuthErrorCode(rawValue: ns.code) { | ||
XCTAssertEqual(code, .invalidUserToken, "Expected .invalidUserToken, got \(code)") | ||
} else { | ||
XCTFail("Unexpected error: \(error)") | ||
} | ||
let message = (ns.userInfo[NSLocalizedDescriptionKey] as? String ?? "").uppercased() | ||
XCTAssertTrue( | ||
message | ||
.contains( | ||
"THIS USER'S CREDENTIAL ISN'T VALID FOR THIS PROJECT. THIS CAN HAPPEN IF THE USER'S TOKEN HAS BEEN TAMPERED WITH, OR IF THE USER DOESN’T BELONG TO THE PROJECT ASSOCIATED WITH THE API KEY USED IN YOUR REQUEST." | ||
), | ||
"Expected invalidUserToken, got: \(message)" | ||
) | ||
} | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testFinalizePasskeyEnrollmentFailureWithInvalidToken() async throws { | ||
try await signInAnonymouslyAsync() | ||
guard let user = Auth.auth().currentUser else { | ||
XCTFail("Expected a signed-in user") | ||
return | ||
} | ||
let badRequest = FinalizePasskeyEnrollmentRequest( | ||
idToken: "invalidToken", | ||
name: "fakeName", | ||
credentialID: "fakeCredentialId".data(using: .utf8)!.base64EncodedString(), | ||
clientDataJSON: "fakeClientData".data(using: .utf8)!.base64EncodedString(), | ||
attestationObject: "fakeAttestion".data(using: .utf8)!.base64EncodedString(), | ||
requestConfiguration: user.requestConfiguration | ||
) | ||
do { | ||
_ = try await user.backend.call(with: badRequest) | ||
XCTFail("Expected invalid_user_token") | ||
} catch { | ||
let ns = error as NSError | ||
if let code = AuthErrorCode(rawValue: ns.code) { | ||
XCTAssertEqual(code, .invalidUserToken, "Expected .invalidUserToken, got \(code)") | ||
} | ||
let message = (ns.userInfo[NSLocalizedDescriptionKey] as? String ?? "").uppercased() | ||
XCTAssertTrue( | ||
message | ||
.contains( | ||
"THIS USER'S CREDENTIAL ISN'T VALID FOR THIS PROJECT. THIS CAN HAPPEN IF THE USER'S TOKEN HAS BEEN TAMPERED WITH, OR IF THE USER DOESN’T BELONG TO THE PROJECT ASSOCIATED WITH THE API KEY USED IN YOUR REQUEST." | ||
), | ||
"Expected invalidUserToken, got: \(message)" | ||
) | ||
} | ||
try? await deleteCurrentUserAsync() | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testFinalizePasskeyEnrollmentFailureWithoutAttestation() async throws { | ||
try await signInAnonymouslyAsync() | ||
guard let user = Auth.auth().currentUser else { | ||
XCTFail("Expected a signed-in user") | ||
return | ||
} | ||
try? await user.reload() | ||
let token = user.rawAccessToken() | ||
let badRequest = FinalizePasskeyEnrollmentRequest( | ||
idToken: token, | ||
name: "fakeName", | ||
credentialID: "fakeCredentialId".data(using: .utf8)!.base64EncodedString(), | ||
clientDataJSON: "fakeClientData".data(using: .utf8)!.base64EncodedString(), | ||
attestationObject: "fakeAttestion".data(using: .utf8)!.base64EncodedString(), | ||
requestConfiguration: user.requestConfiguration | ||
) | ||
do { | ||
_ = try await user.backend.call(with: badRequest) | ||
XCTFail("Expected invalid_authenticator_response") | ||
} catch { | ||
let ns = error as NSError | ||
if let code = AuthErrorCode(rawValue: ns.code) { | ||
XCTAssertEqual(code, .invalidAuthenticatorResponse, | ||
"Expected .invalidAuthenticatorResponse, got \(code)") | ||
} | ||
let message = (ns.userInfo[NSLocalizedDescriptionKey] as? String ?? "").uppercased() | ||
XCTAssertTrue( | ||
message | ||
.contains( | ||
"DURING PASSKEY ENROLLMENT AND SIGN IN, THE AUTHENTICATOR RESPONSE IS NOT PARSEABLE, MISSING REQUIRED FIELDS, OR CERTAIN FIELDS ARE INVALID VALUES THAT COMPROMISE THE SECURITY OF THE SIGN-IN OR ENROLLMENT." | ||
), | ||
"Expected INVALID_AUTHENTICATOR_RESPONSE, got: \(message)" | ||
) | ||
} | ||
try? await deleteCurrentUserAsync() | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testStartPasskeySignInSuccess() async throws { | ||
let assertionRequest = try await Auth.auth().startPasskeySignIn() | ||
XCTAssertFalse(assertionRequest.relyingPartyIdentifier.isEmpty, | ||
"rpID should be non-empty") | ||
XCTAssertFalse(assertionRequest.challenge.isEmpty, | ||
"challenge should be non-empty") | ||
XCTAssertNotNil( | ||
assertionRequest as ASAuthorizationPlatformPublicKeyCredentialAssertionRequest | ||
) | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testFinalizePasskeySignInFailureInvalidAttestation() async throws { | ||
let auth = Auth.auth() | ||
let config = auth.requestConfiguration | ||
let badRequest = FinalizePasskeySignInRequest( | ||
credentialID: "fakeCredentialId".data(using: .utf8)!.base64EncodedString(), | ||
clientDataJSON: "fakeClientData".data(using: .utf8)!.base64EncodedString(), | ||
authenticatorData: "fakeAuthenticatorData".data(using: .utf8)!.base64EncodedString(), | ||
signature: "fakeSignature".data(using: .utf8)!.base64EncodedString(), | ||
userId: "fakeUID".data(using: .utf8)!.base64EncodedString(), | ||
requestConfiguration: config | ||
) | ||
do { | ||
_ = try await auth.backend.call(with: badRequest) | ||
} catch { | ||
let ns = error as NSError | ||
if let code = AuthErrorCode(rawValue: ns.code) { | ||
XCTAssertEqual(code, .userNotFound) | ||
} | ||
} | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testFinalizePasskeySignInFailureIncorrectAttestation() async throws { | ||
let auth = Auth.auth() | ||
let config = auth.requestConfiguration | ||
let badRequest = FinalizePasskeySignInRequest( | ||
credentialID: "", | ||
clientDataJSON: "", | ||
authenticatorData: "", | ||
signature: "", | ||
userId: "", | ||
requestConfiguration: config | ||
) | ||
do { | ||
_ = try await auth.backend.call(with: badRequest) | ||
} catch { | ||
let ns = error as NSError | ||
if let code = AuthErrorCode(rawValue: ns.code) { | ||
XCTAssertEqual(code, .userNotFound) | ||
} | ||
} | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func DRAFTtestUnenrollPasskeySuccess() async throws { | ||
let testEmail = "[email protected]" | ||
let testPassword = "sample.ios.auth" | ||
let testCredentialId = "cred_id" | ||
let auth = Auth.auth() | ||
try await auth.signIn(withEmail: testEmail, password: testPassword) | ||
guard let user = Auth.auth().currentUser else { | ||
XCTFail("Expected a signed-in user") | ||
return | ||
} | ||
try? await user.reload() | ||
let prevPasskeys = user.enrolledPasskeys ?? [] | ||
XCTAssertTrue( | ||
prevPasskeys.contains { $0.credentialID == testCredentialId }, | ||
"Precondition failed: passkey \(testCredentialId) is not enrolled on this account." | ||
) | ||
let prevCount = prevPasskeys.count | ||
let _ = try await user.unenrollPasskey(withCredentialID: testCredentialId) | ||
try? await user.reload() | ||
let updatedPasskeys = user.enrolledPasskeys ?? [] | ||
XCTAssertFalse( | ||
updatedPasskeys.contains { $0.credentialID == testCredentialId }, | ||
"Passkey \(testCredentialId) should be removed after unenroll." | ||
) | ||
XCTAssertEqual( | ||
updatedPasskeys.count, prevCount - 1, | ||
"Exactly one passkey should have been removed." | ||
) | ||
XCTAssertNil( | ||
updatedPasskeys.first { $0.credentialID == testCredentialId }, | ||
"Passkey \(testCredentialId) should not exist after unenroll." | ||
) | ||
} | ||
|
||
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *) | ||
func testUnenrollPasskeyFailure() async throws { | ||
let testEmail = "[email protected]" | ||
let testPassword = "sample.ios.auth" | ||
let testCredentialId = "FCBopZ3mzjfPNXqWXXjAM/ZnnlQ=" | ||
let auth = Auth.auth() | ||
try await auth.signIn(withEmail: testEmail, password: testPassword) | ||
guard let user = Auth.auth().currentUser else { | ||
XCTFail("Expected a signed-in user") | ||
return | ||
} | ||
try? await user.reload() | ||
do { | ||
let _ = try await user.unenrollPasskey(withCredentialID: testCredentialId) | ||
XCTFail("Expected invalid passkey error") | ||
} catch { | ||
let ns = error as NSError | ||
if let code = AuthErrorCode(rawValue: ns.code) { | ||
XCTAssertEqual(code, .missingPasskeyEnrollment, | ||
"Expected .missingPasskeyEnrollment, got \(code)") | ||
} | ||
let message = (ns.userInfo[NSLocalizedDescriptionKey] as? String ?? "").uppercased() | ||
XCTAssertTrue( | ||
message | ||
.contains( | ||
"CANNOT FIND THE PASSKEY LINKED TO THE CURRENT ACCOUNT" | ||
), | ||
"Expected Missing Passkey Enrollment error, got: \(message)" | ||
) | ||
} | ||
} | ||
} | ||
|
||
#endif |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's remove this test as we won't be able to run it anytime soon. Thanks for trying out.