DomainDig/AuditFixtures.swift

196 lines · 8391 bytes

  1#if DEBUG
  2import Foundation
  3
  4/// Deterministic in-memory fixtures for the accessibility audit suite.
  5///
  6/// The dense rows (`WatchlistRowView`, `BatchResultRowView`) and the Dashboard
  7/// portfolio sections never render on a fresh simulator, so five phases of row
  8/// treatment shipped unverified by the automated audit. Driving the add-domain
  9/// UI instead was tried and rejected: typing raises the keyboard, which then
 10/// follows the audit onto later screens, and the added domains persist across
 11/// runs, contaminating every other test's baseline.
 12///
 13/// These are activated by the `DOMAIN_DIG_SEED_FIXTURES` launch argument
 14/// (DEBUG builds only, same pattern as `DOMAIN_DIG_FORCE_PRO_PLUS`) and are
 15/// **never persisted** — see `seedAuditFixturesIfRequested()`.
 16///
 17/// The set is chosen to exercise every row path: healthy/warning/critical
 18/// certificate badges, pinned, noted, changed, monitoring on/off, a
 19/// stress-length domain name, and every batch status including failure.
 20enum AuditFixtures {
 21    /// Clears the app's own store so an audit launch starts from a known
 22    /// state.
 23    ///
 24    /// The fixtures below are in-memory and never persist, but nothing stopped
 25    /// *other* state — whatever a previous run, a manual launch, or another
 26    /// test target left in the container — from reaching a screen the enforced
 27    /// suite audits as empty. That made the result depend on what ran before
 28    /// it: `testTrackedDomainsScreen` passes with one finding in isolation and
 29    /// reported an enforced `dynamicType` failure on `EditButton`, which only
 30    /// renders when the watchlist has rows, during a full `xcodebuild test`.
 31    ///
 32    /// Returns the store it cleared so a caller can thread it into whatever
 33    /// reads it first, which is what stops the reset being ordered after the
 34    /// read by accident.
 35    @discardableResult
 36    static func resetStoreIfRequested(_ defaults: UserDefaults = .standard) -> UserDefaults {
 37        guard ProcessInfo.processInfo.arguments.contains(resetStoreArgument) else {
 38            return defaults
 39        }
 40        if let domain = Bundle.main.bundleIdentifier {
 41            defaults.removePersistentDomain(forName: domain)
 42        }
 43        HistoryFileStore.removeAll(at: .default)
 44        return defaults
 45    }
 46
 47    static let resetStoreArgument = "DOMAIN_DIG_RESET_STORE"
 48
 49    static let launchArgument = "DOMAIN_DIG_SEED_FIXTURES"
 50
 51    static var requested: Bool {
 52        ProcessInfo.processInfo.arguments.contains(launchArgument)
 53    }
 54
 55    /// Relative to launch so the recency-gated Dashboard sections (Recent
 56    /// Activity, Attention Required — both keyed to the last 24h) actually
 57    /// render. Label text varies run to run ("2 hr. ago"); the audit measures
 58    /// layout and traits, not string equality, so coverage wins.
 59    private static let now = Date()
 60
 61    static var trackedDomains: [TrackedDomain] {
 62        [
 63            TrackedDomain(
 64                domain: "healthy.example",
 65                createdAt: now.addingTimeInterval(-86_400 * 30),
 66                updatedAt: now.addingTimeInterval(-3_600),
 67                isPinned: true,
 68                monitoringEnabled: true,
 69                lastKnownAvailability: .registered,
 70                certificateWarningLevel: .none,
 71                certificateDaysRemaining: 240,
 72                lastMonitoredAt: now.addingTimeInterval(-1_800)
 73            ),
 74            TrackedDomain(
 75                domain: "expiring.example",
 76                createdAt: now.addingTimeInterval(-86_400 * 90),
 77                updatedAt: now.addingTimeInterval(-7_200),
 78                monitoringEnabled: true,
 79                lastKnownAvailability: .registered,
 80                lastChangeSummary: DomainChangeSummary(
 81                    hasChanges: true,
 82                    changedSections: ["ssl"],
 83                    message: "Certificate is approaching expiry",
 84                    severity: .medium,
 85                    impactClassification: .warning,
 86                    generatedAt: now.addingTimeInterval(-7_200)
 87                ),
 88                lastChangeSeverity: .medium,
 89                certificateWarningLevel: .warning,
 90                certificateDaysRemaining: 12,
 91                lastMonitoredAt: now.addingTimeInterval(-7_200),
 92                lastAlertAt: now.addingTimeInterval(-7_000)
 93            ),
 94            TrackedDomain(
 95                domain: "broken.example",
 96                createdAt: now.addingTimeInterval(-86_400 * 7),
 97                updatedAt: now.addingTimeInterval(-600),
 98                note: "Production incident follow-up: certificate replaced?",
 99                monitoringEnabled: false,
100                lastKnownAvailability: .registered,
101                lastChangeSummary: DomainChangeSummary(
102                    hasChanges: true,
103                    changedSections: ["ssl", "dns"],
104                    message: "TLS validation failed and NS records changed",
105                    severity: .high,
106                    impactClassification: .critical,
107                    generatedAt: now.addingTimeInterval(-600)
108                ),
109                lastChangeSeverity: .high,
110                certificateWarningLevel: .critical,
111                certificateDaysRemaining: -3
112            ),
113            TrackedDomain(
114                domain: "very-long-subdomain.observability.internal.staging.example",
115                createdAt: now.addingTimeInterval(-86_400),
116                updatedAt: now.addingTimeInterval(-60),
117                monitoringEnabled: true,
118                lastKnownAvailability: .unknown
119            )
120        ]
121    }
122
123    static var batchResults: [BatchLookupResult] {
124        [
125            BatchLookupResult(
126                domain: "healthy.example",
127                historyEntryID: nil,
128                resultSource: .live,
129                availability: .registered,
130                primaryIP: "203.0.113.10",
131                quickStatus: "Stable",
132                summaryMessage: nil,
133                changeSeverity: nil,
134                changeClassification: nil,
135                certificateWarningLevel: .none,
136                riskScore: 12,
137                riskLevel: .low,
138                timestamp: now.addingTimeInterval(-120),
139                status: .completed,
140                errorMessage: nil
141            ),
142            BatchLookupResult(
143                domain: "expiring.example",
144                historyEntryID: nil,
145                resultSource: .cached,
146                availability: .registered,
147                primaryIP: "203.0.113.11",
148                quickStatus: "Changed",
149                summaryMessage: "Certificate is approaching expiry",
150                changeSeverity: .medium,
151                changeClassification: .warning,
152                certificateWarningLevel: .warning,
153                riskScore: 41,
154                riskLevel: .medium,
155                timestamp: now.addingTimeInterval(-3_600),
156                status: .completed,
157                errorMessage: nil
158            ),
159            BatchLookupResult(
160                domain: "broken.example",
161                historyEntryID: nil,
162                resultSource: .live,
163                availability: .registered,
164                primaryIP: "2001:db8::1f3:44",
165                quickStatus: "Changed",
166                summaryMessage: "TLS validation failed",
167                changeSeverity: .high,
168                changeClassification: .critical,
169                certificateWarningLevel: .critical,
170                riskScore: 78,
171                riskLevel: .high,
172                timestamp: now.addingTimeInterval(-60),
173                status: .completed,
174                errorMessage: nil
175            ),
176            BatchLookupResult(
177                domain: "unreachable.example",
178                historyEntryID: nil,
179                resultSource: .live,
180                availability: nil,
181                primaryIP: nil,
182                quickStatus: "Failed",
183                summaryMessage: nil,
184                changeSeverity: nil,
185                changeClassification: nil,
186                certificateWarningLevel: .none,
187                riskScore: nil,
188                riskLevel: nil,
189                timestamp: now,
190                status: .failed,
191                errorMessage: "The lookup timed out before any records were returned"
192            )
193        ]
194    }
195}
196#endif