DomainDig/DomainInspectionService.swift

v5.5.0
domain-dig/DomainDig/DomainInspectionService.swift history · blame · raw

665 lines · 31184 bytes

  1import Foundation
  2
  3struct DomainInspectionService {
  4    private let reportBuilder = DomainReportBuilder()
  5    private let runtime: LookupRuntime
  6
  7    init(runtime: LookupRuntime = .shared) {
  8        self.runtime = runtime
  9    }
 10
 11    func inspect(
 12        domain: String,
 13        previousSnapshot: LookupSnapshot? = nil,
 14        scope: InspectionScope
 15    ) async -> DomainReport {
 16        let snapshot = await inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
 17        return reportBuilder.build(from: snapshot)
 18    }
 19
 20    func inspectSnapshot(
 21        domain: String,
 22        previousSnapshot: LookupSnapshot? = nil,
 23        scope: InspectionScope
 24    ) async -> LookupSnapshot {
 25        let normalizedDomain = normalize(domain)
 26        let inspectionStartedAt = DomainDebugLog.signpostStart("Inspection.inspectSnapshot", domain: normalizedDomain)
 27        let startedAt = Date()
 28        let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
 29        let resolverURLString = DNSLookupService.currentResolverURLString()
 30        var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName, scope: scope)
 31
 32        async let dnsFetch = runtime.dns(domain: normalizedDomain)
 33        async let availabilityFetch = runtime.availability(domain: normalizedDomain, allowsRDAP: scope.allowsRDAP)
 34        async let sslFetch = runtime.ssl(domain: normalizedDomain)
 35        async let hstsFetch = runtime.hsts(domain: normalizedDomain)
 36        async let httpFetch = runtime.http(domain: normalizedDomain)
 37        async let ownershipFetch = whenInScope(.ownership, scope) {
 38            await runtime.ownership(domain: normalizedDomain)
 39        }
 40        async let redirectFetch = runtime.redirectChain(domain: normalizedDomain)
 41        async let subdomainFetch = whenInScope(.subdomains, scope) {
 42            await runtime.subdomains(domain: normalizedDomain)
 43        }
 44
 45        let resolvedDNS = await dnsFetch
 46        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)")
 47        let dnsResult = normalizeErrors(in: resolvedDNS.value)
 48        ledger.track(.dns, source: resolvedDNS.source)
 49        ledger.captureFailure(for: .dns, result: dnsResult)
 50
 51        let availability = await availabilityFetch
 52        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=availability source=\(availability.source.rawValue)")
 53        ledger.track(.availability, source: availability.source)
 54
 55        let resolvedSSL = await sslFetch
 56        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ssl source=\(resolvedSSL.source.rawValue)")
 57        let sslResult = normalizeErrors(in: resolvedSSL.value)
 58        ledger.track(.ssl, source: resolvedSSL.source)
 59        ledger.captureFailure(for: .ssl, result: sslResult)
 60
 61        let hsts = await hstsFetch
 62        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=hsts source=\(hsts.source.rawValue)")
 63        ledger.track(.hsts, source: hsts.source)
 64
 65        let http = await httpFetch
 66        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=http source=\(http.source.rawValue)")
 67        let httpResult = normalizeErrors(in: http.value)
 68        ledger.track(.httpHeaders, source: http.source)
 69        ledger.captureFailure(for: .httpHeaders, result: httpResult)
 70
 71        let resolvedOwnership = await ownershipFetch
 72        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)")
 73        let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
 74        if scope.runs(.ownership) {
 75            ledger.track(.ownership, source: resolvedOwnership.source)
 76            ledger.captureFailure(for: .ownership, result: ownershipResult)
 77        }
 78
 79        let redirects = await redirectFetch
 80        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)")
 81        let redirectResult = normalizeErrors(in: redirects.value)
 82        ledger.track(.redirectChain, source: redirects.source)
 83        ledger.captureFailure(for: .redirectChain, result: redirectResult)
 84
 85        let resolvedSubdomains = await subdomainFetch
 86        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)")
 87        let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
 88        if scope.runs(.subdomains) {
 89            ledger.track(.subdomains, source: resolvedSubdomains.source)
 90            ledger.captureFailure(for: .subdomains, result: subdomainResult)
 91        }
 92
 93        let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
 94        let sslInfo = mapOptionalValueServiceResult(sslResult)
 95        let httpHeadersResult = mapHTTPResult(httpResult)
 96        let redirectChain = mapServiceResult(redirectResult, emptyValue: [])
 97        let ownership = mapOptionalValueServiceResult(ownershipResult)
 98        let subdomains = mapServiceResult(subdomainResult, emptyValue: [])
 99
100        let txtRecords = dnsSections.value.first(where: { $0.recordType == .TXT })?.records ?? []
101        let primaryIP = dnsSections.value.first(where: { $0.recordType == .A })?.records.first?.value
102        let hasNetworkTarget = dnsSections.value.contains { section in
103            (section.recordType == .A || section.recordType == .AAAA)
104                && (!section.records.isEmpty || !section.wildcardRecords.isEmpty)
105        }
106        let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
107        let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
108
109        let reachabilityOutcome = await whenInScope(.reachability, scope) {
110            await whenRoutable(hasNetworkTarget) {
111                await runtime.reachability(domain: normalizedDomain)
112            }
113        }
114        let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value)
115        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)")
116        if scope.runs(.reachability) {
117            ledger.track(.reachability, source: reachabilityOutcome.source)
118            if hasNetworkTarget {
119                ledger.captureFailure(for: .reachability, result: reachabilityResult)
120            }
121        }
122        let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
123
124        let portScanOutcome = await whenInScope(.portScan, scope) {
125            await whenRoutable(hasNetworkTarget) {
126                await runtime.portScan(domain: normalizedDomain)
127            }
128        }
129        let portScanResult = normalizeErrors(in: portScanOutcome.value)
130        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)")
131        if scope.runs(.portScan) {
132            ledger.track(.portScan, source: portScanOutcome.source)
133            if hasNetworkTarget {
134                ledger.captureFailure(for: .portScan, result: portScanResult)
135            }
136        }
137        let portScanResults = scope.runs(.portScan) && hasNetworkTarget
138            ? await mapPortScanResult(portScanResult, domain: normalizedDomain)
139            : (value: [], message: scope.skipReason(for: .portScan))
140
141        let emailOutcome = await reusingPrevious(
142            previousSnapshot?.emailSecurity,
143            error: previousSnapshot?.emailSecurityError,
144            when: canReuseDNSDependents
145        ) {
146            await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
147        }
148        let normalizedEmailResult = normalizeErrors(in: emailOutcome.value)
149        DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=email source=\(emailOutcome.source.rawValue)")
150        ledger.track(.emailSecurity, source: emailOutcome.source)
151        ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult)
152
153        let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
154        if scope.runs(.suggestions), availability.value.status == .registered {
155            suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
156            ledger.track(.suggestions, source: suggestionsOutcome.source)
157        } else {
158            suggestionsOutcome = CachedLookupResult(value: [], source: .live)
159        }
160
161        let ptrOutcome: CachedLookupResult<ServiceResult<String>>?
162        let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>?
163        if let primaryIP {
164            let ptr = await reusingPrevious(
165                previousSnapshot?.ptrRecord,
166                error: previousSnapshot?.ptrError,
167                when: canReuseIPDependents
168            ) {
169                await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
170            }
171            let geo = await whenInScope(.ipGeolocation, scope) {
172                await reusingPrevious(
173                    previousSnapshot?.ipGeolocation,
174                    error: previousSnapshot?.ipGeolocationError,
175                    when: canReuseIPDependents
176                ) {
177                    await runtime.ipGeolocation(ip: primaryIP)
178                }
179            }
180            ledger.track(.ptr, source: ptr.source)
181            ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value))
182            if scope.runs(.ipGeolocation) {
183                ledger.track(.ipGeolocation, source: geo.source)
184                ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value))
185            }
186            ptrOutcome = ptr
187            geoOutcome = geo
188        } else {
189            ptrOutcome = nil
190            geoOutcome = nil
191        }
192
193        let emailSecurity = mapOptionalValueServiceResult(normalizedEmailResult)
194        let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
195        let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
196        let availabilityConfidence = confidenceForAvailability(result: availability.value, provenance: ledger.provenanceBySection[.availability])
197        let ownershipConfidence = confidenceForOwnership(result: ownership.value)
198        let subdomainConfidence = confidenceForSubdomains(results: subdomains.value)
199        let emailConfidence = confidenceForEmail(result: emailSecurity.value)
200        let geolocationConfidence = confidenceForGeolocation(result: geolocation.value)
201        let validationIssues = validationIssues(for: normalizedDomain, snapshotTimestamp: startedAt, availability: availability.value, dnsSections: dnsSections.value, provenanceBySection: ledger.provenanceBySection)
202
203        let snapshot = LookupSnapshot(
204            historyEntryID: nil,
205            domain: availability.value.domain,
206            timestamp: Date(),
207            trackedDomainID: previousSnapshot?.trackedDomainID,
208            note: previousSnapshot?.note,
209            appVersion: AppVersion.current,
210            resolverDisplayName: resolverDisplayName,
211            resolverURLString: resolverURLString,
212            dataSources: Array(ledger.dataSources).sorted(),
213            provenanceBySection: ledger.provenanceBySection,
214            availabilityConfidence: availabilityConfidence,
215            ownershipConfidence: ownershipConfidence,
216            subdomainConfidence: subdomainConfidence,
217            emailSecurityConfidence: emailConfidence,
218            geolocationConfidence: geolocationConfidence,
219            errorDetails: ledger.errorDetails,
220            isPartialSnapshot: !validationIssues.isEmpty,
221            validationIssues: validationIssues,
222            totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
223            snapshotIndex: nil,
224            previousSnapshotID: previousSnapshot?.historyEntryID,
225            changeCount: 0,
226            severitySummary: nil,
227            dnsSections: dnsSections.value,
228            dnsError: dnsSections.message,
229            availabilityResult: availability.value,
230            suggestions: suggestionsOutcome.value,
231            sslInfo: sslInfo.value,
232            sslError: sslInfo.message,
233            hstsPreloaded: hsts.value,
234            httpHeaders: httpHeadersResult.headers,
235            httpSecurityGrade: httpHeadersResult.securityGrade,
236            httpStatusCode: httpHeadersResult.statusCode,
237            httpResponseTimeMs: httpHeadersResult.responseTimeMs,
238            httpProtocol: httpHeadersResult.httpProtocol,
239            http3Advertised: httpHeadersResult.http3Advertised,
240            httpHeadersError: httpHeadersResult.error,
241            reachabilityResults: reachabilityResultValue.value,
242            reachabilityError: reachabilityResultValue.message,
243            ipGeolocation: geolocation.value,
244            ipGeolocationError: geolocation.message,
245            emailSecurity: emailSecurity.value,
246            emailSecurityError: emailSecurity.message,
247            ownership: ownership.value,
248            ownershipError: ownership.message,
249            ownershipHistory: [],
250            ownershipHistoryError: nil,
251            inferredProvider: nil,
252            priorProviders: [],
253            domainClassification: nil,
254            ownershipTransitions: [],
255            hostingTransitions: [],
256            subdomainHistory: [],
257            riskSignals: [],
258            intelligenceTimeline: [],
259            ptrRecord: ptrRecord.value,
260            ptrError: ptrRecord.message,
261            redirectChain: redirectChain.value,
262            redirectChainError: redirectChain.message,
263            subdomains: subdomains.value,
264            subdomainsError: subdomains.message,
265            extendedSubdomains: [],
266            extendedSubdomainsError: nil,
267            dnsHistory: [],
268            dnsHistoryError: nil,
269            domainPricing: nil,
270            domainPricingError: nil,
271            reputation: nil,
272            reputationError: nil,
273            portScanResults: portScanResults.value,
274            portScanError: portScanResults.message,
275            changeSummary: nil,
276            resultSource: aggregateSource(ledger.sectionSources),
277            cachedSections: Array(ledger.cachedSections).sorted { $0.rawValue < $1.rawValue },
278            statusMessage: nil
279        )
280        DomainDebugLog.signpostEnd(
281            "Inspection.inspectSnapshot",
282            start: inspectionStartedAt,
283            domain: normalizedDomain,
284            extra: "resultSource=\(snapshot.resultSource.rawValue) cachedSections=\(snapshot.cachedSections.count) partial=\(snapshot.isPartialSnapshot)"
285        )
286        return snapshot
287    }
288
289    private func normalize(_ domain: String) -> String {
290        domain
291            .trimmingCharacters(in: .whitespacesAndNewlines)
292            .replacingOccurrences(of: "https://", with: "")
293            .replacingOccurrences(of: "http://", with: "")
294            .components(separatedBy: "/").first?
295            .lowercased() ?? domain.lowercased()
296    }
297
298    /// The section's lookup, or a stand-in carrying why the scope skipped it.
299    private func whenInScope<Value>(
300        _ section: LookupSectionKind,
301        _ scope: InspectionScope,
302        fetch: () async -> CachedLookupResult<ServiceResult<Value>>
303    ) async -> CachedLookupResult<ServiceResult<Value>> {
304        guard let reason = scope.skipReason(for: section) else { return await fetch() }
305        return CachedLookupResult(value: .empty(reason), source: .live)
306    }
307
308    /// A lookup that needs an address to reach, or an empty result when the
309    /// domain has none.
310    private func whenRoutable<Value>(
311        _ hasNetworkTarget: Bool,
312        fetch: () async -> CachedLookupResult<ServiceResult<Value>>
313    ) async -> CachedLookupResult<ServiceResult<Value>> {
314        guard hasNetworkTarget else {
315            return CachedLookupResult(value: .empty("No routable address available"), source: .live)
316        }
317        return await fetch()
318    }
319
320    /// The previous snapshot's value, or its error, when its section can be
321    /// reused; otherwise a fresh lookup.
322    private func reusingPrevious<Value>(
323        _ value: Value?,
324        error: String?,
325        when reusable: Bool,
326        otherwise fetch: () async -> CachedLookupResult<ServiceResult<Value>>
327    ) async -> CachedLookupResult<ServiceResult<Value>> {
328        if reusable, let value {
329            return CachedLookupResult(value: .success(value), source: .cached)
330        }
331        if reusable, let error {
332            return CachedLookupResult(value: .error(error), source: .cached)
333        }
334        return await fetch()
335    }
336
337    fileprivate static func provenance(
338        for section: LookupSectionKind,
339        source: LookupResultSource,
340        collectedAt: Date,
341        resolverDisplayName: String,
342        allowsRDAP: Bool
343    ) -> SectionProvenance {
344        switch section {
345        case .dns, .ptr:
346            return SectionProvenance(
347                source: "DNS-over-HTTPS query",
348                collectedAt: collectedAt,
349                provider: "Selected DoH resolver",
350                resolver: resolverDisplayName,
351                resultSource: source
352            )
353        case .availability:
354            return SectionProvenance(
355                source: allowsRDAP ? "RDAP lookup with DNS fallback" : "DNS query",
356                collectedAt: collectedAt,
357                provider: allowsRDAP ? "rdap.org / selected resolver" : "Selected DoH resolver",
358                resolver: resolverDisplayName,
359                resultSource: source
360            )
361        case .ssl:
362            return SectionProvenance(source: "Direct TLS handshake", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
363        case .hsts, .httpHeaders, .redirectChain:
364            return SectionProvenance(source: "HTTP request", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
365        case .reachability:
366            return SectionProvenance(source: "TCP reachability probe", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
367        case .ipGeolocation:
368            return SectionProvenance(source: "IP geolocation lookup", collectedAt: collectedAt, provider: "ipapi.co", resolver: nil, resultSource: source)
369        case .emailSecurity:
370            return SectionProvenance(source: "DNS TXT inspection", collectedAt: collectedAt, provider: "Selected DoH resolver", resolver: resolverDisplayName, resultSource: source)
371        case .ownership:
372            return SectionProvenance(source: "RDAP domain lookup", collectedAt: collectedAt, provider: "rdap.org", resolver: nil, resultSource: source)
373        case .subdomains:
374            return SectionProvenance(source: "Certificate transparency search", collectedAt: collectedAt, provider: "crt.sh", resolver: nil, resultSource: source)
375        case .portScan:
376            return SectionProvenance(source: "TCP port scan", collectedAt: collectedAt, provider: "Target host", resolver: nil, resultSource: source)
377        case .suggestions:
378            return SectionProvenance(source: "Availability suggestions", collectedAt: collectedAt, provider: "DomainDig heuristic", resolver: resolverDisplayName, resultSource: source)
379        }
380    }
381
382    private func aggregateSource(_ sectionSources: [LookupResultSource]) -> LookupResultSource {
383        let normalizedSources = sectionSources.map { source -> LookupResultSource in
384            source == .mixed ? .cached : source
385        }
386
387        let hasLive = normalizedSources.contains(.live)
388        let hasCached = normalizedSources.contains(.cached)
389
390        switch (hasLive, hasCached) {
391        case (true, true):
392            return .mixed
393        case (false, true):
394            return .cached
395        default:
396            return .live
397        }
398    }
399
400    private func canReuseDependentSections(from previousSnapshot: LookupSnapshot?, dnsSections: [DNSSection]) -> Bool {
401        guard let previousSnapshot else { return false }
402        return dnsSignature(for: previousSnapshot.dnsSections) == dnsSignature(for: dnsSections)
403    }
404
405    private func canReuseIPBasedSections(from previousSnapshot: LookupSnapshot?, primaryIP: String?) -> Bool {
406        guard let previousSnapshot else { return false }
407        let previousIP = previousSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
408        return primaryIP == previousIP
409    }
410
411    private func dnsSignature(for sections: [DNSSection]) -> String {
412        sections
413            .sorted { $0.recordType.rawValue < $1.recordType.rawValue }
414            .map { section in
415                let records = section.records
416                    .sorted { $0.value < $1.value }
417                    .map { "\($0.value)|\($0.ttl)" }
418                    .joined(separator: ",")
419                let wildcardRecords = section.wildcardRecords
420                    .sorted { $0.value < $1.value }
421                    .map { "\($0.value)|\($0.ttl)" }
422                    .joined(separator: ",")
423                return [
424                    section.recordType.rawValue,
425                    records,
426                    wildcardRecords,
427                    section.dnssecSigned.map { $0 ? "signed" : "unsigned" } ?? "unknown",
428                    section.error ?? ""
429                ].joined(separator: "#")
430            }
431            .joined(separator: "||")
432    }
433
434    private func normalizeErrors<Value>(in result: ServiceResult<Value>) -> ServiceResult<Value> {
435        switch result {
436        case let .success(value):
437            return .success(value)
438        case let .empty(message):
439            return .empty(Self.classifyFailure(from: message, defaultKind: .unavailable).message)
440        case let .error(message):
441            return .error(Self.classifyFailure(from: message).message)
442        }
443    }
444
445    fileprivate static func classifyFailure(from message: String, defaultKind: InspectionErrorKind = .unknown) -> InspectionFailure {
446        let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
447        let lowercasedMessage = normalizedMessage.lowercased()
448        if lowercasedMessage.contains("timed out") {
449            return InspectionFailure(kind: .timeout, message: "Timed out", details: normalizedMessage)
450        }
451        if lowercasedMessage.contains("429")
452            || lowercasedMessage.contains("too many requests")
453            || lowercasedMessage.contains("rate limit") {
454            return InspectionFailure(kind: .rateLimited, message: "Rate limited", details: normalizedMessage)
455        }
456        if lowercasedMessage.contains("cannot parse")
457            || lowercasedMessage.contains("decoding")
458            || lowercasedMessage.contains("json") {
459            return InspectionFailure(kind: .parsing, message: "Could not parse response", details: normalizedMessage)
460        }
461        if lowercasedMessage.contains("offline")
462            || lowercasedMessage.contains("internet connection")
463            || lowercasedMessage.contains("not connected")
464            || lowercasedMessage.contains("network connection") {
465            return InspectionFailure(kind: .network, message: "Network unavailable", details: normalizedMessage)
466        }
467        if lowercasedMessage.contains("unsupported") {
468            return InspectionFailure(kind: .unsupported, message: "Unsupported for this target", details: normalizedMessage)
469        }
470        if lowercasedMessage == "unavailable" || lowercasedMessage.contains("no a record available") {
471            return InspectionFailure(kind: .unavailable, message: normalizedMessage, details: nil)
472        }
473        if defaultKind == .unavailable {
474            return InspectionFailure(kind: .unavailable, message: normalizedMessage, details: nil)
475        }
476        return InspectionFailure(kind: .unknown, message: normalizedMessage.isEmpty ? defaultKind.title : normalizedMessage, details: normalizedMessage)
477    }
478
479    private func confidenceForAvailability(result: DomainAvailabilityResult, provenance: SectionProvenance?) -> ConfidenceLevel {
480        guard result.status != .unknown else { return .low }
481        if provenance?.provider?.localizedCaseInsensitiveContains("rdap.org") == true, result.status == .registered {
482            return .high
483        }
484        if result.status == .registered {
485            return .medium
486        }
487        return .low
488    }
489
490    private func confidenceForOwnership(result: DomainOwnership?) -> ConfidenceLevel {
491        guard let result else { return .low }
492        let hasDirectRegistrationData = result.registrar != nil || result.createdDate != nil || result.expirationDate != nil
493        return hasDirectRegistrationData ? .high : .medium
494    }
495
496    private func confidenceForSubdomains(results: [DiscoveredSubdomain]) -> ConfidenceLevel {
497        if !results.isEmpty {
498            return .medium
499        }
500        return .low
501    }
502
503    private func confidenceForEmail(result: EmailSecurityResult?) -> ConfidenceLevel {
504        guard let result else { return .low }
505        let foundCount = [result.spf.found, result.dmarc.found, result.dkim.found, result.bimi.found, result.mtaSts?.txtFound == true]
506            .filter { $0 }
507            .count
508        if foundCount >= 3 {
509            return .high
510        }
511        if foundCount >= 1 {
512            return .medium
513        }
514        return .low
515    }
516
517    private func confidenceForGeolocation(result: IPGeolocation?) -> ConfidenceLevel {
518        guard let result else { return .low }
519        if result.city != nil && result.countryName != nil && result.latitude != nil && result.longitude != nil {
520            return .high
521        }
522        if result.countryName != nil || result.org != nil {
523            return .medium
524        }
525        return .low
526    }
527
528    private func validationIssues(
529        for domain: String,
530        snapshotTimestamp: Date,
531        availability: DomainAvailabilityResult,
532        dnsSections: [DNSSection],
533        provenanceBySection: [LookupSectionKind: SectionProvenance]
534    ) -> [String] {
535        var issues: [String] = []
536        if domain.isEmpty {
537            issues.append("Missing normalized domain")
538        }
539        if availability.domain.isEmpty {
540            issues.append("Missing normalized availability domain")
541        }
542        if dnsSections.isEmpty && provenanceBySection[.dns] == nil {
543            issues.append("Missing DNS provenance")
544        }
545        if snapshotTimestamp > Date().addingTimeInterval(5) {
546            issues.append("Snapshot timestamp is in the future")
547        }
548        return issues
549    }
550
551    private func mapServiceResult<Value>(_ result: ServiceResult<Value>, emptyValue: Value) -> (value: Value, message: String?) {
552        switch result {
553        case let .success(value):
554            return (value, nil)
555        case let .empty(message), let .error(message):
556            return (emptyValue, message)
557        }
558    }
559
560    private func mapOptionalValueServiceResult<Value>(_ result: ServiceResult<Value>) -> (value: Value?, message: String?) {
561        switch result {
562        case let .success(value):
563            return (value, nil)
564        case let .empty(message), let .error(message):
565            return (nil, message)
566        }
567    }
568
569    private func mapOptionalServiceResult<Value>(
570        _ result: ServiceResult<Value>?,
571        missingMessage: String
572    ) -> (value: Value?, message: String?) {
573        guard let result else {
574            return (nil, missingMessage)
575        }
576
577        switch result {
578        case let .success(value):
579            return (value, nil)
580        case let .empty(message), let .error(message):
581            return (nil, message)
582        }
583    }
584
585    private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
586        switch result {
587        case let .success(results):
588            return (await PortScanService.withBanners(results, host: domain), nil)
589        case let .empty(message), let .error(message):
590            return ([], message)
591        }
592    }
593
594    private func mapHTTPResult(_ result: ServiceResult<HTTPHeadersResult>) -> (
595        headers: [HTTPHeader],
596        securityGrade: String?,
597        statusCode: Int?,
598        responseTimeMs: Int?,
599        httpProtocol: String?,
600        http3Advertised: Bool,
601        error: String?
602    ) {
603        switch result {
604        case let .success(value):
605            return (
606                headers: value.headers,
607                securityGrade: HTTPSecurityGrade.grade(for: value.headers).rawValue,
608                statusCode: value.statusCode,
609                responseTimeMs: value.responseTimeMs,
610                httpProtocol: value.httpProtocol,
611                http3Advertised: value.http3Advertised,
612                error: nil
613            )
614        case let .empty(message), let .error(message):
615            return (
616                headers: [],
617                securityGrade: nil,
618                statusCode: nil,
619                responseTimeMs: nil,
620                httpProtocol: nil,
621                http3Advertised: false,
622                error: message
623            )
624        }
625    }
626}
627
628/// What an inspection has learned about its sections so far: where each came
629/// from, which were served from cache, and which failed.
630private struct InspectionLedger {
631    let resolverDisplayName: String
632    let scope: InspectionScope
633    var cachedSections = Set<LookupSectionKind>()
634    var sectionSources: [LookupResultSource] = []
635    var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
636    var dataSources = Set<String>()
637    var errorDetails: [LookupSectionKind: InspectionFailure] = [:]
638
639    mutating func track(_ section: LookupSectionKind, source: LookupResultSource) {
640        let provenance = DomainInspectionService.provenance(
641            for: section,
642            source: source,
643            collectedAt: Date(),
644            resolverDisplayName: resolverDisplayName,
645            allowsRDAP: scope.allowsRDAP
646        )
647        sectionSources.append(source)
648        provenanceBySection[section] = provenance
649        dataSources.insert(provenance.provider ?? provenance.source)
650        if source != .live {
651            cachedSections.insert(section)
652        }
653    }
654
655    mutating func captureFailure<Value>(for section: LookupSectionKind, result: ServiceResult<Value>) {
656        switch result {
657        case .success:
658            return
659        case let .empty(message):
660            errorDetails[section] = DomainInspectionService.classifyFailure(from: message, defaultKind: .unavailable)
661        case let .error(message):
662            errorDetails[section] = DomainInspectionService.classifyFailure(from: message)
663        }
664    }
665}