Files
element-x-ios/UnitTests/Sources/AuthenticationServiceTests.swift
Mauro Romito 5792a8ba5c Create sessions through the user session manager
Sign-in now creates and stores its session through the
UserSessionManagerProtocol rather than the UserSessionStore, so the
AppCoordinator no longer holds the store.

- The manager forwards clientSessionDelegate and
  userSession(for:sessionDirectories:passphrase:) to its store. As with
  restoring, the new session isn't registered until the AppCoordinator
  adds it.
- AuthenticationService takes the manager, for both sign-in and soft
  logout.
- The store mock's configuration moves to the manager mock.
2026-10-09 15:21:27 +02:00

170 lines
7.4 KiB
Swift

//
// Copyright 2025 Element Creations Ltd.
// Copyright 2024-2025 New Vector Ltd.
//
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial.
// Please see LICENSE files in the repository root for full details.
//
@testable import ElementX
import Foundation
import MatrixRustSDKMocks
import Testing
@MainActor
struct AuthenticationServiceTests {
var client: ClientSDKMock!
var encryption: EncryptionSDKMock!
var userSessionManager: UserSessionManagerMock!
var encryptionKeyProvider: MockEncryptionKeyProvider!
var service: AuthenticationService!
@Test
mutating func passwordLogin() async throws {
try await setup(serverNameOrBaseURL: "example.com")
switch await service.configure(for: "example.com", flow: .login) {
case .success:
break
case .failure(let error):
Issue.record("Unexpected failure: \(error)")
}
#expect(service.flow == .login)
#expect(service.homeserver.value == .mockBasicServer)
switch await service.login(username: "alice", password: "12345678", initialDeviceName: nil, deviceID: nil) {
case .success:
#expect(client.loginUsernamePasswordInitialDeviceNameDeviceIdCallsCount == 1)
#expect(userSessionManager.userSessionForSessionDirectoriesPassphraseCallsCount == 1)
#expect(userSessionManager.userSessionForSessionDirectoriesPassphraseReceivedArguments?.passphrase == encryptionKeyProvider.generateKey())
case .failure(let error):
Issue.record("Unexpected failure: \(error)")
}
}
@Test
mutating func configureLoginWithOAuth() async throws {
try await setup()
try await service.configure(for: "matrix.org", flow: .login).get()
#expect(service.flow == .login)
#expect(service.homeserver.value == .mockMatrixDotOrg)
}
@Test
mutating func configureRegisterWithOAuth() async throws {
try await setup()
try await service.configure(for: "matrix.org", flow: .register).get()
#expect(service.flow == .register)
#expect(service.homeserver.value == .mockMatrixDotOrg)
}
@Test
mutating func configureRegisterNoSupport() async throws {
let serverNameOrBaseURL = "example.com"
try await setup(serverNameOrBaseURL: serverNameOrBaseURL)
try await #require(throws: AuthenticationServiceError.registrationNotSupported) {
try await service.configure(for: serverNameOrBaseURL, flow: .register).get()
}
#expect(service.flow == .login)
#expect(service.homeserver.value == .init(accountProvider: .managed(serverName: "matrix.org", baseURL: "https://matrix-client.matrix.org"),
loginMode: .unknown))
}
@Test
mutating func classicAppAccountSecretsBundleIsUsed() async throws {
// Given an authentication service with an Element Classic account for Alice.
try await setup(classicAppAccounts: [.mockAlice])
try await service.configure(for: "matrix.org", flow: .login).get()
#expect(service.flow == .login)
#expect(service.classicAppAccount?.state.availableSecrets == .complete)
// When logging in as Alice.
_ = try await service.login(username: "alice", password: "12345678", initialDeviceName: nil, deviceID: nil).get()
#expect(client.loginUsernamePasswordInitialDeviceNameDeviceIdCallsCount == 1)
// Then Alice's secrets from Element Classic should be imported.
#expect(encryption.importSecretsBundleSecretsBundleCalled)
}
@Test
mutating func classicAppAccountSecretsBundleIsIgnoredWhenUnavailable() async throws {
// Given an authentication service with an Element Classic account for Alice
// which isn't configured with any available secrets.
try await setup(classicAppAccounts: [.mockAlice], availableSecrets: .unavailable)
try await service.configure(for: "matrix.org", flow: .login).get()
#expect(service.flow == .login)
#expect(service.classicAppAccount?.state.availableSecrets == .unavailable)
// When logging in as Alice.
_ = try await service.login(username: "alice", password: "12345678", initialDeviceName: nil, deviceID: nil).get()
#expect(client.loginUsernamePasswordInitialDeviceNameDeviceIdCallsCount == 1)
// Then an attempt to import Alice's secrets from Element Classic must not be made.
#expect(!encryption.importSecretsBundleSecretsBundleCalled)
}
@Test
mutating func classicAppAccountSecretsBundleIsIgnoredForDifferentUser() async throws {
// Given an authentication service with an Element Classic account for Dan.
try await setup(classicAppAccounts: [.mockDan])
try await service.configure(for: "matrix.org", flow: .login).get()
#expect(service.flow == .login)
#expect(service.classicAppAccount?.state.availableSecrets == .complete)
// When logging in as Alice
_ = try await service.login(username: "alice", password: "12345678", initialDeviceName: nil, deviceID: nil).get()
#expect(client.loginUsernamePasswordInitialDeviceNameDeviceIdCallsCount == 1)
// Then Dan's secrets from Element Calssic should not be imported into Alice's client.
#expect(!encryption.importSecretsBundleSecretsBundleCalled)
}
// MARK: - Helpers
private mutating func setup(serverNameOrBaseURL: String = "matrix.org",
classicAppAccounts: [ClassicAppAccount] = [],
availableSecrets: ClassicAppAccount.AvailableSecrets = .complete) async throws {
let configuration: ClientFactoryMock.Configuration = .init()
let clientFactory = ClientFactoryMock(configuration)
client = configuration.homeserverClients[serverNameOrBaseURL]
encryption = EncryptionSDKMock()
client.encryptionReturnValue = encryption
userSessionManager = UserSessionManagerMock(.init())
encryptionKeyProvider = MockEncryptionKeyProvider()
let classicAppManager = ClassicAppManagerMock(.init(accounts: classicAppAccounts,
availableSecrets: availableSecrets,
secretsBundle: SecretsBundleWithUserIdSDKMock()))
service = AuthenticationService(userSessionManager: userSessionManager,
encryptionKeyProvider: encryptionKeyProvider,
classicAppManager: classicAppManager,
clientFactory: clientFactory,
appSettings: .volatile(),
appHooks: AppHooks())
if let classicAppAccount = service.classicAppAccount {
await service.setupClassicAppAccountState()
try #require(classicAppAccount.state.isServerSupported == true)
try #require(classicAppAccount.state.availableSecrets == availableSecrets)
}
}
}
struct MockEncryptionKeyProvider: EncryptionKeyProviderProtocol {
private let key = "12345678"
func generateKey() -> Data {
Data(key.utf8)
}
}