SPB Git

Repository Public

SecurityAssessment.swift 8.6 KB 176 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Features/SecurityCenter/SecurityAssessment.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation4243/// Pure reading of a `SecurityReport`: one finding per indicator and an overall44/// verdict derived from them. No value is assumed; what is not measured is said45/// to be unknown.46struct SecurityAssessment: Equatable, Sendable {47    enum Level: Int, Comparable, Sendable {48        case good, attention, risk49        static func < (a: Level, b: Level) -> Bool { a.rawValue < b.rawValue }50    }5152    enum Topic: String, Sendable, CaseIterable {53        case biometry, key, encryption, integrity, backup, recovery, fileProtection, backupExclusion54    }5556    struct Finding: Equatable, Sendable, Identifiable {57        var topic: Topic58        var level: Level59        var title: String60        var detail: String61        var id: String { topic.rawValue }62    }6364    var findings: [Finding]6566    var level: Level { findings.map(\.level).max() ?? .good }67    var issues: [Finding] { findings.filter { $0.level != .good } }68    func finding(_ topic: Topic) -> Finding? { findings.first { $0.topic == topic } }6970    var headline: String {71        switch level {72        case .good: "Vault secured"73        case .attention: issues.count == 1 ? "1 point needs attention" : "\(issues.count) points need attention"74        case .risk: "Action required"75        }76    }7778    var summary: String {79        switch level {80        case .good: "Every check passed on this device."81        case .attention, .risk: issues.map(\.title).joined(separator: " · ")82        }83    }8485    static let backupFreshDays = 3086    static let backupStaleDays = 908788    /// Age of the last backup in whole days, `nil` if there has never been one.89    static func backupAgeDays(_ lastBackup: Date?, now: Date) -> Int? {90        guard let lastBackup else { return nil }91        return max(0, Int(now.timeIntervalSince(lastBackup) / 86_400))92    }9394    static func backupLevel(lastBackup: Date?, cardCount: Int, now: Date) -> Level {95        guard let age = backupAgeDays(lastBackup, now: now) else { return cardCount == 0 ? .good : .attention }96        if age <= backupFreshDays { return .good }97        return age <= backupStaleDays ? .attention : .risk98    }99100    /// - Parameter fileProtectionEnforced: false on the simulator, where the101    ///   file system does not report protection classes.102    init(report: SecurityReport, now: Date = Date(), fileProtectionEnforced: Bool = true) {103        var findings: [Finding] = []104105        switch report.biometry {106        case .available(let kind):107            findings.append(Finding(topic: .biometry, level: .good, title: "\(kind.rawValue) ready", detail: "Required every time the vault opens."))108        case .lockedOut:109            findings.append(Finding(topic: .biometry, level: .attention, title: "Face ID locked by iOS",110                                    detail: "Unlock the iPhone with its passcode to re-enable it."))111        case .notEnrolled:112            findings.append(Finding(topic: .biometry, level: .risk, title: "Face ID not set up", detail: "The vault cannot be opened without it."))113        case .unavailable:114            findings.append(Finding(topic: .biometry, level: .risk, title: "Face ID unavailable", detail: "Biometry is off or unsupported on this device."))115        }116117        findings.append(report.keyPresent118            ? Finding(topic: .key, level: .good, title: "Master key in the Keychain", detail: report.keyProtection)119            : Finding(topic: .key, level: .risk, title: "Master key missing", detail: "The Keychain item is gone; recovery will be needed at the next unlock."))120121        findings.append(report.encryptionSelfTestPassed122            ? Finding(topic: .encryption, level: .good, title: "Encryption verified", detail: "Seal, reopen and tamper checks passed with the live key.")123            : Finding(topic: .encryption, level: .risk, title: "Encryption self-test failed", detail: "The live key could not seal and reopen a probe."))124125        findings.append(report.damagedCards == 0126            ? Finding(topic: .integrity, level: .good, title: "All cards intact", detail: "Every record authenticated when the vault opened.")127            : Finding(topic: .integrity, level: .risk, title: report.damagedCards == 1 ? "1 damaged card" : "\(report.damagedCards) damaged cards",128                      detail: "Their files failed authentication. Restore them from a backup."))129130        let backup = Self.backupLevel(lastBackup: report.lastBackupAt, cardCount: report.cardCount, now: now)131        if let age = Self.backupAgeDays(report.lastBackupAt, now: now) {132            let when = age == 0 ? "today" : age == 1 ? "yesterday" : "\(age) days ago"133            findings.append(Finding(topic: .backup, level: backup, title: backup == .good ? "Backup up to date" : "Backup is \(age) days old",134                                    detail: "Last encrypted backup made \(when)."))135        } else {136            findings.append(Finding(topic: .backup, level: backup, title: backup == .good ? "Nothing to back up yet" : "No backup yet",137                                    detail: backup == .good ? "The vault is empty." : "A lost or reset iPhone would lose every card."))138        }139140        findings.append(report.recoveryConfigured141            ? Finding(topic: .recovery, level: .good, title: "Recovery passphrase set",142                      detail: "PBKDF2-HMAC-SHA256" + (report.recoveryIterations.map { ", \($0.formatted()) iterations" } ?? ""))143            : Finding(topic: .recovery, level: .attention, title: "No recovery passphrase",144                      detail: "If Face ID is reset, only a backup can bring the cards back."))145146        let storage = report.storage147        if !fileProtectionEnforced {148            findings.append(Finding(topic: .fileProtection, level: .good, title: "File protection not reported",149                                    detail: "The simulator does not enforce protection classes; checked on a real iPhone only."))150        } else if storage.allFilesProtected {151            findings.append(Finding(topic: .fileProtection, level: .good, title: "Files protected",152                                    detail: "\(storage.protectedFiles) of \(storage.fileCount) files use complete protection."))153        } else {154            findings.append(Finding(topic: .fileProtection, level: .attention, title: "Some files lack complete protection",155                                    detail: "\(storage.protectedFiles) of \(storage.fileCount) files use complete protection."))156        }157158        findings.append(storage.excludedFromBackup159            ? Finding(topic: .backupExclusion, level: .good, title: "Kept out of iCloud and Finder backups", detail: "The vault folder is flagged as excluded.")160            : Finding(topic: .backupExclusion, level: .attention, title: "Vault folder not excluded from backups",161                      detail: "Device backups would carry the encrypted files."))162163        self.findings = findings164    }165}166167extension SecurityAssessment.Level {168    var tone: StatusTone {169        switch self {170        case .good: .positive171        case .attention: .warning172        case .risk: .critical173        }174    }175}176
Files main
Menu

Theme