Skip to content

implementing finalize signin for passkey #15173

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

Draft
wants to merge 2 commits into
base: passkey-new-start-signin
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions FirebaseAuth/Sources/Swift/Auth/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1669,6 +1669,34 @@ extension Auth: AuthInterop {
challenge: challengeInData
)
}

/// finalize sign in with passkey with existing credential assertion.
/// - Parameter platformCredential The existing credential assertion created by device.
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
public func finalizePasskeySignIn(withPlatformCredential platformCredential: ASAuthorizationPlatformPublicKeyCredentialAssertion) async throws
-> AuthDataResult {
let credentialID = platformCredential.credentialID.base64EncodedString()
let clientDataJSON = platformCredential.rawClientDataJSON.base64EncodedString()
let authenticatorData = platformCredential.rawAuthenticatorData.base64EncodedString()
let signature = platformCredential.signature.base64EncodedString()
let userID = platformCredential.userID.base64EncodedString()
let request = FinalizePasskeySignInRequest(
credentialID: credentialID,
clientDataJSON: clientDataJSON,
authenticatorData: authenticatorData,
signature: signature,
userId: userID,
requestConfiguration: requestConfiguration
)
let response = try await backend.call(with: request)
let user = try await Auth.auth().completeSignIn(
withAccessToken: response.idToken,
accessTokenExpirationDate: nil,
refreshToken: response.refreshToken,
anonymous: false
)
return AuthDataResult(withUser: user, additionalUserInfo: nil)
}
#endif

// MARK: Internal methods
Expand Down
1 change: 1 addition & 0 deletions FirebaseAuth/Sources/Swift/Backend/AuthBackend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,7 @@ final class AuthBackend: AuthBackendProtocol {
return AuthErrorUtils.credentialAlreadyInUseError(
message: serverDetailErrorMessage, credential: credential, email: email
)
case "INVALID_AUTHENTICATOR_RESPONSE": return AuthErrorUtils.invalidAuthenticatorResponse()
default:
if let underlyingErrors = errorDictionary["errors"] as? [[String: String]] {
for underlyingError in underlyingErrors {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* 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/LICENSE2.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.
*/

/// The GCIP endpoint for finalizePasskeySignIn rpc
private let finalizePasskeySignInEndPoint = "accounts/passkeySignIn:finalize"

class FinalizePasskeySignInRequest: IdentityToolkitRequest, AuthRPCRequest {
typealias Response = FinalizePasskeySignInResponse
/// The credential ID
let credentialID: String
/// The CollectedClientData object from the authenticator.
let clientDataJSON: String
/// The AuthenticatorData from the authenticator.
let authenticatorData: String
/// The signature from the authenticator.
let signature: String
/// The user handle
let userId: String

init(credentialID: String,
clientDataJSON: String,
authenticatorData: String,
signature: String,
userId: String,
requestConfiguration: AuthRequestConfiguration) {
self.credentialID = credentialID
self.clientDataJSON = clientDataJSON
self.authenticatorData = authenticatorData
self.signature = signature
self.userId = userId
super.init(
endpoint: finalizePasskeySignInEndPoint,
requestConfiguration: requestConfiguration,
useIdentityPlatform: true
)
}

var unencodedHTTPRequestBody: [String: AnyHashable]? {
var postBody: [String: AnyHashable] = [
"authenticatorAssertionResponse": [
"credentialId": credentialID,
"authenticatorAssertionResponse": [
"clientDataJSON": clientDataJSON,
"authenticatorData": authenticatorData,
"signature": signature,
"userHandle": userId,
],
] as [String: AnyHashable],
]
if let tenantID = tenantID {
postBody["tenantId"] = tenantID
}
return postBody
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* 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/LICENSE2.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.
*/

struct FinalizePasskeySignInResponse: AuthRPCResponse {
/// The user raw access token.
let idToken: String
/// Refresh token for the authenticated user.
let refreshToken: String

init(dictionary: [String: AnyHashable]) throws {
guard
let idToken = dictionary["idToken"] as? String,
let refreshToken = dictionary["refreshToken"] as? String
else {
throw AuthErrorUtils.unexpectedResponse(deserializedResponse: dictionary)
}
self.idToken = idToken
self.refreshToken = refreshToken
}
}
4 changes: 4 additions & 0 deletions FirebaseAuth/Sources/Swift/Utilities/AuthErrorUtils.swift
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,10 @@ class AuthErrorUtils {
error(code: .invalidRecaptchaToken)
}

static func invalidAuthenticatorResponse() -> Error {
error(code: .invalidAuthenticatorResponse)
}

static func unauthorizedDomainError(message: String?) -> Error {
error(code: .unauthorizedDomain, message: message)
}
Expand Down
11 changes: 11 additions & 0 deletions FirebaseAuth/Sources/Swift/Utilities/AuthErrors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,10 @@ import Foundation
/// Indicates that the reCAPTCHA SDK actions class failed to create.
case recaptchaActionCreationFailed = 17210

/// the authenticator response for passkey signin or enrollment is not parseable, missing required
/// fields, or certain fields are invalid values
case invalidAuthenticatorResponse = 17211

/// Indicates an error occurred while attempting to access the keychain.
case keychainError = 17995

Expand Down Expand Up @@ -528,6 +532,8 @@ import Foundation
return kErrorSiteKeyMissing
case .recaptchaActionCreationFailed:
return kErrorRecaptchaActionCreationFailed
case .invalidAuthenticatorResponse:
return kErrorInvalidAuthenticatorResponse
}
}

Expand Down Expand Up @@ -719,6 +725,8 @@ import Foundation
return "ERROR_RECAPTCHA_SITE_KEY_MISSING"
case .recaptchaActionCreationFailed:
return "ERROR_RECAPTCHA_ACTION_CREATION_FAILED"
case .invalidAuthenticatorResponse:
return "ERROR_INVALID_AUTHENTICATOR_RESPONSE"
}
}
}
Expand Down Expand Up @@ -996,3 +1004,6 @@ private let kErrorSiteKeyMissing =
private let kErrorRecaptchaActionCreationFailed =
"The reCAPTCHA SDK action class failed to initialize. See " +
"https://cloud.google.com/recaptcha-enterprise/docs/instrument-ios-apps"

private let kErrorInvalidAuthenticatorResponse =
"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."
119 changes: 119 additions & 0 deletions FirebaseAuth/Tests/Unit/AuthTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
static let kFakeRecaptchaVersion = "RecaptchaVersion"
static let kRpId = "FAKE_RP_ID"
static let kChallenge = "Y2hhbGxlbmdl"
private let kCredentialID = "FAKE_CREDENTIAL_ID"
private let kClientDataJSON = "FAKE_CLIENT_DATA"
private let kAuthenticatorData = "FAKE_AUTHENTICATOR_DATA"
private let kSignature = "FAKE_SIGNATURE"
private let kUserId = "FAKE_USERID"
var auth: Auth!
static var testNum = 0
var authDispatcherCallback: (() -> Void)?
Expand Down Expand Up @@ -89,7 +94,7 @@
return try self.rpcIssuer.respond(withJSON: ["signinMethods": allSignInMethods])
}

auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in

Check warning on line 97 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, macOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 97 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, tvOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 97 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, watchOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 97 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, catalyst)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 97 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-14, Xcode_16.2, iOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 97 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, iOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 97 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, visionOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.
// 4. After the response triggers the callback, verify the returned signInMethods.
XCTAssertTrue(Thread.isMainThread)
XCTAssertEqual(signInMethods, allSignInMethods)
Expand All @@ -110,7 +115,7 @@
let message = "TOO_MANY_ATTEMPTS_TRY_LATER"
return try self.rpcIssuer.respond(serverErrorMessage: message)
}
auth?.fetchSignInMethods(forEmail: kEmail) { signInMethods, error in

Check warning on line 118 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, macOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 118 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, tvOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 118 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, watchOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 118 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, catalyst)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 118 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-14, Xcode_16.2, iOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 118 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, iOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.

Check warning on line 118 in FirebaseAuth/Tests/Unit/AuthTests.swift

View workflow job for this annotation

GitHub Actions / spm / spm (macos-15, Xcode_16.4, visionOS)

'fetchSignInMethods(forEmail:completion:)' is deprecated: `fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled.
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(signInMethods)
let rpcError = (error as? NSError)!
Expand Down Expand Up @@ -2510,5 +2515,119 @@
}
waitForExpectations(timeout: 5)
}

/// Helper mock to simulate platform credential fields
struct MockPlatformCredential {
let credentialID: Data
let clientDataJSON: Data
let authenticatorData: Data
let signature: Data
let userID: Data
}

private func buildFinalizeRequest(mock: MockPlatformCredential)
-> FinalizePasskeySignInRequest {
return FinalizePasskeySignInRequest(
credentialID: kCredentialID,
clientDataJSON: kClientDataJSON,
authenticatorData: kAuthenticatorData,
signature: kSignature,
userId: kUserId,
requestConfiguration: auth!.requestConfiguration
)
}

func testFinalizePasskeysigninSuccess() async throws {
setFakeGetAccountProvider()
let expectation = expectation(description: #function)
rpcIssuer.respondBlock = {
let request = try XCTUnwrap(self.rpcIssuer?.request as? FinalizePasskeySignInRequest)
XCTAssertEqual(request.credentialID, self.kCredentialID)
XCTAssertNotNil(request.credentialID)
XCTAssertEqual(request.clientDataJSON, self.kClientDataJSON)
XCTAssertNotNil(request.clientDataJSON)
XCTAssertEqual(request.authenticatorData, self.kAuthenticatorData)
XCTAssertNotNil(request.authenticatorData)
XCTAssertEqual(request.signature, self.kSignature)
XCTAssertNotNil(request.signature)
XCTAssertEqual(request.userId, self.kUserId)
XCTAssertNotNil(request.userId)
return try self.rpcIssuer.respond(
withJSON: [
"idToken": RPCBaseTests.kFakeAccessToken,
"refreshToken": self.kRefreshToken,
]
)
}
let mock = MockPlatformCredential(
credentialID: Data(kCredentialID.utf8),
clientDataJSON: Data(kClientDataJSON.utf8),
authenticatorData: Data(kAuthenticatorData.utf8),
signature: Data(kSignature.utf8),
userID: Data(kUserId.utf8)
)
Task {
let request = self.buildFinalizeRequest(mock: mock)
_ = try await self.authBackend.call(with: request)
expectation.fulfill()
}
XCTAssertNotNil(AuthTests.kFakeAccessToken)
await fulfillment(of: [expectation], timeout: 5)
}

func testFinalizePasskeySignInFailure() async throws {
setFakeGetAccountProvider()
let expectation = expectation(description: #function)
rpcIssuer.respondBlock = {
// Simulate backend error (e.g., OperationNotAllowed)
try self.rpcIssuer.respond(serverErrorMessage: "OPERATION_NOT_ALLOWED")
}
let mock = MockPlatformCredential(
credentialID: Data(kCredentialID.utf8),
clientDataJSON: Data(kClientDataJSON.utf8),
authenticatorData: Data(kAuthenticatorData.utf8),
signature: Data(kSignature.utf8),
userID: Data(kUserId.utf8)
)
Task {
let request = self.buildFinalizeRequest(mock: mock)
do {
_ = try await self.authBackend.call(with: request)
XCTFail("Expected error but got success")
} catch {
let nsError = error as NSError
XCTAssertEqual(nsError.code, AuthErrorCode.operationNotAllowed.rawValue)
expectation.fulfill()
}
}
await fulfillment(of: [expectation], timeout: 5)
}

func testFinalizePasskeySignInFailureWithoutAssertion() async throws {
setFakeGetAccountProvider()
let expectation = expectation(description: #function)
rpcIssuer.respondBlock = {
try self.rpcIssuer.respond(serverErrorMessage: "INVALID_AUTHENTICATOR_RESPONSE")
}
let mock = MockPlatformCredential(
credentialID: Data(kCredentialID.utf8),
clientDataJSON: Data(), // Empty or missing data
authenticatorData: Data(kAuthenticatorData.utf8),
signature: Data(), // Empty or missing data
userID: Data(kUserId.utf8)
)
Task {
let request = self.buildFinalizeRequest(mock: mock)
do {
_ = try await self.authBackend.call(with: request)
XCTFail("Expected invalid_authenticator_response error")
} catch {
let nsError = error as NSError
XCTAssertEqual(nsError.code, AuthErrorCode.invalidAuthenticatorResponse.rawValue)
expectation.fulfill()
}
}
await fulfillment(of: [expectation], timeout: 5)
}
}
#endif
Loading
Loading