DomainDig/AuditFixtures.swift

216 lines · 9279 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    /// Inspect's recent-searches section renders only once a lookup has been
 62    /// run, so a fresh-install audit never sees it. Assigning
 63    /// `recentSearches` does not persist — only `addRecentSearch` and
 64    /// `clearRecentSearches` write to defaults — so these stay in memory like
 65    /// the rest of the fixtures.
 66    ///
 67    /// Its own argument rather than part of `DOMAIN_DIG_SEED_FIXTURES`,
 68    /// because Inspect shows either a result or the recent list, never both:
 69    /// seeding the batch results takes the branch and the section never
 70    /// renders.
 71    static var recentSearches: [String] {
 72        ["healthy.example", "expiring.example", "broken.example"]
 73    }
 74
 75    static let recentSearchesArgument = "DOMAIN_DIG_SEED_RECENT"
 76
 77    static var recentSearchesRequested: Bool {
 78        ProcessInfo.processInfo.arguments.contains(recentSearchesArgument)
 79    }
 80
 81    static var trackedDomains: [TrackedDomain] {
 82        [
 83            TrackedDomain(
 84                domain: "healthy.example",
 85                createdAt: now.addingTimeInterval(-86_400 * 30),
 86                updatedAt: now.addingTimeInterval(-3_600),
 87                isPinned: true,
 88                monitoringEnabled: true,
 89                lastKnownAvailability: .registered,
 90                certificateWarningLevel: .none,
 91                certificateDaysRemaining: 240,
 92                lastMonitoredAt: now.addingTimeInterval(-1_800)
 93            ),
 94            TrackedDomain(
 95                domain: "expiring.example",
 96                createdAt: now.addingTimeInterval(-86_400 * 90),
 97                updatedAt: now.addingTimeInterval(-7_200),
 98                monitoringEnabled: true,
 99                lastKnownAvailability: .registered,
100                lastChangeSummary: DomainChangeSummary(
101                    hasChanges: true,
102                    changedSections: ["ssl"],
103                    message: "Certificate is approaching expiry",
104                    severity: .medium,
105                    impactClassification: .warning,
106                    generatedAt: now.addingTimeInterval(-7_200)
107                ),
108                lastChangeSeverity: .medium,
109                certificateWarningLevel: .warning,
110                certificateDaysRemaining: 12,
111                lastMonitoredAt: now.addingTimeInterval(-7_200),
112                lastAlertAt: now.addingTimeInterval(-7_000)
113            ),
114            TrackedDomain(
115                domain: "broken.example",
116                createdAt: now.addingTimeInterval(-86_400 * 7),
117                updatedAt: now.addingTimeInterval(-600),
118                note: "Production incident follow-up: certificate replaced?",
119                monitoringEnabled: false,
120                lastKnownAvailability: .registered,
121                lastChangeSummary: DomainChangeSummary(
122                    hasChanges: true,
123                    changedSections: ["ssl", "dns"],
124                    message: "TLS validation failed and NS records changed",
125                    severity: .high,
126                    impactClassification: .critical,
127                    generatedAt: now.addingTimeInterval(-600)
128                ),
129                lastChangeSeverity: .high,
130                certificateWarningLevel: .critical,
131                certificateDaysRemaining: -3
132            ),
133            TrackedDomain(
134                domain: "very-long-subdomain.observability.internal.staging.example",
135                createdAt: now.addingTimeInterval(-86_400),
136                updatedAt: now.addingTimeInterval(-60),
137                monitoringEnabled: true,
138                lastKnownAvailability: .unknown
139            )
140        ]
141    }
142
143    static var batchResults: [BatchLookupResult] {
144        [
145            BatchLookupResult(
146                domain: "healthy.example",
147                historyEntryID: nil,
148                resultSource: .live,
149                availability: .registered,
150                primaryIP: "203.0.113.10",
151                quickStatus: "Stable",
152                summaryMessage: nil,
153                changeSeverity: nil,
154                changeClassification: nil,
155                certificateWarningLevel: .none,
156                riskScore: 12,
157                riskLevel: .low,
158                timestamp: now.addingTimeInterval(-120),
159                status: .completed,
160                errorMessage: nil
161            ),
162            BatchLookupResult(
163                domain: "expiring.example",
164                historyEntryID: nil,
165                resultSource: .cached,
166                availability: .registered,
167                primaryIP: "203.0.113.11",
168                quickStatus: "Changed",
169                summaryMessage: "Certificate is approaching expiry",
170                changeSeverity: .medium,
171                changeClassification: .warning,
172                certificateWarningLevel: .warning,
173                riskScore: 41,
174                riskLevel: .medium,
175                timestamp: now.addingTimeInterval(-3_600),
176                status: .completed,
177                errorMessage: nil
178            ),
179            BatchLookupResult(
180                domain: "broken.example",
181                historyEntryID: nil,
182                resultSource: .live,
183                availability: .registered,
184                primaryIP: "2001:db8::1f3:44",
185                quickStatus: "Changed",
186                summaryMessage: "TLS validation failed",
187                changeSeverity: .high,
188                changeClassification: .critical,
189                certificateWarningLevel: .critical,
190                riskScore: 78,
191                riskLevel: .high,
192                timestamp: now.addingTimeInterval(-60),
193                status: .completed,
194                errorMessage: nil
195            ),
196            BatchLookupResult(
197                domain: "unreachable.example",
198                historyEntryID: nil,
199                resultSource: .live,
200                availability: nil,
201                primaryIP: nil,
202                quickStatus: "Failed",
203                summaryMessage: nil,
204                changeSeverity: nil,
205                changeClassification: nil,
206                certificateWarningLevel: .none,
207                riskScore: nil,
208                riskLevel: nil,
209                timestamp: now,
210                status: .failed,
211                errorMessage: "The lookup timed out before any records were returned"
212            )
213        ]
214    }
215}
216#endif