Skip to content

implementing start passkey sign-in #15168

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 5 commits into
base: passkey-new
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
30 changes: 30 additions & 0 deletions FirebaseAuth/Sources/Swift/Auth/Auth.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ import FirebaseCoreExtension
import UIKit
#endif

#if os(iOS) || os(tvOS) || os(macOS) || targetEnvironment(macCatalyst)
import AuthenticationServices
#endif

// Export the deprecated Objective-C defined globals and typedefs.
#if SWIFT_PACKAGE
@_exported import FirebaseAuthInternal
Expand Down Expand Up @@ -1641,6 +1645,32 @@ extension Auth: AuthInterop {
public static let authStateDidChangeNotification =
NSNotification.Name(rawValue: "FIRAuthStateDidChangeNotification")

// MARK: Passkey Implementation

#if os(iOS) || os(tvOS) || os(macOS) || targetEnvironment(macCatalyst)

/// starts sign in with passkey retrieving challenge from GCIP and create an assertion request.
@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
public func startPasskeySignIn() async throws ->
ASAuthorizationPlatformPublicKeyCredentialAssertionRequest {
let request = StartPasskeySignInRequest(requestConfiguration: requestConfiguration)
let response = try await backend.call(with: request)
guard let challengeInData = Data(base64Encoded: response.challenge) else {
throw NSError(
domain: AuthErrorDomain,
code: AuthInternalErrorCode.RPCResponseDecodingError.rawValue,
userInfo: [NSLocalizedDescriptionKey: "Failed to decode base64 challenge from response."]
)
}
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(
relyingPartyIdentifier: response.rpID
)
return provider.createCredentialAssertionRequest(
challenge: challengeInData
)
}
#endif

// MARK: Internal methods

init(app: FirebaseApp,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// 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.

/// The GCIP endpoint for startPasskeySignIn rpc
private let startPasskeySignInEndpoint = "accounts/passkeySignIn:start"

@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
class StartPasskeySignInRequest: IdentityToolkitRequest, AuthRPCRequest {
typealias Response = StartPasskeySignInResponse

init(requestConfiguration: AuthRequestConfiguration) {
super.init(
endpoint: startPasskeySignInEndpoint,
requestConfiguration: requestConfiguration,
useIdentityPlatform: true
)
}

var unencodedHTTPRequestBody: [String: AnyHashable]? {
guard let tenantID = tenantID else {
return nil
}
return ["tenantId": tenantID]
}
}
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/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.

@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
struct StartPasskeySignInResponse: AuthRPCResponse {
/// The RP ID of the FIDO Relying Party
let rpID: String
/// The FIDO challenge
let challenge: String

init(dictionary: [String: AnyHashable]) throws {
guard let options = dictionary["credentialRequestOptions"] as? [String: Any] else {
throw AuthErrorUtils.unexpectedResponse(deserializedResponse: dictionary)
}
guard let rpID = options["rpId"] as? String,
let challenge = options["challenge"] as? String else {
throw AuthErrorUtils.unexpectedResponse(deserializedResponse: dictionary)
}
self.rpID = rpID
self.challenge = challenge
}
}
57 changes: 57 additions & 0 deletions FirebaseAuth/Tests/Unit/AuthTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
static let kFakeAPIKey = "FAKE_API_KEY"
static let kFakeRecaptchaResponse = "RecaptchaResponse"
static let kFakeRecaptchaVersion = "RecaptchaVersion"
static let kRpId = "FAKE_RP_ID"
static let kChallenge = "Y2hhbGxlbmdl"
var auth: Auth!
static var testNum = 0
var authDispatcherCallback: (() -> Void)?
Expand Down Expand Up @@ -87,7 +89,7 @@
return try self.rpcIssuer.respond(withJSON: ["signinMethods": allSignInMethods])
}

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

Check warning on line 92 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 92 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 92 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 92 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 92 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.

Check warning on line 92 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 92 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.
// 4. After the response triggers the callback, verify the returned signInMethods.
XCTAssertTrue(Thread.isMainThread)
XCTAssertEqual(signInMethods, allSignInMethods)
Expand All @@ -108,7 +110,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 113 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 113 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 113 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 113 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 113 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.

Check warning on line 113 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 113 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.
XCTAssertTrue(Thread.isMainThread)
XCTAssertNil(signInMethods)
let rpcError = (error as? NSError)!
Expand Down Expand Up @@ -2455,3 +2457,58 @@
XCTAssertEqual(user.providerData.count, 0)
}
}

// MARK: Passkey Sign-In Tests

#if os(iOS)
import AuthenticationServices

@available(iOS 15.0, *)
extension AuthTests {
func testStartPasskeySignInSuccess() throws {
let expectation = self.expectation(description: #function)
let expectedChallenge = AuthTests.kChallenge // base64 string
let expectedRpId = AuthTests.kRpId
let expectedChallengeData = Data(base64Encoded: expectedChallenge)!
rpcIssuer.respondBlock = {
let request = try XCTUnwrap(self.rpcIssuer.request as? StartPasskeySignInRequest)
XCTAssertEqual(request.apiKey, AuthTests.kFakeAPIKey)
return try self.rpcIssuer.respond(withJSON: [
"credentialRequestOptions": [
"rpId": expectedRpId,
"challenge": expectedChallenge,
],
])
}
Task {
do {
let assertionRequest = try await self.auth.startPasskeySignIn()
XCTAssertEqual(assertionRequest.challenge, expectedChallengeData)
XCTAssertEqual(assertionRequest.relyingPartyIdentifier, expectedRpId)
expectation.fulfill()
} catch {
XCTFail("Unexpected error: \(error)")
}
}
waitForExpectations(timeout: 5)
}

func testStartPasskeySignInFailure() throws {
let expectation = self.expectation(description: #function)
rpcIssuer.respondBlock = {
try self.rpcIssuer.respond(serverErrorMessage: "OPERATION_NOT_ALLOWED")
}
Task {
do {
_ = try await self.auth.startPasskeySignIn()
XCTFail("Expected error from backend but got success")
} catch {
let nsError = error as NSError
XCTAssertEqual(nsError.code, AuthErrorCode.operationNotAllowed.rawValue)
expectation.fulfill()
}
}
waitForExpectations(timeout: 5)
}
}
#endif
75 changes: 75 additions & 0 deletions FirebaseAuth/Tests/Unit/StartPasskeySignInRequestTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// 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)

@testable import FirebaseAuth
import FirebaseCore
import Foundation
import XCTest

@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
final class StartPasskeySignInRequestTests: XCTestCase {
private var config: AuthRequestConfiguration!

override func setUp() {
super.setUp()
config = AuthRequestConfiguration(
apiKey: "FAKE_API_KEY",
appID: "FAKE_APP_ID"
)
}

override func tearDown() {
config = nil
super.tearDown()
}

func testInit_SetsEndpointAndConfig() {
let request = StartPasskeySignInRequest(requestConfiguration: config)
XCTAssertEqual(request.endpoint, "accounts/passkeySignIn:start")
XCTAssertTrue(request.useIdentityPlatform)
XCTAssertEqual(request.requestConfiguration().apiKey, "FAKE_API_KEY")
XCTAssertEqual(request.requestConfiguration().appID, "FAKE_APP_ID")
}

func testUnencodedHTTPRequestBody_WithTenantId() {
// setting up fake auth to set tenantId
let options = FirebaseOptions(googleAppID: "0:0000000000000:ios:0000000000000000",
gcmSenderID: "00000000000000000-00000000000-000000000")
options.apiKey = AuthTests.kFakeAPIKey
options.projectID = "myProjectID"
let name = "test-AuthTests\(AuthTests.testNum)"
AuthTests.testNum = AuthTests.testNum + 1
let fakeAuth = Auth(app: FirebaseApp(instanceWithName: name, options: options))
fakeAuth.tenantID = "TEST_TENANT"
let configWithTenant = AuthRequestConfiguration(
apiKey: "FAKE_API_KEY",
appID: "FAKE_APP_ID",
auth: fakeAuth
)
_ = AuthRequestConfiguration(apiKey: "apiKey", appID: "appId")
let request = StartPasskeySignInRequest(
requestConfiguration: configWithTenant
)
let body = request.unencodedHTTPRequestBody
XCTAssertEqual(body!["tenantId"], "TEST_TENANT")
}

func testUnencodedHTTPRequestBody_WithoutTenantId() {
let request = StartPasskeySignInRequest(requestConfiguration: config)
XCTAssertNil(request.unencodedHTTPRequestBody)
}
}

#endif
75 changes: 75 additions & 0 deletions FirebaseAuth/Tests/Unit/StartPasskeySignInResponseTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// 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)

@testable import FirebaseAuth
import XCTest

@available(iOS 15.0, macOS 12.0, tvOS 16.0, *)
final class StartPasskeySignInResponseTests: XCTestCase {
private func makeValidDictionary() -> [String: AnyHashable] {
return [
"credentialRequestOptions": [
"rpId": "FAKE_RPID",
"challenge": "FAKE_CHALLENGE",
] as [String: AnyHashable],
]
}

func testInitWithValidDictionary() throws {
let dict = makeValidDictionary()
let response = try StartPasskeySignInResponse(dictionary: dict)
XCTAssertEqual(response.rpID, "FAKE_RPID")
XCTAssertEqual(response.challenge, "FAKE_CHALLENGE")
}

/// Helper function to remove nested field from dictionary
private func removeField(_ dict: inout [String: AnyHashable], keyPath: [String]) {
guard let first = keyPath.first else { return }
if keyPath.count == 1 {
dict.removeValue(forKey: first)
} else if var inDict = dict[first] as? [String: AnyHashable] {
removeField(&inDict, keyPath: Array(keyPath.dropFirst()))
dict[first] = inDict
}
}

func testInitWithInvalidDictionary() throws {
struct TestCase {
let name: String
let removeFieldPath: [String]
}
let cases: [TestCase] = [
.init(name: "Missing credential options", removeFieldPath: ["credentialRequestOptions"]),
.init(name: "Missing rpId", removeFieldPath: ["credentialRequestOptions", "rpId"]),
.init(
name: "Missing challenge",
removeFieldPath: ["credentialRequestOptions", "challenge"]
),
]
for testCase in cases {
var dict = makeValidDictionary()
removeField(&dict, keyPath: testCase.removeFieldPath)
XCTAssertThrowsError(try StartPasskeySignInResponse(dictionary: dict),
testCase.name) { error in
let nsError = error as NSError
XCTAssertEqual(nsError.domain, AuthErrorDomain)
XCTAssertEqual(nsError.code, AuthErrorCode.internalError.rawValue)
}
}
}
}

#endif
Loading