vector-im/element-x-ios/issues/31 - Implement simple SaS sesson verification

* vector-im/element-x-ios/issues/31 - Session verification unit and UI tests
* Fix ImageAnonymizer tests when running on Apple Silicon
* Rename SessionVerification to SessionVerificationScreen
This commit is contained in:
Stefan Ceriu
2022-07-01 13:56:52 +03:00
committed by GitHub
parent 266ca656fc
commit a6f9d1ba89
30 changed files with 1604 additions and 98 deletions
@@ -0,0 +1,67 @@
//
// Copyright 2021 New Vector Ltd
//
// 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.
//
import SwiftUI
struct SessionVerificationCoordinatorParameters {
let sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol
}
final class SessionVerificationCoordinator: Coordinator, Presentable {
// MARK: - Properties
// MARK: Private
private let parameters: SessionVerificationCoordinatorParameters
private let sessionVerificationHostingController: UIViewController
private var sessionVerificationViewModel: SessionVerificationViewModelProtocol
// MARK: Public
// Must be used only internally
var childCoordinators: [Coordinator] = []
var callback: (() -> Void)?
// MARK: - Setup
init(parameters: SessionVerificationCoordinatorParameters) {
self.parameters = parameters
let viewModel = SessionVerificationViewModel(sessionVerificationControllerProxy: parameters.sessionVerificationControllerProxy)
let view = SessionVerificationScreen(context: viewModel.context)
sessionVerificationViewModel = viewModel
sessionVerificationHostingController = UIHostingController(rootView: view)
}
// MARK: - Public
func start() {
MXLog.debug("[SessionVerificationCoordinator] did start.")
sessionVerificationViewModel.callback = { [weak self] action in
guard let self = self else { return }
switch action {
case .finished:
self.callback?()
}
}
}
func toPresentable() -> UIViewController {
sessionVerificationHostingController
}
}
@@ -0,0 +1,46 @@
//
// Copyright 2021 New Vector Ltd
//
// 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.
//
import Foundation
// MARK: View model
enum SessionVerificationViewModelAction {
case finished
}
// MARK: View
struct SessionVerificationViewState: BindableState {
var verificationState: SessionVerificationStateMachine.State = .initial
var shouldDisableDismissButton: Bool {
verificationState != .verified
}
var shouldDisableCancelButton: Bool {
verificationState == .verified
}
}
enum SessionVerificationViewAction {
case start
case restart
case accept
case decline
case dismiss
case cancel
}
@@ -0,0 +1,135 @@
//
// SessionVerificationStateMachine.swift
// ElementX
//
// Created by Stefan Ceriu on 15/06/2022.
// Copyright © 2022 Element. All rights reserved.
//
import Foundation
import SwiftState
class SessionVerificationStateMachine {
/// States the SessionVerificationViewModel can find itself in
enum State: StateType {
/// The initial state, before verification started
case initial
/// Waiting for verification acceptance
case requestingVerification
/// Verification accepted and emojis received
case showingChallenge(emojis: [SessionVerificationEmoji])
/// Emojis match locally
case acceptingChallenge(emojis: [SessionVerificationEmoji])
/// Emojis do not match locally
case decliningChallenge(emojis: [SessionVerificationEmoji])
/// Verification successful
case verified
/// User requested verification cancellation
case cancelling
/// The verification has been cancelled, remotely or locally
case cancelled
}
/// Events that can be triggered on the SessionVerification state machine
enum Event: EventType {
/// Request verification
case requestVerification
/// Has received emojis
case didReceiveChallenge(emojis: [SessionVerificationEmoji])
/// Emojis match
case acceptChallenge
/// Emojis do not match
case declineChallenge
/// Remote accepted challenge
case didAcceptChallenge
/// Request cancellation
case cancel
/// Verification cancelled
case didCancel
/// Request failed
case didFail
/// Restart the verification flow
case restart
}
private let stateMachine: StateMachine<State, Event>
var state: State {
stateMachine.state
}
// swiftlint:disable cyclomatic_complexity
init() {
stateMachine = StateMachine(state: .initial) { machine in
machine.addRoutes(event: .requestVerification, transitions: [ .initial => .requestingVerification ])
machine.addRoutes(event: .didFail, transitions: [ .requestingVerification => .initial ])
machine.addRoutes(event: .cancel, transitions: [ .requestingVerification => .cancelling ])
machine.addRoutes(event: .didCancel, transitions: [ .requestingVerification => .cancelled ])
// Cancellation request from the other party should either take us from `.cancelling`
// to `.cancelled` or keep us in `.cancelled` if already there. There is more `.didCancel`
// handling in `addRouteMapping` for states containing associated values
machine.addRoutes(event: .didCancel, transitions: [ .cancelling => .cancelled ])
machine.addRoutes(event: .didCancel, transitions: [ .cancelled => .cancelled ])
machine.addRoutes(event: .didFail, transitions: [ .cancelled => .cancelled ])
machine.addRoutes(event: .restart, transitions: [ .cancelled => .initial ])
// Transitions with associated values need to be handled through `addRouteMapping`
machine.addRouteMapping { event, fromState, _ in
switch (event, fromState) {
case (.didReceiveChallenge(let emojis), .requestingVerification):
return .showingChallenge(emojis: emojis)
case (.acceptChallenge, .showingChallenge(let emojis)):
return .acceptingChallenge(emojis: emojis)
case (.didFail, .acceptingChallenge(let emojis)):
return .showingChallenge(emojis: emojis)
case (.didAcceptChallenge, .acceptingChallenge):
return .verified
case (.declineChallenge, .showingChallenge(let emojis)):
return .decliningChallenge(emojis: emojis)
case (.didFail, .decliningChallenge(let emojis)):
return .showingChallenge(emojis: emojis)
case (.cancel, .showingChallenge):
return .cancelling
case (.cancel, .acceptingChallenge):
return .cancelling
case (.cancel, .decliningChallenge):
return .cancelling
case (.didCancel, .showingChallenge):
return .cancelled
case (.didCancel, .acceptingChallenge):
return .cancelled
case (.didCancel, .decliningChallenge):
return .cancelled
default:
return nil
}
}
}
}
// swiftlint:enable cyclomatic_complexity
/// Attempt to move the state machine to another state through an event
/// It will either invoke the `transitionHandler` or the `errorHandler` depending on its current state
func processEvent(_ event: Event) {
stateMachine.tryEvent(event)
}
/// Registers a callback for processing state machine transitions
func addTransitionHandler(_ handler: @escaping StateMachine<State, Event>.Handler) {
stateMachine.addAnyHandler(.any => .any, handler: handler)
}
/// Registers a callback for processing state machine errors
func addErrorHandler(_ handler: @escaping StateMachine<State, Event>.Handler) {
stateMachine.addErrorHandler(handler: handler)
}
}
@@ -0,0 +1,164 @@
//
// Copyright 2021 New Vector Ltd
//
// 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.
//
import SwiftUI
typealias SessionVerificationViewModelType = StateStoreViewModel<SessionVerificationViewState, SessionVerificationViewAction>
class SessionVerificationViewModel: SessionVerificationViewModelType, SessionVerificationViewModelProtocol {
// MARK: - Properties
// MARK: Private
private let sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol
private var stateMachine: SessionVerificationStateMachine
// MARK: Public
var callback: ((SessionVerificationViewModelAction) -> Void)?
// MARK: - Setup
init(sessionVerificationControllerProxy: SessionVerificationControllerProxyProtocol,
initialState: SessionVerificationViewState = SessionVerificationViewState()) {
self.sessionVerificationControllerProxy = sessionVerificationControllerProxy
stateMachine = SessionVerificationStateMachine()
super.init(initialViewState: initialState)
setupStateMachine()
sessionVerificationControllerProxy.callbacks
.receive(on: DispatchQueue.main)
.sink { [weak self] callback in
guard let self = self else { return }
switch callback {
case .receivedVerificationData(let emojis):
self.stateMachine.processEvent(.didReceiveChallenge(emojis: emojis))
case .finished:
self.stateMachine.processEvent(.didAcceptChallenge)
case .cancelled:
self.stateMachine.processEvent(.didCancel)
case .failed:
self.stateMachine.processEvent(.didFail)
}
}.store(in: &cancellables)
}
// MARK: - Public
override func process(viewAction: SessionVerificationViewAction) async {
switch viewAction {
case .start:
stateMachine.processEvent(.requestVerification)
case .restart:
stateMachine.processEvent(.restart)
case .dismiss:
callback?(.finished)
case .cancel:
guard stateMachine.state == .initial ||
stateMachine.state == .verified ||
stateMachine.state == .cancelled else {
stateMachine.processEvent(.cancel)
return
}
callback?(.finished)
case .accept:
stateMachine.processEvent(.acceptChallenge)
case .decline:
stateMachine.processEvent(.declineChallenge)
}
}
// MARK: - Private
private func setupStateMachine() {
stateMachine.addTransitionHandler { [weak self] context in
guard let self = self else { return }
self.state.verificationState = context.toState
switch (context.fromState, context.event, context.toState) {
case (.initial, .requestVerification, .requestingVerification):
self.requestVerification()
case (.showingChallenge, .acceptChallenge, .acceptingChallenge):
self.acceptChallenge()
case (.showingChallenge, .declineChallenge, .decliningChallenge):
self.declineChallenge()
case (_, .cancel, .cancelling):
self.cancelVerification()
default:
break
}
}
stateMachine.addErrorHandler { context in
fatalError("Failed transition with context: \(context)")
}
}
private func requestVerification() {
Task {
switch await sessionVerificationControllerProxy.requestVerification() {
case.success:
// Need to wait for the callback from the remote
break
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
private func cancelVerification() {
Task {
switch await sessionVerificationControllerProxy.cancelVerification() {
case.success:
stateMachine.processEvent(.didCancel)
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
private func acceptChallenge() {
Task {
switch await sessionVerificationControllerProxy.approveVerification() {
case.success:
// Need to wait for the callback from the remote
break
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
private func declineChallenge() {
Task {
switch await sessionVerificationControllerProxy.declineVerification() {
case.success:
stateMachine.processEvent(.didCancel)
case .failure:
stateMachine.processEvent(.didFail)
}
}
}
}
@@ -0,0 +1,23 @@
//
// Copyright 2021 New Vector Ltd
//
// 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.
//
import Foundation
@MainActor
protocol SessionVerificationViewModelProtocol {
var callback: ((SessionVerificationViewModelAction) -> Void)? { get set }
var context: SessionVerificationViewModelType.Context { get }
}
@@ -0,0 +1,204 @@
//
// Copyright 2021 New Vector Ltd
//
// 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.
//
import SwiftUI
import MatrixRustSDK
struct SessionVerificationScreen: View {
@ObservedObject var context: SessionVerificationViewModel.Context
// MARK: Views
var body: some View {
NavigationView {
VStack(spacing: 32.0) {
Text(heading)
.font(.body)
.multilineTextAlignment(.center)
.foregroundColor(.element.primaryContent)
.accessibilityIdentifier("titleLabel")
switch context.viewState.verificationState {
case .initial:
StateIcon(systemName: "lock.shield")
Button(ElementL10n.startVerification) {
context.send(viewAction: .start)
}
.buttonStyle(.elementAction(.regular))
.accessibilityIdentifier("startButton")
case .cancelled:
StateIcon(systemName: "xmark.shield")
.accessibilityIdentifier("sessionVerificationFailedIcon")
Button(ElementL10n.globalRetry) {
context.send(viewAction: .restart)
}
.buttonStyle(.elementAction(.regular))
.accessibilityIdentifier("restartButton")
case .requestingVerification:
ProgressView()
.accessibilityIdentifier("requestingVerificationProgressView")
case .cancelling:
ProgressView()
.accessibilityIdentifier("cancellingVerificationProgressView")
case .acceptingChallenge:
ProgressView()
.accessibilityIdentifier("acceptingChallengeProgressView")
case .decliningChallenge:
ProgressView()
.accessibilityIdentifier("decliningChallengeProgressView")
case .showingChallenge(let emojis):
HStack(spacing: 8.0) {
ForEach(emojis.prefix(4), id: \.self) { emoji in
EmojiView(emoji: emoji)
}
}
HStack(spacing: 8.0) {
ForEach(emojis.suffix(from: 4), id: \.self) { emoji in
EmojiView(emoji: emoji)
}
}
actionButtons
case .verified:
StateIcon(systemName: "checkmark.shield")
.accessibilityIdentifier("sessionVerificationSucceededIcon")
}
Spacer()
}
.padding()
.padding(.top, 64)
.navigationBarTitleDisplayMode(.inline)
.navigationTitle(ElementL10n.verificationVerifyDevice)
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button(ElementL10n.done) {
context.send(viewAction: .dismiss)
}
.disabled(context.viewState.shouldDisableDismissButton)
.accessibilityIdentifier("dismissButton")
}
ToolbarItem(placement: .cancellationAction) {
Button(ElementL10n.actionCancel) {
context.send(viewAction: .cancel)
}
.disabled(context.viewState.shouldDisableCancelButton)
.accessibilityIdentifier("cancelButton")
}
}
}
.navigationViewStyle(StackNavigationViewStyle())
}
// MARK: - Private
private var heading: String {
switch context.viewState.verificationState {
case .initial:
return ElementL10n.verificationOpenOtherToVerify
case .requestingVerification:
return ElementL10n.verificationRequestWaiting
case .acceptingChallenge:
return ElementL10n.verificationRequestWaiting
case .decliningChallenge:
return ElementL10n.verificationRequestWaiting
case .cancelling:
return ElementL10n.verificationRequestWaiting
case .showingChallenge:
return ElementL10n.verificationEmojiNotice
case .verified:
return ElementL10n.verificationConclusionOkSelfNotice
case .cancelled:
return ElementL10n.verificationCancelled
}
}
private var actionButtons: some View {
HStack(spacing: 16.0) {
Button(ElementL10n.verificationSasDoNotMatch) {
context.send(viewAction: .decline)
}
.buttonStyle(.elementAction(.regular, color: .red))
.accessibilityLabel("challengeDeclineButton")
Button(ElementL10n.verificationSasMatch) {
context.send(viewAction: .accept)
}
.buttonStyle(.elementAction(.regular))
.accessibilityLabel("challengeAcceptButton")
}
.padding(32.0)
}
struct EmojiView: View {
let emoji: SessionVerificationEmoji
var body: some View {
VStack(spacing: 16.0) {
Text(emoji.symbol)
.font(.largeTitle)
Text(emoji.description)
.font(.body)
}
.padding(8.0)
}
}
struct StateIcon: View {
let systemName: String
var body: some View {
Image(systemName: systemName)
.resizable()
.scaledToFit()
.foregroundColor(.element.accent)
.frame(width: 100, height: 100)
}
}
}
// MARK: - Previews
struct SessionVerification_Previews: PreviewProvider {
static var previews: some View {
body.preferredColorScheme(.light)
body.preferredColorScheme(.dark)
}
@ViewBuilder
static var body: some View {
Group {
sessionVerificationScreen(state: .initial)
sessionVerificationScreen(state: .requestingVerification)
sessionVerificationScreen(state: .cancelled)
sessionVerificationScreen(state: .showingChallenge(emojis: MockSessionVerificationControllerProxy.emojis))
sessionVerificationScreen(state: .verified)
}
}
static func sessionVerificationScreen(state: SessionVerificationStateMachine.State) -> some View {
let viewModel = SessionVerificationViewModel(sessionVerificationControllerProxy: MockSessionVerificationControllerProxy(),
initialState: SessionVerificationViewState(verificationState: state))
return SessionVerificationScreen(context: viewModel.context)
}
}