DomainDig/DiffService.swift

fd34553ab0e63b4d3bc22532b61f4fef32846f34
domain-dig/DomainDig/DiffService.swift history · blame · raw

563 lines · 24298 bytes

  1import Foundation
  2
  3enum DiffChangeType: String, Codable {
  4    case added
  5    case removed
  6    case changed
  7    case unchanged
  8
  9    var marker: String {
 10        switch self {
 11        case .added:
 12            return "+"
 13        case .removed:
 14            return "-"
 15        case .changed:
 16            return "~"
 17        case .unchanged:
 18            return "="
 19        }
 20    }
 21
 22    var title: String {
 23        switch self {
 24        case .added:
 25            return "Added"
 26        case .removed:
 27            return "Removed"
 28        case .changed:
 29            return "Changed"
 30        case .unchanged:
 31            return "Unchanged"
 32        }
 33    }
 34}
 35
 36struct DiffItem: Identifiable, Equatable, Codable {
 37    let id: String
 38    let label: String
 39    let changeType: DiffChangeType
 40    let oldValue: String?
 41    let newValue: String?
 42    let severity: ChangeSeverity
 43
 44    init(
 45        id: String,
 46        label: String,
 47        changeType: DiffChangeType,
 48        oldValue: String?,
 49        newValue: String?,
 50        severity: ChangeSeverity
 51    ) {
 52        self.id = id
 53        self.label = label
 54        self.changeType = changeType
 55        self.oldValue = oldValue
 56        self.newValue = newValue
 57        self.severity = severity
 58    }
 59
 60    var hasChanges: Bool {
 61        changeType != .unchanged
 62    }
 63}
 64
 65struct DiffSection: Identifiable, Equatable, Codable {
 66    let id: String
 67    let title: String
 68    let items: [DiffItem]
 69
 70    var hasChanges: Bool {
 71        items.contains(where: \.hasChanges)
 72    }
 73
 74    var severity: ChangeSeverity {
 75        items.map(\.severity).max() ?? .low
 76    }
 77
 78    var changeCount: Int {
 79        items.filter(\.hasChanges).count
 80    }
 81}
 82
 83struct DomainDiff: Identifiable, Equatable, Codable {
 84    let domain: String
 85    let fromTimestamp: Date
 86    let toTimestamp: Date
 87    let sections: [DiffSection]
 88    let changedSectionIDs: [String]
 89    let changedSectionTitles: [String]
 90    let contextNote: String?
 91
 92    var id: String {
 93        "\(domain)-\(fromTimestamp.timeIntervalSince1970)-\(toTimestamp.timeIntervalSince1970)"
 94    }
 95
 96    var changeCount: Int {
 97        sections.reduce(0) { $0 + $1.changeCount }
 98    }
 99
100    var severity: ChangeSeverity {
101        sections.map(\.severity).max() ?? .low
102    }
103}
104
105typealias DomainDiffItem = DiffItem
106typealias DomainDiffSection = DiffSection
107
108enum DiffService {
109    static func compare(from oldReport: DomainReport, to newReport: DomainReport) -> DomainDiff {
110        let sections = [
111            availabilitySection(from: oldReport, to: newReport),
112            ownershipSection(from: oldReport, to: newReport),
113            dnsSection(from: oldReport, to: newReport),
114            webSection(from: oldReport, to: newReport),
115            emailSection(from: oldReport, to: newReport),
116            networkSection(from: oldReport, to: newReport),
117            subdomainsSection(from: oldReport, to: newReport),
118            riskSection(from: oldReport, to: newReport)
119        ]
120
121        let changedSections = sections.filter(\.hasChanges)
122        return DomainDiff(
123            domain: newReport.domain,
124            fromTimestamp: oldReport.timestamp,
125            toTimestamp: newReport.timestamp,
126            sections: sections,
127            changedSectionIDs: changedSections.map(\.id),
128            changedSectionTitles: changedSections.map(\.title),
129            contextNote: comparisonContextNote(from: oldReport, to: newReport)
130        )
131    }
132
133    static func compare(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> DomainDiff {
134        let builder = DomainReportBuilder()
135        let oldReport = builder.build(from: oldSnapshot, deriveChangeSummary: false)
136        let newReport = builder.build(from: newSnapshot, previousSnapshot: oldSnapshot, deriveChangeSummary: false)
137        return compare(from: oldReport, to: newReport)
138    }
139
140    static func summary(
141        from oldSnapshot: LookupSnapshot,
142        to newSnapshot: LookupSnapshot,
143        generatedAt: Date = Date(),
144        riskAssessment: DomainRiskAssessment? = nil,
145        insights: [String]? = nil
146    ) -> DomainChangeSummary {
147        let diff = compare(from: oldSnapshot, to: newSnapshot)
148        let changedItems = diff.sections.flatMap(\.items).filter(\.hasChanges)
149        let highlights = diff.changedSectionTitles
150        let severity = changedItems.map(\.severity).max() ?? .low
151        let message = summaryMessage(from: highlights, changeCount: changedItems.count)
152        let observedFacts = changedItems.prefix(4).map { item in
153            "\(item.label): \(item.oldValue ?? "none") -> \(item.newValue ?? "none")"
154        }
155
156        let analysis = DomainInsightEngine.analyze(snapshot: newSnapshot, previousSnapshot: oldSnapshot)
157        let currentRiskAssessment = riskAssessment ?? analysis.riskAssessment
158        let currentInsights = insights ?? analysis.insights
159        let previousRiskScore = DomainInsightEngine.analyze(snapshot: oldSnapshot).riskAssessment.score
160        let riskScoreDelta = currentRiskAssessment.score - previousRiskScore
161        let impactClassification = DomainInsightEngine.impactClassification(
162            severity: severity,
163            riskDelta: riskScoreDelta,
164            changedSections: highlights
165        )
166
167        return DomainChangeSummary(
168            hasChanges: !changedItems.isEmpty,
169            changedSections: highlights,
170            message: message,
171            severity: severity,
172            impactClassification: impactClassification,
173            generatedAt: generatedAt,
174            observedFacts: observedFacts,
175            inferredConclusions: highlights.isEmpty ? [] : [message],
176            contextNote: diff.contextNote,
177            riskAssessment: currentRiskAssessment,
178            insights: currentInsights,
179            riskScoreDelta: riskScoreDelta
180        )
181    }
182
183    static func comparisonContextNote(from oldReport: DomainReport, to newReport: DomainReport) -> String? {
184        var notes: [String] = []
185        if oldReport.resolverURLString != newReport.resolverURLString {
186            notes.append("Compared snapshots used different DNS resolvers.")
187        }
188        if oldReport.resultSource != newReport.resultSource {
189            notes.append("Compared snapshots came from different collection modes.")
190        }
191        return notes.isEmpty ? nil : notes.joined(separator: " ")
192    }
193
194    static func comparisonContextNote(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> String? {
195        comparisonContextNote(
196            from: DomainReportBuilder().build(from: oldSnapshot, deriveChangeSummary: false),
197            to: DomainReportBuilder().build(from: newSnapshot, previousSnapshot: oldSnapshot, deriveChangeSummary: false)
198        )
199    }
200
201    static func certificateWarningLevel(for snapshot: LookupSnapshot) -> CertificateWarningLevel {
202        guard let days = snapshot.sslInfo?.daysUntilExpiry else {
203            return .none
204        }
205        if days < 14 {
206            return .critical
207        }
208        if days < 30 {
209            return .warning
210        }
211        return .none
212    }
213
214    private static func availabilitySection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
215        DiffSection(
216            id: "availability",
217            title: "Domain / Availability",
218            items: [
219                compare(id: "domain", label: "Domain", oldValue: oldReport.domain, newValue: newReport.domain, severity: .low),
220                compare(
221                    id: "availability",
222                    label: "Availability",
223                    oldValue: availabilityLabel(oldReport.availability),
224                    newValue: availabilityLabel(newReport.availability),
225                    severity: .high
226                ),
227                compare(id: "primary-ip", label: "Primary IP", oldValue: oldReport.dns.primaryIP, newValue: newReport.dns.primaryIP, severity: .high),
228                compare(
229                    id: "tls-status",
230                    label: "TLS Status",
231                    oldValue: oldReport.web.tlsStatus,
232                    newValue: newReport.web.tlsStatus,
233                    severity: .medium
234                )
235            ].compactMap { $0 }
236        )
237    }
238
239    private static func ownershipSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
240        DiffSection(
241            id: "ownership",
242            title: "Ownership",
243            items: [
244                compare(id: "registrar", label: "Registrar", oldValue: oldReport.ownership?.registrar, newValue: newReport.ownership?.registrar, severity: .high),
245                compare(id: "registrant", label: "Registrant", oldValue: oldReport.ownership?.registrant, newValue: newReport.ownership?.registrant, severity: .medium),
246                compare(
247                    id: "ownership-created",
248                    label: "Registration Date",
249                    oldValue: ownershipDateLabel(oldReport.ownership?.createdDate),
250                    newValue: ownershipDateLabel(newReport.ownership?.createdDate),
251                    severity: .low
252                ),
253                compare(
254                    id: "ownership-expires",
255                    label: "Expiration Date",
256                    oldValue: ownershipDateLabel(oldReport.ownership?.expirationDate),
257                    newValue: ownershipDateLabel(newReport.ownership?.expirationDate),
258                    severity: .medium
259                ),
260                compare(
261                    id: "ownership-status",
262                    label: "Status",
263                    oldValue: joined(oldReport.ownership?.status),
264                    newValue: joined(newReport.ownership?.status),
265                    severity: .low
266                ),
267                compare(
268                    id: "ownership-nameservers",
269                    label: "Nameservers",
270                    oldValue: joined(oldReport.ownership?.nameservers),
271                    newValue: joined(newReport.ownership?.nameservers),
272                    severity: .medium
273                ),
274                compare(id: "ownership-abuse", label: "Abuse Contact", oldValue: oldReport.ownership?.abuseEmail, newValue: newReport.ownership?.abuseEmail, severity: .low)
275            ].compactMap { $0 }
276        )
277    }
278
279    private static func dnsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
280        let oldSections = Dictionary(uniqueKeysWithValues: oldReport.dns.recordSections.map { ($0.recordType, $0) })
281        let newSections = Dictionary(uniqueKeysWithValues: newReport.dns.recordSections.map { ($0.recordType, $0) })
282        let recordTypes = Set(oldSections.keys).union(newSections.keys).sorted { $0.rawValue < $1.rawValue }
283
284        var items: [DiffItem] = [
285            compare(id: "dnssec", label: "DNSSEC", oldValue: dnssecLabel(oldReport.dns.dnssecSigned), newValue: dnssecLabel(newReport.dns.dnssecSigned), severity: .medium),
286            compare(id: "ptr", label: "PTR", oldValue: oldReport.dns.ptrRecord, newValue: newReport.dns.ptrRecord, severity: .low)
287        ].compactMap { $0 }
288
289        for type in recordTypes {
290            items.append(
291                compare(
292                    id: "dns-\(type.rawValue.lowercased())-records",
293                    label: "\(type.rawValue) Records",
294                    oldValue: normalizedRecordValues(for: oldSections[type]),
295                    newValue: normalizedRecordValues(for: newSections[type]),
296                    severity: type == .A || type == .NS ? .high : .medium
297                ) ?? DiffItem(id: "", label: "", changeType: .unchanged, oldValue: nil, newValue: nil, severity: .low)
298            )
299            if let ttlChange = compare(
300                id: "dns-\(type.rawValue.lowercased())-ttl",
301                label: "\(type.rawValue) TTL",
302                oldValue: normalizedTTLValues(for: oldSections[type]),
303                newValue: normalizedTTLValues(for: newSections[type]),
304                severity: .low
305            ) {
306                items.append(ttlChange)
307            }
308        }
309
310        return DiffSection(
311            id: "dns",
312            title: "DNS",
313            items: items.filter { !$0.id.isEmpty }
314        )
315    }
316
317    private static func webSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
318        DiffSection(
319            id: "web",
320            title: "Web",
321            items: [
322                compare(id: "web-status", label: "HTTP Status", oldValue: oldReport.web.statusCode.map(String.init), newValue: newReport.web.statusCode.map(String.init), severity: .medium),
323                compare(id: "web-grade", label: "Security Grade", oldValue: oldReport.web.securityGrade, newValue: newReport.web.securityGrade, severity: .medium),
324                compare(id: "web-final-url", label: "Final URL", oldValue: oldReport.web.finalURL, newValue: newReport.web.finalURL, severity: .high),
325                compare(id: "web-tls-issuer", label: "TLS Issuer", oldValue: oldReport.web.tls?.issuer, newValue: newReport.web.tls?.issuer, severity: .medium),
326                compare(id: "web-tls-expiry", label: "TLS Expiration", oldValue: expirationLabel(oldReport.web.tls), newValue: expirationLabel(newReport.web.tls), severity: .medium),
327                compare(id: "web-headers", label: "Headers", oldValue: normalizedHeaders(oldReport.web.headers), newValue: normalizedHeaders(newReport.web.headers), severity: .low),
328                compare(id: "web-redirects", label: "Redirect Chain", oldValue: redirectChainSummary(oldReport.web.redirectChain), newValue: redirectChainSummary(newReport.web.redirectChain), severity: .medium)
329            ].compactMap { $0 }
330        )
331    }
332
333    private static func emailSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
334        DiffSection(
335            id: "email",
336            title: "Email Security",
337            items: [
338                compare(id: "email-summary", label: "Summary", oldValue: oldReport.email.summary, newValue: newReport.email.summary, severity: .medium),
339                compare(id: "email-grade", label: "Grade", oldValue: oldReport.email.grade?.rawValue, newValue: newReport.email.grade?.rawValue, severity: .medium),
340                compare(id: "email-spf", label: "SPF", oldValue: recordLabel(oldReport.email.records?.spf), newValue: recordLabel(newReport.email.records?.spf), severity: .medium),
341                compare(id: "email-dmarc", label: "DMARC", oldValue: recordLabel(oldReport.email.records?.dmarc), newValue: recordLabel(newReport.email.records?.dmarc), severity: .high),
342                compare(id: "email-dkim", label: "DKIM", oldValue: recordLabel(oldReport.email.records?.dkim), newValue: recordLabel(newReport.email.records?.dkim), severity: .medium),
343                compare(id: "email-bimi", label: "BIMI", oldValue: recordLabel(oldReport.email.records?.bimi), newValue: recordLabel(newReport.email.records?.bimi), severity: .low),
344                compare(id: "email-mta-sts", label: "MTA-STS", oldValue: mtaStsLabel(oldReport.email.records?.mtaSts), newValue: mtaStsLabel(newReport.email.records?.mtaSts), severity: .medium)
345            ].compactMap { $0 }
346        )
347    }
348
349    private static func networkSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
350        DiffSection(
351            id: "network",
352            title: "Network",
353            items: [
354                compare(id: "network-reachability", label: "Reachability", oldValue: oldReport.network.reachabilitySummary, newValue: newReport.network.reachabilitySummary, severity: .medium),
355                compare(id: "network-geolocation", label: "Geolocation", oldValue: oldReport.network.geolocationSummary, newValue: newReport.network.geolocationSummary, severity: .medium),
356                compare(id: "network-open-ports", label: "Open Ports", oldValue: joined(oldReport.network.openPorts.map(String.init)), newValue: joined(newReport.network.openPorts.map(String.init)), severity: .high),
357                compare(id: "network-port-scan", label: "Port Scan", oldValue: portScanSummary(oldReport.network.portScan), newValue: portScanSummary(newReport.network.portScan), severity: .medium)
358            ].compactMap { $0 }
359        )
360    }
361
362    private static func subdomainsSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
363        DiffSection(
364            id: "subdomains",
365            title: "Subdomains",
366            items: [
367                compare(id: "subdomains-primary", label: "Primary Subdomains", oldValue: joined(oldReport.subdomains), newValue: joined(newReport.subdomains), severity: .low),
368                compare(id: "subdomains-extended", label: "Extended Subdomains", oldValue: joined(oldReport.extendedSubdomains), newValue: joined(newReport.extendedSubdomains), severity: .low),
369                compare(id: "subdomains-groups", label: "Groups", oldValue: groupSummary(oldReport.subdomainGroups), newValue: groupSummary(newReport.subdomainGroups), severity: .low)
370            ].compactMap { $0 }
371        )
372    }
373
374    private static func riskSection(from oldReport: DomainReport, to newReport: DomainReport) -> DiffSection {
375        DiffSection(
376            id: "risk",
377            title: "Risk / Insights",
378            items: [
379                compare(id: "risk-score", label: "Risk Score", oldValue: "\(oldReport.riskAssessment.score)", newValue: "\(newReport.riskAssessment.score)", severity: .high),
380                compare(id: "risk-level", label: "Risk Level", oldValue: oldReport.riskAssessment.level.title, newValue: newReport.riskAssessment.level.title, severity: .high),
381                compare(id: "risk-factors", label: "Risk Factors", oldValue: joined(oldReport.riskAssessment.factors.map(\.description)), newValue: joined(newReport.riskAssessment.factors.map(\.description)), severity: .medium),
382                compare(id: "risk-insights", label: "Insights", oldValue: joined(oldReport.insights), newValue: joined(newReport.insights), severity: .medium)
383            ].compactMap { $0 }
384        )
385    }
386
387    private static func compare(
388        id: String,
389        label: String,
390        oldValue: String?,
391        newValue: String?,
392        severity: ChangeSeverity
393    ) -> DiffItem? {
394        let oldValue = normalized(oldValue)
395        let newValue = normalized(newValue)
396
397        guard oldValue != nil || newValue != nil else {
398            return nil
399        }
400
401        let changeType: DiffChangeType
402        switch (oldValue?.lowercased(), newValue?.lowercased()) {
403        case let (old?, new?) where old == new:
404            changeType = .unchanged
405        case (nil, _?):
406            changeType = .added
407        case (_?, nil):
408            changeType = .removed
409        default:
410            changeType = .changed
411        }
412
413        return DiffItem(
414            id: id,
415            label: label,
416            changeType: changeType,
417            oldValue: oldValue,
418            newValue: newValue,
419            severity: severity
420        )
421    }
422
423    static func summaryMessage(from sectionTitles: [String], changeCount: Int) -> String {
424        guard !sectionTitles.isEmpty else {
425            return "No meaningful changes"
426        }
427        if sectionTitles.count == 1 {
428            return "\(sectionTitles[0]) changed"
429        }
430        return "\(sectionTitles[0]) and \(sectionTitles[1].lowercased()) changed (\(changeCount) items)"
431    }
432
433    private static func normalized(_ value: String?) -> String? {
434        guard let value = value?.trimmingCharacters(in: .whitespacesAndNewlines), !value.isEmpty else {
435            return nil
436        }
437        return value
438    }
439
440    private static func availabilityLabel(_ status: DomainAvailabilityStatus) -> String {
441        switch status {
442        case .available:
443            return "Available"
444        case .registered:
445            return "Registered"
446        case .unknown:
447            return "Unknown"
448        }
449    }
450
451    private static func ownershipDateLabel(_ date: Date?) -> String? {
452        date?.formatted(date: .abbreviated, time: .omitted)
453    }
454
455    private static func expirationLabel(_ certificate: SSLCertificateInfo?) -> String? {
456        guard let certificate else { return nil }
457        return "\(certificate.validUntil.formatted(date: .abbreviated, time: .omitted)) (\(certificate.daysUntilExpiry)d)"
458    }
459
460    private static func joined(_ values: [String]?) -> String? {
461        guard let values else { return nil }
462        let normalizedValues = values
463            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
464            .filter { !$0.isEmpty }
465            .sorted()
466        return normalizedValues.isEmpty ? nil : normalizedValues.joined(separator: ", ")
467    }
468
469    private static func normalizedRecordValues(for section: DNSSection?) -> String? {
470        guard let section else { return nil }
471        let values = (section.records + section.wildcardRecords)
472            .map(\.value)
473            .map { $0.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() }
474            .sorted()
475        return values.isEmpty ? nil : values.joined(separator: ", ")
476    }
477
478    private static func normalizedTTLValues(for section: DNSSection?) -> String? {
479        guard let section else { return nil }
480        let values = (section.records + section.wildcardRecords)
481            .map { "\($0.value.lowercased()):\($0.ttl)" }
482            .sorted()
483        return values.isEmpty ? nil : values.joined(separator: ", ")
484    }
485
486    private static func normalizedHeaders(_ headers: [HTTPHeader]) -> String? {
487        let values = headers
488            .map { "\($0.name.lowercased()): \($0.value.trimmingCharacters(in: .whitespacesAndNewlines))" }
489            .sorted()
490        return values.isEmpty ? nil : values.joined(separator: " | ")
491    }
492
493    private static func redirectChainSummary(_ redirects: [RedirectHop]) -> String? {
494        let values = redirects.map { "\($0.statusCode) \($0.url)" }
495        return values.isEmpty ? nil : values.joined(separator: " -> ")
496    }
497
498    private static func portScanSummary(_ results: [PortScanResult]) -> String? {
499        let values = results
500            .sorted { $0.port < $1.port }
501            .map { "\($0.port):\($0.open ? "open" : "closed")" }
502        return values.isEmpty ? nil : values.joined(separator: ", ")
503    }
504
505    private static func groupSummary(_ groups: [SubdomainGroup]) -> String? {
506        joined(groups.map { "\($0.label): \($0.subdomains.count)" })
507    }
508
509    private static func recordLabel(_ record: EmailSecurityRecord?) -> String? {
510        guard let record else { return nil }
511        if record.found {
512            return record.value ?? "Present"
513        }
514        return "Missing"
515    }
516
517    private static func mtaStsLabel(_ result: MTASTSResult?) -> String? {
518        guard let result else { return nil }
519        guard result.txtFound else { return "Missing" }
520        return result.policyMode ?? "Present"
521    }
522
523    private static func dnssecLabel(_ value: Bool?) -> String? {
524        switch value {
525        case true:
526            return "Signed"
527        case false:
528            return "Unsigned"
529        case nil:
530            return nil
531        }
532    }
533}
534
535enum DomainDiffService {
536    static func diff(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> [DomainDiffSection] {
537        DiffService.compare(from: oldSnapshot, to: newSnapshot).sections
538    }
539
540    static func summary(
541        from oldSnapshot: LookupSnapshot,
542        to newSnapshot: LookupSnapshot,
543        generatedAt: Date = Date(),
544        riskAssessment: DomainRiskAssessment? = nil,
545        insights: [String]? = nil
546    ) -> DomainChangeSummary {
547        DiffService.summary(
548            from: oldSnapshot,
549            to: newSnapshot,
550            generatedAt: generatedAt,
551            riskAssessment: riskAssessment,
552            insights: insights
553        )
554    }
555
556    static func comparisonContextNote(from oldSnapshot: LookupSnapshot, to newSnapshot: LookupSnapshot) -> String? {
557        DiffService.comparisonContextNote(from: oldSnapshot, to: newSnapshot)
558    }
559
560    static func certificateWarningLevel(for snapshot: LookupSnapshot) -> CertificateWarningLevel {
561        DiffService.certificateWarningLevel(for: snapshot)
562    }
563}