Skip to content
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

feat(auth): Keychain Sharing (No App Reload Required) #3811

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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 Amplify/Categories/Auth/Models/AccessGroup.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//

import Foundation

public struct AccessGroup {
public let name: String?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we add doc comments explaining what is the intent of the variable, this comment applies to anything that is being made public here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Example:
(Its just an example, please make modifications as you feel are correct)

/// A structure representing an access group for managing keychain items.
public struct AccessGroup {
    /// The name of the access group.
    public let name: String?
    
    /// A flag indicating whether to migrate keychain items.
    public let migrateKeychainItems: Bool

    /**
     Initializes an `AccessGroup` with the specified name and migration option.
     
     - Parameter name: The name of the access group.
     - Parameter migrateKeychainItemsOfUserSession: A flag indicating whether to migrate keychain items. Defaults to `false`.
     */
    public init(name: String, migrateKeychainItemsOfUserSession: Bool = false) {
        self.init(name: name, migrateKeychainItems: migrateKeychainItemsOfUserSession)
    }

    /**
     Creates an `AccessGroup` instance with no specified name.
     
     - Parameter migrateKeychainItemsOfUserSession: A flag indicating whether to migrate keychain items.
     - Returns: An `AccessGroup` instance with the migration option set.
     */
    public static func none(migrateKeychainItemsOfUserSession: Bool) -> AccessGroup {
        return .init(migrateKeychainItems: migrateKeychainItemsOfUserSession)
    }

    /**
     A static property representing an `AccessGroup` with no name and no migration.
     
     - Returns: An `AccessGroup` instance with no name and the migration option set to `false`.
     */
    public static var none: AccessGroup {
        return .none(migrateKeychainItemsOfUserSession: false)
    }
}

public let migrateKeychainItems: Bool

public init(name: String, migrateKeychainItemsOfUserSession: Bool = false) {
self.init(name: name, migrateKeychainItems: migrateKeychainItemsOfUserSession)
thisisabhash marked this conversation as resolved.
Show resolved Hide resolved
}

public static func none(migrateKeychainItemsOfUserSession: Bool) -> AccessGroup {
return .init(migrateKeychainItems: migrateKeychainItemsOfUserSession)
}

public static var none: AccessGroup {
return .none(migrateKeychainItemsOfUserSession: false)
}

private init(name: String? = nil, migrateKeychainItems: Bool) {
self.name = name
self.migrateKeychainItems = migrateKeychainItems
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,11 @@ extension AWSCognitoAuthPlugin {
}

private func makeCredentialStore() -> AmplifyAuthCredentialStoreBehavior {
AWSCognitoAuthCredentialStore(authConfiguration: authConfiguration)
return AWSCognitoAuthCredentialStore(
authConfiguration: authConfiguration,
accessGroup: secureStoragePreferences?.accessGroup?.name,
migrateKeychainItemsOfUserSession: secureStoragePreferences?.accessGroup?.migrateKeychainItems ?? false
)
}

private func makeLegacyKeychainStore(service: String) -> KeychainStoreBehavior {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public final class AWSCognitoAuthPlugin: AWSCognitoAuthPluginBehavior {
/// The user network preferences for timeout and retry
let networkPreferences: AWSCognitoNetworkPreferences?

/// The user secure storage preferences for access group
let secureStoragePreferences: AWSCognitoSecureStoragePreferences?

@_spi(InternalAmplifyConfiguration)
internal(set) public var jsonConfiguration: JSONValue?

Expand All @@ -43,15 +46,14 @@ public final class AWSCognitoAuthPlugin: AWSCognitoAuthPluginBehavior {
return "awsCognitoAuthPlugin"
}

/// Instantiates an instance of the AWSCognitoAuthPlugin.
public init() {
self.networkPreferences = nil
}

/// Instantiates an instance of the AWSCognitoAuthPlugin with custom network preferences
/// Instantiates an instance of the AWSCognitoAuthPlugin with optional custom network
/// preferences and optional custom secure storage preferences
/// - Parameters:
/// - networkPreferences: network preferences
public init(networkPreferences: AWSCognitoNetworkPreferences) {
/// - secureStoragePreferences: secure storage preferences
public init(networkPreferences: AWSCognitoNetworkPreferences? = nil,
secureStoragePreferences: AWSCognitoSecureStoragePreferences = AWSCognitoSecureStoragePreferences()) {
self.networkPreferences = networkPreferences
self.secureStoragePreferences = secureStoragePreferences
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,11 @@ extension AWSCognitoAuthPlugin: AuthCategoryBehavior {
public func fetchAuthSession(options: AuthFetchSessionRequest.Options?) async throws -> AuthSession {
let options = options ?? AuthFetchSessionRequest.Options()
let request = AuthFetchSessionRequest(options: options)
let task = AWSAuthFetchSessionTask(request, authStateMachine: authStateMachine)
let forceReconfigure = secureStoragePreferences?.accessGroup?.name != nil
let task = AWSAuthFetchSessionTask(request,
authStateMachine: authStateMachine,
configuration: authConfiguration,
forceReconfigure: forceReconfigure)
return try await taskQueue.sync {
return try await task.value
} as! AuthSession
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ struct AWSCognitoAuthCredentialStore {

// Credential store constants
private let service = "com.amplify.awsCognitoAuthPlugin"
private let sharedService = "com.amplify.awsCognitoAuthPluginShared"
private let sessionKey = "session"
private let deviceMetadataKey = "deviceMetadata"
private let deviceASFKey = "deviceASF"
Expand All @@ -25,14 +26,33 @@ struct AWSCognitoAuthCredentialStore {
private var isKeychainConfiguredKey: String {
"\(userDefaultsNameSpace).isKeychainConfigured"
}
private var accessGroupKey: String {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a small comment explaining the usage of the accessGroupKey like for isKeychainConfiguredKey?

"\(userDefaultsNameSpace).accessGroup"
}

private let authConfiguration: AuthConfiguration
private let keychain: KeychainStoreBehavior
private let userDefaults = UserDefaults.standard
private let accessGroup: String?

init(authConfiguration: AuthConfiguration, accessGroup: String? = nil) {
init(
authConfiguration: AuthConfiguration,
accessGroup: String? = nil,
migrateKeychainItemsOfUserSession: Bool = false
) {
self.authConfiguration = authConfiguration
self.keychain = KeychainStore(service: service, accessGroup: accessGroup)
self.accessGroup = accessGroup
if let accessGroup {
self.keychain = KeychainStore(service: sharedService, accessGroup: accessGroup)
} else {
self.keychain = KeychainStore(service: service)
}

if migrateKeychainItemsOfUserSession {
try? migrateKeychainItemsToAccessGroup()
}

try? saveStoredAccessGroup()

if !userDefaults.bool(forKey: isKeychainConfiguredKey) {
try? clearAllCredentials()
Expand Down Expand Up @@ -182,6 +202,62 @@ extension AWSCognitoAuthCredentialStore: AmplifyAuthCredentialStoreBehavior {
private func clearAllCredentials() throws {
try keychain._removeAll()
}

private func retrieveStoredAccessGroup() throws -> String? {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method is not throwing, so can be renamed without throws.

Suggested change
private func retrieveStoredAccessGroup() throws -> String? {
private func retrieveStoredAccessGroup() -> String? {

return userDefaults.string(forKey: accessGroupKey)
}

private func saveStoredAccessGroup() throws {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method is not throwing, so can be renamed without throws.

Suggested change
private func saveStoredAccessGroup() throws {
private func saveStoredAccessGroup() {

if let accessGroup {
userDefaults.set(accessGroup, forKey: accessGroupKey)
} else {
userDefaults.removeObject(forKey: accessGroupKey)
}
}

private func migrateKeychainItemsToAccessGroup() throws {
let oldAccessGroup = try? retrieveStoredAccessGroup()
let oldKeychain: KeychainStoreBehavior

if oldAccessGroup == accessGroup {
log.verbose("[AWSCognitoAuthCredentialStore] Stored access group is the same as current access group, aborting migration")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than verbose, I think this log statement should be of type info.

return
}

if let oldAccessGroup {
oldKeychain = KeychainStore(service: sharedService, accessGroup: oldAccessGroup)
} else {
oldKeychain = KeychainStore(service: service)
}

let authCredentialStoreKey = generateSessionKey(for: authConfiguration)
let authCredentialData: Data
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the data need to be declared outside the try?

let awsCredential: AmplifyCredentials
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

awsCredential variable name can be mistakenly interpreted as AWS Temporary Credentials.

Suggested change
let awsCredential: AmplifyCredentials
let amplifyCredential: AmplifyCredentials

do {
authCredentialData = try oldKeychain._getData(authCredentialStoreKey)
awsCredential = try decode(data: authCredentialData)
} catch {
log.verbose("[AWSCognitoAuthCredentialStore] Could not retrieve previous credentials in keychain under old access group, nothing to migrate")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This log should be of type error or at the least warn.

return
}

guard awsCredential.areValid() else {
log.verbose("[AWSCognitoAuthCredentialStore] Credentials found are not valid (expired) in old access group keychain, aborting migration")
return
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this check might no be accurate, as the areValid method doesn't validate the refresh token.. The refresh token might still be valid.. So I think we should skip this check, and if its not valid, the fetchAuthSession will fail, which is acceptable I think.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense. I'm okay with removing this part.


let oldService = oldAccessGroup != nil ? sharedService : service
let newService = accessGroup != nil ? sharedService : service

do {
thisisabhash marked this conversation as resolved.
Show resolved Hide resolved
try KeychainStoreMigrator(oldService: oldService, newService: newService, oldAccessGroup: oldAccessGroup, newAccessGroup: accessGroup).migrate()
} catch {
log.error("[AWSCognitoAuthCredentialStore] Migration has failed")
return
}

log.verbose("[AWSCognitoAuthCredentialStore] Migration of keychain items from old access group to new access group successful")
}

}

Expand All @@ -205,3 +281,11 @@ private extension AWSCognitoAuthCredentialStore {
}

}

extension AWSCognitoAuthCredentialStore: DefaultLogger {
public static var log: Logger {
Amplify.Logging.logger(forNamespace: String(describing: self))
}

public nonisolated var log: Logger { Self.log }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//
// Copyright Amazon.com Inc. or its affiliates.
// All Rights Reserved.
//
// SPDX-License-Identifier: Apache-2.0
//

import Foundation
import Amplify

public struct AWSCognitoSecureStoragePreferences {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: doc comments.


/// The access group that the keychain will use for auth items
public let accessGroup: AccessGroup?

public init(accessGroup: AccessGroup? = nil) {
self.accessGroup = accessGroup
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,34 @@ class AWSAuthFetchSessionTask: AuthFetchSessionTask, DefaultLogger {
private let authStateMachine: AuthStateMachine
private let fetchAuthSessionHelper: FetchAuthSessionOperationHelper
private let taskHelper: AWSAuthTaskHelper
private let configuration: AuthConfiguration
private let forceReconfigure: Bool

var eventName: HubPayloadEventName {
HubPayload.EventName.Auth.fetchSessionAPI
}

init(_ request: AuthFetchSessionRequest, authStateMachine: AuthStateMachine) {
init(
_ request: AuthFetchSessionRequest,
authStateMachine: AuthStateMachine,
configuration: AuthConfiguration,
forceReconfigure: Bool = false
) {
self.request = request
self.authStateMachine = authStateMachine
self.fetchAuthSessionHelper = FetchAuthSessionOperationHelper()
self.taskHelper = AWSAuthTaskHelper(authStateMachine: authStateMachine)
self.configuration = configuration
self.forceReconfigure = forceReconfigure
}

func execute() async throws -> AuthSession {
log.verbose("Starting execution")
if forceReconfigure {
log.verbose("Reconfiguring auth state machine for keychain sharing")
let event = AuthEvent(eventType: .reconfigure(configuration))
await authStateMachine.send(event)
}
await taskHelper.didStateMachineConfigured()
let doesNeedForceRefresh = request.options.forceRefresh
return try await fetchAuthSessionHelper.fetch(authStateMachine,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@ class MockKeychainStoreBehavior: KeychainStoreBehavior {
typealias VoidHandler = () -> Void

let data: String
let allData: [(key: String, value: Data)]
let removeAllHandler: VoidHandler?
let mockKey: String = "mockKey"

init(data: String,
removeAllHandler: VoidHandler? = nil) {
self.data = data
self.removeAllHandler = removeAllHandler
self.allData = [(key: mockKey, value: Data(data.utf8))]
}

func _getString(_ key: String) throws -> String {
Expand All @@ -41,4 +44,8 @@ class MockKeychainStoreBehavior: KeychainStoreBehavior {
func _removeAll() throws {
removeAllHandler?()
}

func _getAll() throws -> [(key: String, value: Data)] {
return allData
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,84 @@ class AWSCognitoAuthPluginAmplifyOutputsConfigTests: XCTestCase {
XCTFail("Should not throw error. \(error)")
}
}

/// Test Auth configuration with valid config for user pool and identity pool, with secure storage preferences
///
/// - Given: Given valid config for user pool and identity pool with secure storage preferences
/// - When:
/// - I configure auth with the given configuration and secure storage preferences
/// - Then:
/// - I should not get any error while configuring auth
///
func testConfigWithUserPoolAndIdentityPoolWithSecureStoragePreferences() throws {
let plugin = AWSCognitoAuthPlugin(
secureStoragePreferences: .init(
accessGroup: AccessGroup(name: "xx")
)
)
try Amplify.add(plugin: plugin)

let amplifyConfig = AmplifyOutputsData(auth: .init(
awsRegion: "us-east-1",
userPoolId: "xx",
userPoolClientId: "xx",
identityPoolId: "xx"))

do {
try Amplify.configure(amplifyConfig)

let escapeHatch = plugin.getEscapeHatch()
guard case .userPoolAndIdentityPool(let userPoolClient, let identityPoolClient) = escapeHatch else {
XCTFail("Expected .userPool, got \(escapeHatch)")
return
}
XCTAssertNotNil(userPoolClient)
XCTAssertNotNil(identityPoolClient)

} catch {
XCTFail("Should not throw error. \(error)")
}
}

/// Test Auth configuration with valid config for user pool and identity pool, with network preferences and secure storage preferences
///
/// - Given: Given valid config for user pool and identity pool, network preferences, and secure storage preferences
/// - When:
/// - I configure auth with the given configuration, network preferences, and secure storage preferences
/// - Then:
/// - I should not get any error while configuring auth
///
func testConfigWithUserPoolAndIdentityPoolWithNetworkPreferencesAndSecureStoragePreferences() throws {
let plugin = AWSCognitoAuthPlugin(
networkPreferences: .init(
maxRetryCount: 2,
timeoutIntervalForRequest: 60,
timeoutIntervalForResource: 60),
secureStoragePreferences: .init(
accessGroup: AccessGroup(name: "xx")
)
)
try Amplify.add(plugin: plugin)

let amplifyConfig = AmplifyOutputsData(auth: .init(
awsRegion: "us-east-1",
userPoolId: "xx",
userPoolClientId: "xx",
identityPoolId: "xx"))

do {
try Amplify.configure(amplifyConfig)

let escapeHatch = plugin.getEscapeHatch()
guard case .userPoolAndIdentityPool(let userPoolClient, let identityPoolClient) = escapeHatch else {
XCTFail("Expected .userPool, got \(escapeHatch)")
return
}
XCTAssertNotNil(userPoolClient)
XCTAssertNotNil(identityPoolClient)

} catch {
XCTFail("Should not throw error. \(error)")
}
}
}
Loading
Loading