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
2 changes: 1 addition & 1 deletion Sources/AskKeyAppKit/AppLanguage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ enum AppLanguage {
"Expired without decision",
"Open Ask Key to review pending requests.",
"Disable system authentication for read approvals",
"Pair a device with this Mac",
"Pair an iPhone that can approve Agent requests",
"Ask Key could not save an access record. Credential operations continue, and this warning will remain until recording succeeds.",
"Ask Key could not prepare Agent access. Open the app to review the vault state.",
"Ask Key could not apply this decision. Open Pending requests to retry or reject it.",
Expand Down
273 changes: 54 additions & 219 deletions Sources/AskKeyAppKit/Devices/DeviceCoordinator+Approvers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,240 +2,75 @@ import AskKeyDevices
import AskKeyVault
import Foundation

/// Turning a paired iPhone's approval on and off (ADR 0014 → Approvers).
/// Which paired iPhones the Broker's active-approver set holds (ADR 0014 →
/// Approvers, #336). Pairing an iPhone writes its approval flag in the same
/// list write that adds it; the coordinator then adds that pairing ID alone
/// to the set, and repairs any flagged entry the set is missing whenever it
/// reads the list. Removing the pairing is the only way approval stops.
extension DeviceCoordinator {
/// The approver code exists for at most this long.
static let approverCodeLifetime: TimeInterval = 5 * 60
static let approverCodeAttempts = 3
/// The inbox's zone poll runs about once a second while the sheet waits,
/// because a confirmation has a random message ID.
static let approverPollInterval: TimeInterval = 1

/// **Approve agent requests**, step 1, in the management session: asks
/// for system authentication, records it with the Vault for this device
/// and pairing, then shows a new six-digit code for at most 5 minutes
/// and polls for the iPhone's confirmation. The open sheet keeps the
/// management session from expiring for idleness.
package func startApproverConfirmation(for id: DeviceID) async {
guard approverConfirmation?.isActive != true else { return }
guard let services, availability == .ready, account == .available,
let row = devices.first(where: { $0.id == id }), row.platform == .iOS, !row.isApprover else {
approverConfirmation = .ended(.unavailable)
return
}
guard managementSessionIsOpen() else {
approverConfirmation = .ended(.managementRequired)
return
}
approverGeneration += 1
let generation = approverGeneration
approverConfirmation = .authenticating(device: row)
acquireApproverExpiryHold()
let authenticate = environment.authenticate
let reason = ManagementAuthenticationAction.approveDevice.reasonKey
let prompt = Task { @MainActor in await authenticate(reason) }
approverAuthentication = prompt
let result = await prompt.value
guard generation == approverGeneration else { return }
approverAuthentication = nil
// The sheet may have closed, management locked, the services or the
// device's entry changed while the prompt was open.
guard !prompt.isCancelled, managementSessionIsOpen(), self.services === services,
devices.contains(where: { $0.id == row.id && $0.pairingID == row.pairingID && !$0.isApprover }) else {
return endApproverAttempt(.authenticationCancelled)
}
switch result {
case .authenticated(let authenticator):
do {
try vault.authorizeDeviceApprover(row.id, pairingID: row.pairingID, using: authenticator)
} catch {
return endApproverAttempt(.authenticationFailed)
}
case .cancelled:
return endApproverAttempt(.authenticationCancelled)
case .failed:
return endApproverAttempt(.authenticationFailed)
}
let code = ApproverCode.random()
let expiresAt = now.addingTimeInterval(Self.approverCodeLifetime)
approverAttempt = ApproverAttempt(device: row, code: code, expiresAt: expiresAt,
attemptsRemaining: Self.approverCodeAttempts)
approverCode = code
approverConfirmation = .waitingForIPhone(device: row, expiresAt: expiresAt,
attemptsRemaining: Self.approverCodeAttempts)
startApproverPolling()
}

/// **Cancel** or closing the sheet: discards the code and the authorization.
package func cancelApproverConfirmation() {
guard approverConfirmation != nil else { return }
approverGeneration += 1
finishApproverAttempt()
approverConfirmation = nil
}

func endApproverAttempt(_ reason: ApproverConfirmationEndReason) {
approverGeneration += 1
finishApproverAttempt()
approverConfirmation = .ended(reason)
}

/// Drops the code, the polling, the hold on idle expiry and the Vault's
/// approver authorization.
func finishApproverAttempt() {
approverAuthentication?.cancel()
approverAuthentication = nil
approverAttempt = nil
approverCode = nil
approverPollTask?.cancel()
approverPollTask = nil
approverExpiryHold?.release()
approverExpiryHold = nil
vault.endDeviceApproverAuthorization()
}

/// Step 3: a confirmation from the selected entry whose code proof
/// matches turns approval on; one with another proof counts as a wrong
/// code, and the third ends the attempt. A matching confirmation from
/// any other entry ends the attempt, because that device knows the code;
/// one that does not match is refused without counting.
func handleApproverConfirmation(_ message: VerifiedApprovalMessage,
_ confirmation: ApproverConfirmation) async -> ApprovalMessageHandling {
guard let mac = services?.deviceID, var attempt = approverAttempt, !attempt.enabling,
case .waitingForIPhone = approverConfirmation else { return .refused(.noSession) }
guard now < attempt.expiresAt else {
endApproverAttempt(.expired)
return .refused(.noSession)
}
let matches = attempt.code.matches(proof: confirmation.codeProof, mac: mac, phone: message.senderID,
pairingID: message.pairingID)
guard message.senderID == attempt.device.id, message.pairingID == attempt.device.pairingID else {
if matches {
environment.log(.approverCodeEnteredElsewhere)
endApproverAttempt(.enteredOnOtherDevice(name: message.sender.displayName))
}
return .refused(.bindingMismatch)
}
guard matches else {
attempt.attemptsRemaining -= 1
guard attempt.attemptsRemaining > 0 else {
endApproverAttempt(.tooManyWrongCodes)
return .refused(.bindingMismatch)
}
approverAttempt = attempt
approverConfirmation = .waitingForIPhone(device: attempt.device, expiresAt: attempt.expiresAt,
attemptsRemaining: attempt.attemptsRemaining)
return .refused(.bindingMismatch)
}
attempt.enabling = true
approverAttempt = attempt
await enableApprover(attempt.device)
return .processed
/// Device services ready with the list's account available.
var canActivateApprovers: Bool {
services != nil && availability == .ready && account == .available
}

/// Writes the flag, which uses the Vault's authorization up, then adds
/// only this device to the Broker's set, so other approvers keep their
/// generations.
private func enableApprover(_ row: PairedDeviceRow) async {
guard let services else { return }
let generation = approverGeneration
let outcome: PairedDeviceChangeOutcome?
/// Loads the set from the list once the services are ready with the
/// list's account: every flagged entry gets a new generation, except one
/// whose removal began, also when its write failed or is still pending.
func activateApproversIfNeeded() {
guard canActivateApprovers, !approversLoaded else { return }
trackPendingRequestsBeforeActivation()
do {
outcome = try await services.registry.apply(.setApprover(row.id, pairingID: row.pairingID, enabled: true))
try vault.activateStoredApprovers(excluding: revokedApprovers)
approversLoaded = true
} catch {
outcome = nil
}
if outcome == .applied {
if approversLoaded {
do {
try vault.activateStoredApprovers(only: row.pairingID)
} catch {
// Added alone at the next account check, so the other
// approvers keep their generations.
approversAwaitingActivation.insert(row.pairingID)
environment.log(.approverActivationFailed)
}
} else {
activateApproversIfNeeded()
}
environment.log(.approverEnabled)
}
await publish()
guard generation == approverGeneration else { return }
switch outcome {
case .applied?:
let updated = devices.first { $0.id == row.id && $0.pairingID == row.pairingID } ?? row
approverGeneration += 1
finishApproverAttempt()
approverConfirmation = .enabled(device: updated)
case nil:
endApproverAttempt(.notSaved)
default:
endApproverAttempt(.deviceRemoved)
environment.log(.approverActivationFailed)
}
}

/// Turns a device's approval off, in the management session: it leaves
/// the Broker's set first, then the flag is written, then its outstanding
/// requests close with outcome 5 (ADR 0014 → Revocation). Reducing
/// authority needs no fresh authentication.
@discardableResult
package func disableApprover(_ row: PairedDeviceRow) async -> Bool {
guard let services else { return false }
guard managementSessionIsOpen() else {
lastIssue = .managementRequired
return false
}
lastIssue = nil
vault.approvalRequests.removeActiveApprover(pairingID: row.pairingID.rawValue)
let lifecycle = self.lifecycle
var applied = false
do {
let outcome = try await services.registry.apply(.setApprover(row.id, pairingID: row.pairingID, enabled: false))
applied = outcome == .applied
if outcome == .dropped, lifecycle == self.lifecycle { lastIssue = .deviceNotFound }
} catch {
if lifecycle == self.lifecycle { lastIssue = .actionFailed }
}
guard lifecycle == self.lifecycle else { return applied }
closeRemoteRequests(of: row.id, pairingID: row.pairingID)
await publish()
return applied
/// A pairing added `pairingID` to the list: it joins the set alone as
/// soon as the coordinator learns of the add, whether or not the pairing
/// sheet is still open, so the other approvers keep their generations.
func pairingAdded(_ pairingID: PairingID) {
guard canActivateApprovers else { return }
guard approversLoaded else { return activateApproversIfNeeded() }
activateMissingApprover(pairingID)
}

// MARK: Schedule

func startApproverPolling() {
approverPollTask?.cancel()
approverPollTask = nil
guard environment.automaticPolling else { return }
let sleep = environment.sleep
approverPollTask = Task { [weak self] in
while !Task.isCancelled {
try? await sleep(Self.approverPollInterval)
guard let self, !Task.isCancelled, await self.approverLoopStep() else { return }
}
/// Every list read with the services ready and the account available:
/// each flagged entry missing from the set is added alone, so a missed
/// or failed addition is repaired without new generations for the others.
func reconcileActiveApprovers(with list: [PairedDevice]) {
guard canActivateApprovers else { return }
guard approversLoaded else { return activateApproversIfNeeded() }
for device in list where device.isApprover {
activateMissingApprover(device.pairingID)
}
}

/// One turn of the open sheet: ends the attempt when its code expired or
/// management closed, otherwise keeps management open and polls.
/// Returns whether to go on.
func approverLoopStep() async -> Bool {
guard let attempt = approverAttempt, case .waitingForIPhone = approverConfirmation else { return false }
guard now < attempt.expiresAt else {
endApproverAttempt(.expired)
return false
}
guard managementSessionIsOpen() else {
cancelApproverConfirmation()
return false
/// Adds one pairing ID unless it is in the set already or its removal
/// has begun. The Vault reads the revocation counter and the stored list
/// itself, so an entry removed meanwhile is not added, and a removal that
/// races the addition makes the Broker refuse it (ADR 0014 → Revocation).
private func activateMissingApprover(_ pairingID: PairingID) {
guard !revokedApprovers.contains(pairingID),
vault.approvalRequests.activeApproverGeneration(pairingID: pairingID.rawValue) == nil else { return }
trackPendingRequestsBeforeActivation()
do {
if !(try vault.activateStoredApprovers(only: pairingID)).isEmpty {
environment.log(.approverActivated)
}
} catch {
// The next list read tries again.
environment.log(.approverActivationFailed)
}
await refresh()
return approverAttempt != nil
}

func acquireApproverExpiryHold() {
if approverExpiryHold == nil { approverExpiryHold = SessionPolicy.holdIdleExpiry() }
/// Eligibility is decided when a request is created, but the Broker's
/// notification reaches the coordinator later, and can be merged into a
/// later one. Tracking every pending request against the set as it is
/// before an addition keeps a request the coordinator has not seen yet
/// from going to an approver that joined after it.
private func trackPendingRequestsBeforeActivation() {
reconcileRemoteRequests()
}
}
7 changes: 4 additions & 3 deletions Sources/AskKeyAppKit/Devices/DeviceCoordinator+Pairing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,7 @@ extension DeviceCoordinator {
}

/// The management session ended (locked, expired or its window closed).
/// An open approver sheet ends too, with its code and authorization.
package func managementSessionEnded() async {
if approverConfirmation?.isActive == true { cancelApproverConfirmation() }
guard pairingIsLive else {
finishPairingSession()
return
Expand Down Expand Up @@ -250,7 +248,7 @@ extension DeviceCoordinator {
pairing = .codeAccepted(peer: peer)
case .waitingForPeer(let peer):
pairing = .waitingForIPhoneConfirmation(peer: peer)
case .paired(let peer, _):
case .paired(let peer, let pairingID):
pairing = .paired(peer: peer)
pairingFeedback = nil
environment.log(.devicePaired)
Expand All @@ -260,6 +258,9 @@ extension DeviceCoordinator {
isAuthenticatingPairing = false
vault.endDevicePairingAuthorization()
deliveryCheckAfterPairing = peer.deviceID
// The add wrote the iPhone's flag; it joins the set now. A sheet
// that closed first is covered by the next list read.
pairingAdded(pairingID)
case .ended(let reason):
pairing = .ended(reason)
environment.log(.pairingEnded(reason))
Expand Down
Loading
Loading