DomainInspectionService.swift
402 lines · 18409 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(domain: String, previousSnapshot: LookupSnapshot? = nil) async -> DomainReport {
12 let snapshot = await inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
13 return reportBuilder.build(from: snapshot)
14 }
15
16 func inspectSnapshot(domain: String, previousSnapshot: LookupSnapshot? = nil) async -> LookupSnapshot {
17 let normalizedDomain = normalize(domain)
18 let startedAt = Date()
19 let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
20 let resolverURLString = DNSLookupService.currentResolverURLString()
21 var cachedSections = Set<LookupSectionKind>()
22 var sectionSources: [LookupResultSource] = []
23
24 async let dnsFetch = runtime.dns(domain: normalizedDomain)
25 async let availabilityFetch = runtime.availability(domain: normalizedDomain)
26 async let sslFetch = runtime.ssl(domain: normalizedDomain)
27 async let hstsFetch = runtime.hsts(domain: normalizedDomain)
28 async let httpFetch = runtime.http(domain: normalizedDomain)
29 async let reachabilityFetch = runtime.reachability(domain: normalizedDomain)
30 async let ownershipFetch = runtime.ownership(domain: normalizedDomain)
31 async let redirectFetch = runtime.redirectChain(domain: normalizedDomain)
32 async let subdomainFetch = runtime.subdomains(domain: normalizedDomain)
33 async let portScanFetch = runtime.portScan(domain: normalizedDomain)
34
35 let resolvedDNS = await dnsFetch
36 let dnsResult = normalizeErrors(in: resolvedDNS.value)
37 track(.dns, source: resolvedDNS.source, cachedSections: &cachedSections, sectionSources: §ionSources)
38
39 let availability = await availabilityFetch
40 track(.availability, source: availability.source, cachedSections: &cachedSections, sectionSources: §ionSources)
41
42 let resolvedSSL = await sslFetch
43 let sslResult = normalizeErrors(in: resolvedSSL.value)
44 track(.ssl, source: resolvedSSL.source, cachedSections: &cachedSections, sectionSources: §ionSources)
45
46 let hsts = await hstsFetch
47 track(.hsts, source: hsts.source, cachedSections: &cachedSections, sectionSources: §ionSources)
48
49 let http = await httpFetch
50 let httpResult = normalizeErrors(in: http.value)
51 track(.httpHeaders, source: http.source, cachedSections: &cachedSections, sectionSources: §ionSources)
52
53 let reachability = await reachabilityFetch
54 let reachabilityResult = normalizeErrors(in: reachability.value)
55 track(.reachability, source: reachability.source, cachedSections: &cachedSections, sectionSources: §ionSources)
56
57 let resolvedOwnership = await ownershipFetch
58 let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
59 track(.ownership, source: resolvedOwnership.source, cachedSections: &cachedSections, sectionSources: §ionSources)
60
61 let redirects = await redirectFetch
62 let redirectResult = normalizeErrors(in: redirects.value)
63 track(.redirectChain, source: redirects.source, cachedSections: &cachedSections, sectionSources: §ionSources)
64
65 let resolvedSubdomains = await subdomainFetch
66 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
67 track(.subdomains, source: resolvedSubdomains.source, cachedSections: &cachedSections, sectionSources: §ionSources)
68
69 let ports = await portScanFetch
70 let portScanResult = normalizeErrors(in: ports.value)
71 track(.portScan, source: ports.source, cachedSections: &cachedSections, sectionSources: §ionSources)
72
73 let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
74 let sslInfo = mapOptionalValueServiceResult(sslResult)
75 let httpHeadersResult = mapHTTPResult(httpResult)
76 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
77 let redirectChain = mapServiceResult(redirectResult, emptyValue: [])
78 let ownership = mapOptionalValueServiceResult(ownershipResult)
79 let subdomains = mapServiceResult(subdomainResult, emptyValue: [])
80 let portScanResults = await mapPortScanResult(portScanResult, domain: normalizedDomain)
81
82 let txtRecords = dnsSections.value.first(where: { $0.recordType == .TXT })?.records ?? []
83 let primaryIP = dnsSections.value.first(where: { $0.recordType == .A })?.records.first?.value
84 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
85 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
86
87 let emailOutcome: CachedLookupResult<ServiceResult<EmailSecurityResult>>
88 if canReuseDNSDependents, let previousSnapshot, let emailSecurity = previousSnapshot.emailSecurity {
89 emailOutcome = CachedLookupResult(value: .success(emailSecurity), source: .cached)
90 } else if canReuseDNSDependents, let previousSnapshot, let error = previousSnapshot.emailSecurityError {
91 emailOutcome = CachedLookupResult(value: .error(error), source: .cached)
92 } else {
93 emailOutcome = await runtime.email(domain: normalizedDomain, txtRecords: txtRecords)
94 }
95 track(.emailSecurity, source: emailOutcome.source, cachedSections: &cachedSections, sectionSources: §ionSources)
96
97 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
98 if availability.value.status == .registered {
99 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
100 track(.suggestions, source: suggestionsOutcome.source, cachedSections: &cachedSections, sectionSources: §ionSources)
101 } else {
102 suggestionsOutcome = CachedLookupResult(value: [], source: .live)
103 }
104
105 let ptrOutcome: CachedLookupResult<ServiceResult<String>>?
106 let geoOutcome: CachedLookupResult<ServiceResult<IPGeolocation>>?
107 if let primaryIP {
108 if canReuseIPDependents, let previousSnapshot, let ptrRecord = previousSnapshot.ptrRecord {
109 ptrOutcome = CachedLookupResult(value: .success(ptrRecord), source: .cached)
110 } else if canReuseIPDependents, let previousSnapshot, let ptrError = previousSnapshot.ptrError {
111 ptrOutcome = CachedLookupResult(value: .error(ptrError), source: .cached)
112 } else {
113 ptrOutcome = await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
114 }
115
116 if canReuseIPDependents, let previousSnapshot, let ipGeolocation = previousSnapshot.ipGeolocation {
117 geoOutcome = CachedLookupResult(value: .success(ipGeolocation), source: .cached)
118 } else if canReuseIPDependents, let previousSnapshot, let ipGeolocationError = previousSnapshot.ipGeolocationError {
119 geoOutcome = CachedLookupResult(value: .error(ipGeolocationError), source: .cached)
120 } else {
121 geoOutcome = await runtime.ipGeolocation(ip: primaryIP)
122 }
123
124 if let ptrOutcome {
125 track(.ptr, source: ptrOutcome.source, cachedSections: &cachedSections, sectionSources: §ionSources)
126 }
127 if let geoOutcome {
128 track(.ipGeolocation, source: geoOutcome.source, cachedSections: &cachedSections, sectionSources: §ionSources)
129 }
130 } else {
131 ptrOutcome = nil
132 geoOutcome = nil
133 }
134
135 let emailSecurity = mapOptionalValueServiceResult(normalizeErrors(in: emailOutcome.value))
136 let ptrRecord = mapOptionalServiceResult(ptrOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
137 let geolocation = mapOptionalServiceResult(geoOutcome.map { normalizeErrors(in: $0.value) }, missingMessage: "No A record available")
138
139 return LookupSnapshot(
140 historyEntryID: nil,
141 domain: availability.value.domain,
142 timestamp: Date(),
143 trackedDomainID: previousSnapshot?.trackedDomainID,
144 resolverDisplayName: resolverDisplayName,
145 resolverURLString: resolverURLString,
146 totalLookupDurationMs: Int(Date().timeIntervalSince(startedAt) * 1000),
147 dnsSections: dnsSections.value,
148 dnsError: dnsSections.message,
149 availabilityResult: availability.value,
150 suggestions: suggestionsOutcome.value,
151 sslInfo: sslInfo.value,
152 sslError: sslInfo.message,
153 hstsPreloaded: hsts.value,
154 httpHeaders: httpHeadersResult.headers,
155 httpSecurityGrade: httpHeadersResult.securityGrade,
156 httpStatusCode: httpHeadersResult.statusCode,
157 httpResponseTimeMs: httpHeadersResult.responseTimeMs,
158 httpProtocol: httpHeadersResult.httpProtocol,
159 http3Advertised: httpHeadersResult.http3Advertised,
160 httpHeadersError: httpHeadersResult.error,
161 reachabilityResults: reachabilityResultValue.value,
162 reachabilityError: reachabilityResultValue.message,
163 ipGeolocation: geolocation.value,
164 ipGeolocationError: geolocation.message,
165 emailSecurity: emailSecurity.value,
166 emailSecurityError: emailSecurity.message,
167 ownership: ownership.value,
168 ownershipError: ownership.message,
169 ptrRecord: ptrRecord.value,
170 ptrError: ptrRecord.message,
171 redirectChain: redirectChain.value,
172 redirectChainError: redirectChain.message,
173 subdomains: subdomains.value,
174 subdomainsError: subdomains.message,
175 portScanResults: portScanResults.value,
176 portScanError: portScanResults.message,
177 changeSummary: nil,
178 resultSource: aggregateSource(sectionSources),
179 cachedSections: Array(cachedSections).sorted { $0.rawValue < $1.rawValue },
180 statusMessage: nil
181 )
182 }
183
184 private func normalize(_ domain: String) -> String {
185 domain
186 .trimmingCharacters(in: .whitespacesAndNewlines)
187 .replacingOccurrences(of: "https://", with: "")
188 .replacingOccurrences(of: "http://", with: "")
189 .components(separatedBy: "/").first?
190 .lowercased() ?? domain.lowercased()
191 }
192
193 private func track(
194 _ section: LookupSectionKind,
195 source: LookupResultSource,
196 cachedSections: inout Set<LookupSectionKind>,
197 sectionSources: inout [LookupResultSource]
198 ) {
199 sectionSources.append(source)
200 if source != .live {
201 cachedSections.insert(section)
202 }
203 }
204
205 private func aggregateSource(_ sectionSources: [LookupResultSource]) -> LookupResultSource {
206 let normalizedSources = sectionSources.map { source -> LookupResultSource in
207 source == .mixed ? .cached : source
208 }
209
210 let hasLive = normalizedSources.contains(.live)
211 let hasCached = normalizedSources.contains(.cached)
212
213 switch (hasLive, hasCached) {
214 case (true, true):
215 return .mixed
216 case (false, true):
217 return .cached
218 default:
219 return .live
220 }
221 }
222
223 private func canReuseDependentSections(from previousSnapshot: LookupSnapshot?, dnsSections: [DNSSection]) -> Bool {
224 guard let previousSnapshot else { return false }
225 return dnsSignature(for: previousSnapshot.dnsSections) == dnsSignature(for: dnsSections)
226 }
227
228 private func canReuseIPBasedSections(from previousSnapshot: LookupSnapshot?, primaryIP: String?) -> Bool {
229 guard let previousSnapshot else { return false }
230 let previousIP = previousSnapshot.dnsSections.first(where: { $0.recordType == .A })?.records.first?.value
231 return primaryIP == previousIP
232 }
233
234 private func dnsSignature(for sections: [DNSSection]) -> String {
235 sections
236 .sorted { $0.recordType.rawValue < $1.recordType.rawValue }
237 .map { section in
238 let records = section.records
239 .sorted { $0.value < $1.value }
240 .map { "\($0.value)|\($0.ttl)" }
241 .joined(separator: ",")
242 let wildcardRecords = section.wildcardRecords
243 .sorted { $0.value < $1.value }
244 .map { "\($0.value)|\($0.ttl)" }
245 .joined(separator: ",")
246 return [
247 section.recordType.rawValue,
248 records,
249 wildcardRecords,
250 section.dnssecSigned.map { $0 ? "signed" : "unsigned" } ?? "unknown",
251 section.error ?? ""
252 ].joined(separator: "#")
253 }
254 .joined(separator: "||")
255 }
256
257 private func normalizeErrors<Value>(in result: ServiceResult<Value>) -> ServiceResult<Value> {
258 switch result {
259 case let .success(value):
260 return .success(value)
261 case let .empty(message):
262 return .empty(message)
263 case let .error(message):
264 return .error(classifiedMessage(from: message))
265 }
266 }
267
268 private func classifiedMessage(from message: String) -> String {
269 let normalizedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
270 let lowercasedMessage = normalizedMessage.lowercased()
271
272 if lowercasedMessage.hasPrefix("network error:")
273 || lowercasedMessage.hasPrefix("timeout:")
274 || lowercasedMessage.hasPrefix("rate limit:")
275 || lowercasedMessage.hasPrefix("parsing error:") {
276 return normalizedMessage
277 }
278
279 if lowercasedMessage.contains("timed out") {
280 return "Timeout: Request timed out"
281 }
282 if lowercasedMessage.contains("429")
283 || lowercasedMessage.contains("too many requests")
284 || lowercasedMessage.contains("rate limit") {
285 return "Rate limit: Try again shortly"
286 }
287 if lowercasedMessage.contains("cannot parse")
288 || lowercasedMessage.contains("decoding")
289 || lowercasedMessage.contains("json") {
290 return "Parsing error: Invalid server response"
291 }
292 if lowercasedMessage.contains("offline")
293 || lowercasedMessage.contains("internet connection")
294 || lowercasedMessage.contains("not connected")
295 || lowercasedMessage.contains("network connection") {
296 return "Network error: Offline"
297 }
298
299 return "Network error: \(normalizedMessage)"
300 }
301
302 private func mapServiceResult<Value>(_ result: ServiceResult<Value>, emptyValue: Value) -> (value: Value, message: String?) {
303 switch result {
304 case let .success(value):
305 return (value, nil)
306 case let .empty(message), let .error(message):
307 return (emptyValue, message)
308 }
309 }
310
311 private func mapOptionalValueServiceResult<Value>(_ result: ServiceResult<Value>) -> (value: Value?, message: String?) {
312 switch result {
313 case let .success(value):
314 return (value, nil)
315 case let .empty(message), let .error(message):
316 return (nil, message)
317 }
318 }
319
320 private func mapOptionalServiceResult<Value>(
321 _ result: ServiceResult<Value>?,
322 missingMessage: String
323 ) -> (value: Value?, message: String?) {
324 guard let result else {
325 return (nil, missingMessage)
326 }
327
328 switch result {
329 case let .success(value):
330 return (value, nil)
331 case let .empty(message), let .error(message):
332 return (nil, message)
333 }
334 }
335
336 private func mapPortScanResult(_ result: ServiceResult<[PortScanResult]>, domain: String) async -> (value: [PortScanResult], message: String?) {
337 switch result {
338 case let .success(results):
339 return (await enrichOpenPortBanners(in: results, domain: domain), nil)
340 case let .empty(message), let .error(message):
341 return ([], message)
342 }
343 }
344
345 private func mapHTTPResult(_ result: ServiceResult<HTTPHeadersResult>) -> (
346 headers: [HTTPHeader],
347 securityGrade: String?,
348 statusCode: Int?,
349 responseTimeMs: Int?,
350 httpProtocol: String?,
351 http3Advertised: Bool,
352 error: String?
353 ) {
354 switch result {
355 case let .success(value):
356 return (
357 headers: value.headers,
358 securityGrade: HTTPSecurityGrade.grade(for: value.headers).rawValue,
359 statusCode: value.statusCode,
360 responseTimeMs: value.responseTimeMs,
361 httpProtocol: value.httpProtocol,
362 http3Advertised: value.http3Advertised,
363 error: nil
364 )
365 case let .empty(message), let .error(message):
366 return (
367 headers: [],
368 securityGrade: nil,
369 statusCode: nil,
370 responseTimeMs: nil,
371 httpProtocol: nil,
372 http3Advertised: false,
373 error: message
374 )
375 }
376 }
377
378 private func enrichOpenPortBanners(in results: [PortScanResult], domain: String) async -> [PortScanResult] {
379 let banners = await withTaskGroup(of: (UInt16, String?).self, returning: [UInt16: String].self) { group in
380 for result in results where result.open {
381 group.addTask {
382 let banner = await PortScanService.grabBanner(host: domain, port: result.port)
383 return (result.port, banner)
384 }
385 }
386
387 var collected: [UInt16: String] = [:]
388 for await (port, banner) in group {
389 if let banner {
390 collected[port] = banner
391 }
392 }
393 return collected
394 }
395
396 return results.map { result in
397 var updated = result
398 updated.banner = banners[result.port]
399 return updated
400 }
401 }
402}