DomainDigTests/Fixtures/SnapshotFixture.swift

2ad5d8160338d289a65d6a4d1c214a02bf916f1f
domain-dig/DomainDigTests/Fixtures/SnapshotFixture.swift history · blame · raw

302 lines · 12397 bytes

8 symbols in this file
  1import Foundation
  2@testable import DomainDig
  3
  4/// Deterministic builders for the deep `LookupSnapshot` / `DomainReport` models
  5/// so the core unit tests can construct inputs without wiring up every one of the
  6/// ~75 snapshot fields at each call site.
  7///
  8/// `snapshot(...)` exposes only the fields the tests actually vary; everything
  9/// else defaults to an empty/absent value. `report(...)` runs a snapshot through
 10/// the real `DomainReportBuilder`, which is both the natural constructor for the
 11/// otherwise-unconstructable `DomainReport` and, for the builder tests, the unit
 12/// under test.
 13enum SnapshotFixture {
 14    /// Fixed instant so timestamp-derived output (diff ranges, export headers) is
 15    /// stable across runs.
 16    static let referenceDate = Date(timeIntervalSince1970: 1_700_000_000)
 17
 18    static let defaultResolverURL = "https://resolver.example/dns-query"
 19
 20    /// Per-section failure messages, so a test can build a snapshot where one
 21    /// section failed and the rest succeeded. `LookupSnapshot` keeps a value
 22    /// and an error per section independently, and the views render the error
 23    /// over the value — which is the contract the section slices have to
 24    /// preserve.
 25    struct SectionFailures {
 26        var dnsError: String?
 27        var sslError: String?
 28        var httpHeadersError: String?
 29        var reachabilityError: String?
 30        var ipGeolocationError: String?
 31        var emailSecurityError: String?
 32        var ownershipError: String?
 33        var ptrError: String?
 34        var redirectChainError: String?
 35        var subdomainsError: String?
 36        var portScanError: String?
 37    }
 38
 39    static func snapshot(
 40        domain: String = "example.com",
 41        timestamp: Date = referenceDate,
 42        resolverURLString: String = defaultResolverURL,
 43        resultSource: LookupResultSource = .live,
 44        availability: DomainAvailabilityStatus? = nil,
 45        ownership: DomainOwnership? = nil,
 46        dnsSections: [DNSSection] = [],
 47        ptrRecord: String? = nil,
 48        sslInfo: SSLCertificateInfo? = nil,
 49        httpHeaders: [HTTPHeader] = [],
 50        httpStatusCode: Int? = nil,
 51        httpSecurityGrade: String? = nil,
 52        subdomains: [DiscoveredSubdomain] = [],
 53        extendedSubdomains: [DiscoveredSubdomain] = [],
 54        isPartialSnapshot: Bool = false,
 55        validationIssues: [String] = [],
 56        changeSummary: DomainChangeSummary? = nil,
 57        failures: SectionFailures = SectionFailures(),
 58        provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
 59    ) -> LookupSnapshot {
 60        LookupSnapshot(
 61            historyEntryID: nil,
 62            domain: domain,
 63            timestamp: timestamp,
 64            trackedDomainID: nil,
 65            note: nil,
 66            appVersion: "test",
 67            resolverDisplayName: "Test Resolver",
 68            resolverURLString: resolverURLString,
 69            dataSources: [],
 70            provenanceBySection: provenanceBySection,
 71            availabilityConfidence: nil,
 72            ownershipConfidence: nil,
 73            subdomainConfidence: nil,
 74            emailSecurityConfidence: nil,
 75            geolocationConfidence: nil,
 76            errorDetails: [:],
 77            isPartialSnapshot: isPartialSnapshot,
 78            validationIssues: validationIssues,
 79            totalLookupDurationMs: nil,
 80            snapshotIndex: nil,
 81            previousSnapshotID: nil,
 82            changeCount: 0,
 83            severitySummary: nil,
 84            dnsSections: dnsSections,
 85            dnsError: failures.dnsError,
 86            availabilityResult: availability.map { DomainAvailabilityResult(domain: domain, status: $0) },
 87            suggestions: [],
 88            sslInfo: sslInfo,
 89            sslError: failures.sslError,
 90            hstsPreloaded: nil,
 91            httpHeaders: httpHeaders,
 92            httpSecurityGrade: httpSecurityGrade,
 93            httpStatusCode: httpStatusCode,
 94            httpResponseTimeMs: nil,
 95            httpProtocol: nil,
 96            http3Advertised: false,
 97            httpHeadersError: failures.httpHeadersError,
 98            reachabilityResults: [],
 99            reachabilityError: failures.reachabilityError,
100            ipGeolocation: nil,
101            ipGeolocationError: failures.ipGeolocationError,
102            emailSecurity: nil,
103            emailSecurityError: failures.emailSecurityError,
104            ownership: ownership,
105            ownershipError: failures.ownershipError,
106            ownershipHistory: [],
107            ownershipHistoryError: nil,
108            inferredProvider: nil,
109            priorProviders: [],
110            domainClassification: nil,
111            ownershipTransitions: [],
112            hostingTransitions: [],
113            subdomainHistory: [],
114            riskSignals: [],
115            intelligenceTimeline: [],
116            ptrRecord: ptrRecord,
117            ptrError: failures.ptrError,
118            redirectChain: [],
119            redirectChainError: failures.redirectChainError,
120            subdomains: subdomains,
121            subdomainsError: failures.subdomainsError,
122            extendedSubdomains: extendedSubdomains,
123            extendedSubdomainsError: nil,
124            dnsHistory: [],
125            dnsHistoryError: nil,
126            domainPricing: nil,
127            domainPricingError: nil,
128            reputation: nil,
129            reputationError: nil,
130            portScanResults: [],
131            portScanError: failures.portScanError,
132            changeSummary: changeSummary,
133            resultSource: resultSource,
134            cachedSections: [],
135            statusMessage: nil
136        )
137    }
138
139    static func report(
140        domain: String = "example.com",
141        timestamp: Date = referenceDate,
142        resolverURLString: String = defaultResolverURL,
143        resultSource: LookupResultSource = .live,
144        availability: DomainAvailabilityStatus? = nil,
145        ownership: DomainOwnership? = nil,
146        dnsSections: [DNSSection] = [],
147        ptrRecord: String? = nil,
148        sslInfo: SSLCertificateInfo? = nil,
149        httpHeaders: [HTTPHeader] = [],
150        httpStatusCode: Int? = nil,
151        httpSecurityGrade: String? = nil,
152        subdomains: [DiscoveredSubdomain] = [],
153        extendedSubdomains: [DiscoveredSubdomain] = [],
154        isPartialSnapshot: Bool = false,
155        validationIssues: [String] = []
156    ) -> DomainReport {
157        DomainReportBuilder().build(
158            from: snapshot(
159                domain: domain,
160                timestamp: timestamp,
161                resolverURLString: resolverURLString,
162                resultSource: resultSource,
163                availability: availability,
164                ownership: ownership,
165                dnsSections: dnsSections,
166                ptrRecord: ptrRecord,
167                sslInfo: sslInfo,
168                httpHeaders: httpHeaders,
169                httpStatusCode: httpStatusCode,
170                httpSecurityGrade: httpSecurityGrade,
171                subdomains: subdomains,
172                extendedSubdomains: extendedSubdomains,
173                isPartialSnapshot: isPartialSnapshot,
174                validationIssues: validationIssues
175            ),
176            deriveChangeSummary: false
177        )
178    }
179
180    // MARK: - Nested model conveniences
181
182    static func dnsSection(
183        type: DNSRecordType,
184        values: [String],
185        ttl: Int = 300,
186        dnssecSigned: Bool? = nil,
187        wildcards: [String] = []
188    ) -> DNSSection {
189        DNSSection(
190            recordType: type,
191            records: values.map { DNSRecord(value: $0, ttl: ttl) },
192            wildcardRecords: wildcards.map { DNSRecord(value: $0, ttl: ttl) },
193            dnssecSigned: dnssecSigned
194        )
195    }
196
197    /// A `HistoryEntry` with every section populated, for the tests that care
198    /// about the persisted store rather than about one field. The store holds
199    /// up to 2000 of these at the Pro+ cap, so `index` varies the content: an
200    /// entry repeated verbatim would not measure a realistic encode.
201    static func historyEntry(index: Int = 0, domain: String? = nil) -> HistoryEntry {
202        let host = domain ?? "domain\(index).example"
203        return HistoryEntry(
204            identity: .init(
205                domain: host,
206                timestamp: referenceDate.addingTimeInterval(Double(index)),
207                trackedDomainID: UUID(),
208                note: "note for \(host)"
209            ),
210            inspection: .init(
211                dnsSections: [
212                    dnsSection(type: .A, values: ["203.0.113.\(index % 256)", "198.51.100.\(index % 256)"]),
213                    dnsSection(type: .MX, values: ["10 mail.\(host)"]),
214                    dnsSection(type: .TXT, values: ["v=spf1 include:_spf.\(host) -all"])
215                ],
216                sslInfo: certificate(commonName: host, daysUntilExpiry: 30 + index % 300),
217                httpHeaders: [
218                    HTTPHeader(name: "strict-transport-security", value: "max-age=31536000"),
219                    HTTPHeader(name: "content-security-policy", value: "default-src 'self'"),
220                    HTTPHeader(name: "server", value: "test/\(index)")
221                ],
222                reachabilityResults: [
223                    PortReachability(port: 80, reachable: true, latencyMs: 12 + index % 50),
224                    PortReachability(port: 443, reachable: true, latencyMs: 15 + index % 50)
225                ],
226                ipGeolocation: IPGeolocation(
227                    ip: "203.0.113.\(index % 256)",
228                    city: "Testville",
229                    region: "Test Region",
230                    countryName: "Testland",
231                    org: "Test Org \(index)",
232                    latitude: 45.0,
233                    longitude: -93.0
234                ),
235                ptrRecord: "host\(index).\(host)",
236                redirectChain: [
237                    RedirectHop(stepNumber: 1, statusCode: 301, url: "http://\(host)", isFinal: false),
238                    RedirectHop(stepNumber: 2, statusCode: 200, url: "https://\(host)", isFinal: true)
239                ],
240                subdomains: (0..<5).map { DiscoveredSubdomain(hostname: "sub\($0).\(host)", source: "crt.sh") },
241                hstsPreloaded: index.isMultiple(of: 2)
242            ),
243            registration: .init(priorProviders: ["Provider \(index)", "Provider \(index + 1)"]),
244            intelligence: .init(
245                riskSignals: [
246                    IntelligenceRiskSignal(
247                        id: "signal-\(index)",
248                        title: "Signal \(index)",
249                        detail: "A detail string long enough to be representative of a real finding.",
250                        severity: .medium,
251                        firstObserved: referenceDate,
252                        lastObserved: referenceDate.addingTimeInterval(Double(index))
253                    )
254                ]
255            ),
256            provenance: .init(
257                dataSources: ["dns", "tls", "http", "crt.sh"],
258                validationIssues: [],
259                resolverDisplayName: "Test Resolver",
260                resolverURLString: defaultResolverURL,
261                totalLookupDurationMs: 1200 + index
262            ),
263            summary: .init(
264                primaryIP: "203.0.113.\(index % 256)",
265                finalRedirectURL: "https://\(host)",
266                tlsStatusSummary: "Valid",
267                snapshotIndex: index,
268                changeCount: index % 4
269            )
270        )
271    }
272
273    static func provenance(
274        source: String = "test",
275        provider: String? = nil,
276        resultSource: LookupResultSource = .live
277    ) -> SectionProvenance {
278        SectionProvenance(
279            source: source,
280            collectedAt: referenceDate,
281            provider: provider,
282            resolver: nil,
283            resultSource: resultSource
284        )
285    }
286
287    static func certificate(
288        commonName: String = "example.com",
289        issuer: String = "Test CA",
290        daysUntilExpiry: Int = 90
291    ) -> SSLCertificateInfo {
292        SSLCertificateInfo(
293            commonName: commonName,
294            subjectAltNames: [commonName],
295            issuer: issuer,
296            validFrom: referenceDate,
297            validUntil: referenceDate.addingTimeInterval(Double(daysUntilExpiry) * 86_400),
298            daysUntilExpiry: daysUntilExpiry,
299            chainDepth: 1
300        )
301    }
302}