Skip to content
Merged
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
44 changes: 14 additions & 30 deletions iOS/AskKeyiOSKit/App/AppModel+Approvals.swift
Original file line number Diff line number Diff line change
@@ -1,17 +1,11 @@
import AskKeyDevices
import Foundation

/// A message sealed once and sent until CloudKit saves it.
/// A receipt sealed once and sent until CloudKit saves it.
struct OutgoingMessage: Hashable, Sendable {
enum Purpose: Hashable, Sendable {
/// The receipt for the request with this record name.
case receipt(request: String)
/// An approver confirmation; once saved, the flag for this pairing is set.
case confirmation(mac: DeviceID, pairingID: PairingID)
}

let envelope: DeviceEnvelope
let purpose: Purpose
/// The record name of the request it acknowledges.
let request: String
}

/// The approver's inbox side (ADR 0014 → iPhone app): which verified
Expand All @@ -31,7 +25,8 @@ extension AppModel {

// MARK: Handler

/// Verified kinds 10–14. `AskKeyDevices` checked the envelope, the
/// Verified kinds 10–13 (a retired kind 14 approver confirmation is
/// refused as unexpected). `AskKeyDevices` checked the envelope, the
/// signatures, the payload and the pairing ID; this checks the
/// direction and the approval flag: a Mac sends only requests and
/// closed messages, and only a Mac whose entry carries this iPhone's
Expand Down Expand Up @@ -129,8 +124,7 @@ extension AppModel {
openedContent[recordName] = message
forget(expired)
if let receipt = try? services.sealer.sealApprovalReceipt(answering: message) {
outbox[receipt.envelope.recordName] = OutgoingMessage(envelope: receipt.envelope,
purpose: .receipt(request: recordName))
outbox[receipt.envelope.recordName] = OutgoingMessage(envelope: receipt.envelope, request: recordName)
}
rebuildRequests()
settleRequestNotifications(also: expired)
Expand Down Expand Up @@ -194,39 +188,30 @@ extension AppModel {
/// Runs before any removal of a Mac commits: an unpair notice, a
/// removal here, or pairing again. Its requests are refused from now on.
func macWillBeRemoved(_ entry: PairedDevice) async {
revocationCount += 1
revoke(entry)
}

/// Refuses the pairing's messages from now on and drops the Mac's
/// requests, without suspending. Running it again changes nothing.
func revoke(_ entry: PairedDevice) {
revokedPairings.insert(entry.pairingID)
dropApprovals(forMac: entry.deviceID.text)
}

/// Drops a Mac's requests, stored decisions, markers, unsent receipts
/// and confirmations, and their notifications.
/// and their notifications.
func dropApprovals(forMac mac: String) {
var state = approvals
let dropped = state.requests.filter { $0.macID == mac }.map(\.recordName)
state.requests.removeAll { $0.macID == mac }
state.markers.removeAll { $0.macID == mac }
if state != approvals { commitApprovals(state) }
forget(dropped)
outbox = outbox.filter { _, message in
switch message.purpose {
case .receipt(let request): return !dropped.contains(request)
case .confirmation(let target, _): return target.text != mac
}
}
if approverConfirmation?.macID == mac { stopSendingConfirmation() }
outbox = outbox.filter { _, message in !dropped.contains(message.request) }
rebuildRequests()
settleRequestNotifications(also: dropped)
}

/// A confirmation that will no longer be sent leaves its sheet waiting
/// for the person again.
private func stopSendingConfirmation() {
guard approverConfirmation?.stage == .sending else { return }
approverConfirmation?.stage = .entering
approverConfirmation?.problem = .notSent
}

/// After an account change, a sign-out or an identity reset: every
/// stored request, decision and marker goes.
func dropAllApprovals() {
Expand All @@ -240,7 +225,6 @@ extension AppModel {
// `loadApprovals` drops.
AppLog.failure("Deleting the stored requests", error)
}
stopSendingConfirmation()
approvals = StoredApprovals()
openedContent = [:]
outbox = [:]
Expand Down
30 changes: 9 additions & 21 deletions iOS/AskKeyiOSKit/App/AppModel+Decisions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,8 +135,8 @@ extension AppModel {
/// Sends what is due: stored decisions until CloudKit saves them (every
/// 2 seconds or after CloudKit's retry-after, "recipient unreachable"
/// included) and again every 30 seconds without a closed message while
/// the countdown runs; receipts and approver confirmations until saved
/// or expired. Calls made while sending wait and send once more.
/// the countdown runs; receipts until saved or expired. Calls made while
/// sending wait and send once more.
func sendDueMessages() async {
if let running = sendWork {
sendAgain = true
Expand Down Expand Up @@ -187,24 +187,16 @@ extension AppModel {
let now = environment.clock.now()
guard let message = outbox[name], message.envelope.expiresAt > now,
(nextAttempts[name] ?? .distantPast) <= now else { continue }
if case .receipt(let request) = message.purpose {
// A request already closed needs no receipt; one a tapped
// fetch found waits until a zone poll checked it (#337).
guard let index = approvals.index(of: request), approvals.requests[index].closed == nil else {
outbox[name] = nil
continue
}
if uncheckedRequests.contains(request) { continue }
// A request already closed needs no receipt; one a tapped fetch
// found waits until a zone poll checked it (#337).
guard let index = approvals.index(of: message.request), approvals.requests[index].closed == nil else {
outbox[name] = nil
continue
}
if uncheckedRequests.contains(message.request) { continue }
let saved = await send(message.envelope, retryKey: name, services: services)
guard self.services === services else { return }
if case .confirmation(let mac, _) = message.purpose, !saved, approverConfirmation?.macID == mac.text {
approverConfirmation?.problem = .retrying
}
guard saved, outbox.removeValue(forKey: name) != nil else { continue }
if case .confirmation(let mac, let pairingID) = message.purpose {
await confirmationSaved(mac: mac, pairingID: pairingID, services: services)
}
if saved { outbox[name] = nil }
}
}

Expand Down Expand Up @@ -257,10 +249,6 @@ extension AppModel {
for (name, message) in outbox where message.envelope.expiresAt <= now {
outbox[name] = nil
nextAttempts[name] = nil
if case .confirmation(let mac, _) = message.purpose, approverConfirmation?.macID == mac.text {
approverConfirmation?.stage = .entering
approverConfirmation?.problem = .notSent
}
}
rebuildRequests()
settleRequestNotifications(also: expired)
Expand Down
167 changes: 3 additions & 164 deletions iOS/AskKeyiOSKit/App/AppModel+Macs.swift
Original file line number Diff line number Diff line change
@@ -1,171 +1,10 @@
import AskKeyDevices
import Foundation

/// The approver confirmation while its sheet is open (ADR 0014 → Approvers, step 2).
public struct ApproverConfirmationFlow: Identifiable, Hashable, Sendable {
public enum Stage: Hashable, Sendable {
/// Typing the code.
case entering
/// Checking, and the Face ID prompt.
case confirming
/// Sealed; sending until CloudKit saves it.
case sending
/// Saved, and this iPhone's approval flag for the Mac is set.
case sent
}

public var id: String { macID }
public let macID: String
public let macName: String
public internal(set) var stage: Stage = .entering
public internal(set) var problem: ApproverProblem?

public init(macID: String, macName: String, stage: Stage = .entering, problem: ApproverProblem? = nil) {
self.macID = macID
self.macName = macName
self.stage = stage
self.problem = problem
}
}

/// Why the confirmation is not sent, or not sent yet.
public enum ApproverProblem: Hashable, Sendable {
/// Not exactly six digits once white space is removed; nothing was sent.
case invalidCode
case cancelled
case failed
case unavailable
case account
/// CloudKit has not saved it yet; it is tried again.
case retrying
/// It expired before CloudKit saved it.
case notSent
case other
}

/// The paired Macs on this iPhone: names, approval, removal.
/// The paired Macs on this iPhone: their names. Removal is in `AppModel`;
/// pairing is what makes this iPhone approve a Mac's requests (ADR 0014,
/// amended by #336).
extension AppModel {
// MARK: Approval

public func startApproverConfirmation(macID: String) {
guard stage == .ready, approverConfirmation == nil, let row = pairedMacs.first(where: { $0.id == macID }) else {
return
}
approverConfirmation = ApproverConfirmationFlow(macID: row.id, macName: row.name)
}

/// Closes the sheet. A confirmation already sealed is still sent, and
/// the flag set once CloudKit saves it.
public func closeApproverConfirmation() {
approverConfirmation = nil
}

/// **Approve Requests from This Mac**: sends nothing unless exactly six
/// ASCII digits remain once white space is removed; then signs the code
/// proof with the approval key (Face ID), and once CloudKit saved the
/// confirmation, sets this iPhone's approval flag for the Mac. It
/// cannot learn whether the Mac accepted.
public func confirmApprover(typed text: String) async {
guard let flow = approverConfirmation, flow.stage == .entering, let services,
let mac = DeviceID(text: flow.macID) else { return }
guard let code = ApproverCode(typed: text) else {
approverConfirmation?.problem = .invalidCode
return
}
approverConfirmation?.problem = nil
approverConfirmation?.stage = .confirming
func stop(_ problem: ApproverProblem) {
guard approverConfirmation?.macID == flow.macID else { return }
approverConfirmation?.stage = .entering
approverConfirmation?.problem = problem
}
guard await accountAllowsSending(services) else { return stop(.account) }
guard let list = try? await services.registry.list(), self.services === services,
let entry = list.device(mac) else { return stop(.other) }
let sealed: SealedDeviceMessage
do {
isAuthenticating = true
defer { isAuthenticating = false }
let reason = String(localized: "approver.reason \(entry.displayName)", bundle: .kit)
sealed = try await services.sealer.sealApproverConfirmation(code, to: entry, approvalReason: reason)
} catch let error as DeviceIdentityError {
switch error {
case .authenticationCancelled: return stop(.cancelled)
case .authenticationFailed: return stop(.failed)
case .authenticationUnavailable: return stop(.unavailable)
case .unusable, .secureEnclaveUnavailable, .keyCreationFailed:
approverConfirmation = nil
return identityBecameUnusable()
}
} catch {
AppLog.failure("Sealing an approver confirmation", error)
return stop(.other)
}
// The prompt may have outlasted the Mac's entry.
guard self.services === services, let after = try? await services.registry.list(),
after.device(mac)?.pairingID == entry.pairingID else { return stop(.other) }
outbox[sealed.envelope.recordName] = OutgoingMessage(envelope: sealed.envelope,
purpose: .confirmation(mac: mac, pairingID: entry.pairingID))
if approverConfirmation?.macID == flow.macID { approverConfirmation?.stage = .sending }
await sendDueMessages()
}

/// CloudKit saved the confirmation: the flag for that pairing is set.
/// A revocation that happened meanwhile wins: the flag is cleared again
/// and the revocation stays.
func confirmationSaved(mac: DeviceID, pairingID: PairingID, services: DeviceServices) async {
let revocations = revocationCount
do {
guard try await services.registry.apply(.setApprover(mac, pairingID: pairingID, enabled: true)) == .applied else {
if approverConfirmation?.macID == mac.text { approverConfirmation = nil }
return
}
guard revocationCount == revocations else {
_ = try await services.registry.apply(.setApprover(mac, pairingID: pairingID, enabled: false))
if approverConfirmation?.macID == mac.text { approverConfirmation = nil }
return await refreshList()
}
revokedPairings.remove(pairingID)
if approverConfirmation?.macID == mac.text {
approverConfirmation?.stage = .sent
approverConfirmation?.problem = nil
}
} catch {
AppLog.failure("Setting the approval flag", error)
if approverConfirmation?.macID == mac.text {
approverConfirmation?.stage = .entering
approverConfirmation?.problem = .other
}
}
await refreshList()
}

/// **Stop Approving for This Mac**: its requests are refused at once,
/// and its cards, stored decisions and notifications are dropped before
/// anything waits; then the flag is cleared. The Mac's own setting
/// changes on the Mac. Returns false when the flag could not be cleared,
/// so the person can try again; until then this process refuses the
/// Mac's requests.
@discardableResult
public func stopApproving(macID: String) async -> Bool {
guard let services, let mac = DeviceID(text: macID) else { return false }
var known = knownList?.device(mac)
if known == nil { known = try? await services.registry.list().device(mac) }
guard let entry = known else { return false }
revocationCount += 1
revokedPairings.insert(entry.pairingID)
dropApprovals(forMac: macID)
do {
try await services.registry.apply(.setApprover(mac, pairingID: entry.pairingID, enabled: false))
} catch {
AppLog.failure("Clearing the approval flag", error)
await refreshList()
return false
}
await refreshList()
return true
}

// MARK: Names

/// Renames a Mac on this iPhone. Names stay unique: a name another Mac
Expand Down
Loading
Loading