Commit 86b2b1a65e
Unsigned
Layout: unified · split
Docs/local-api.txt +14
| @@ -78,6 +78,19 @@ Every response — success or error — is wrapped in the same envelope: | |||
| 78 | 78 | ||
| 79 | `certificateWarningLevel` encodes as `"none"`, `"warning"`, or `"critical"`. | 79 | `certificateWarningLevel` encodes as `"none"`, `"warning"`, or `"critical"`. |
| 80 | 80 | ||
| 81 | Both `/inspect` routes accept an optional `profile` query parameter, `full` or | ||
| 82 | `quick`. It defaults to `full`, so a caller that omits it gets every section as | ||
| 83 | before. `quick` runs DNS, registration, ownership, TLS, HSTS, HTTP, redirects | ||
| 84 | and PTR, and leaves out reachability, port scanning, subdomain discovery, IP | ||
| 85 | geolocation and name suggestions; each omitted section carries a message saying | ||
| 86 | it was not run. | ||
| 87 | |||
| 88 | When the device owner has turned off third-party enrichment in Settings, both | ||
| 89 | routes follow that setting and a request cannot override it: ownership, | ||
| 90 | subdomain discovery, IP geolocation and name suggestions are not collected, and | ||
| 91 | registration is decided from DNS alone, which reports `registered` or | ||
| 92 | `unknown` but never `available`. | ||
| 93 | |||
| 81 | `DomainReport` is the app's canonical report model (the same shape the JSON | 94 | `DomainReport` is the app's canonical report model (the same shape the JSON |
| 82 | export produces); see `DomainReportBuilder.swift` for its fields. It is a large | 95 | export produces); see `DomainReportBuilder.swift` for its fields. It is a large |
| 83 | object and is treated as an additive contract: new fields may appear without a | 96 | object and is treated as an additive contract: new fields may appear without a |
| @@ -90,6 +103,7 @@ version bump. | |||
| 90 | | 400 | `bad_request` | The HTTP request line/path could not be parsed | | 103 | | 400 | `bad_request` | The HTTP request line/path could not be parsed | |
| 91 | | 400 | `invalid_body` | `POST /inspect` body was not `{ "domain": "…" }` | | 104 | | 400 | `invalid_body` | `POST /inspect` body was not `{ "domain": "…" }` | |
| 92 | | 400 | `invalid_domain` | A path/body domain was empty or invalid | | 105 | | 400 | `invalid_domain` | A path/body domain was empty or invalid | |
| 106 | | 400 | `invalid_profile` | `profile` was present but named no known profile | | ||
| 93 | | 401 | `unauthorized` | Missing or incorrect token | | 107 | | 401 | `unauthorized` | Missing or incorrect token | |
| 94 | | 404 | `not_found` | No such route | | 108 | | 404 | `not_found` | No such route | |
| 95 | | 404 | `domain_not_found` | No local data / tracked domain for the given name | | 109 | | 404 | `domain_not_found` | No local data / tracked domain for the given name | |
DomainDig.xcodeproj/project.pbxproj +4
| @@ -36,6 +36,7 @@ | |||
| 36 | A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001201 /* HistoryStoreTests.swift */; }; | 36 | A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001201 /* HistoryStoreTests.swift */; }; |
| 37 | A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001401 /* SectionStateTests.swift */; }; | 37 | A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001401 /* SectionStateTests.swift */; }; |
| 38 | A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */; }; | 38 | A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */; }; |
| 39 | A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001601 /* InspectionScopeTests.swift */; }; | ||
| 39 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; | 40 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; |
| 40 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; | 41 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; |
| 41 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; | 42 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; }; |
| @@ -119,6 +120,7 @@ | |||
| 119 | A1B2C3D40000000000001201 /* HistoryStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryStoreTests.swift; sourceTree = "<group>"; }; | 120 | A1B2C3D40000000000001201 /* HistoryStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryStoreTests.swift; sourceTree = "<group>"; }; |
| 120 | A1B2C3D40000000000001401 /* SectionStateTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SectionStateTests.swift; sourceTree = "<group>"; }; | 121 | A1B2C3D40000000000001401 /* SectionStateTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SectionStateTests.swift; sourceTree = "<group>"; }; |
| 121 | A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PortfolioDashboardTests.swift; sourceTree = "<group>"; }; | 122 | A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = PortfolioDashboardTests.swift; sourceTree = "<group>"; }; |
| 123 | A1B2C3D40000000000001601 /* InspectionScopeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionScopeTests.swift; sourceTree = "<group>"; }; | ||
| 122 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; | 124 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; |
| 123 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; | 125 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; |
| 124 | A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; | 126 | A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; }; |
| @@ -267,6 +269,7 @@ | |||
| 267 | A1B2C3D40000000000001201 /* HistoryStoreTests.swift */, | 269 | A1B2C3D40000000000001201 /* HistoryStoreTests.swift */, |
| 268 | A1B2C3D40000000000001401 /* SectionStateTests.swift */, | 270 | A1B2C3D40000000000001401 /* SectionStateTests.swift */, |
| 269 | A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */, | 271 | A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */, |
| 272 | A1B2C3D40000000000001601 /* InspectionScopeTests.swift */, | ||
| 270 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */, | 273 | A1B2C3D40000000000000301 /* AvailabilityTests.swift */, |
| 271 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, | 274 | A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, |
| 272 | A1B2C3D40000000000000501 /* DomainNameTests.swift */, | 275 | A1B2C3D40000000000000501 /* DomainNameTests.swift */, |
| @@ -540,6 +543,7 @@ | |||
| 540 | A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */, | 543 | A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */, |
| 541 | A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */, | 544 | A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */, |
| 542 | A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */, | 545 | A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */, |
| 546 | A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */, | ||
| 543 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, | 547 | A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, |
| 544 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, | 548 | A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, |
| 545 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, | 549 | A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */, |
DomainDig/DomainAvailabilityService.swift +5 −1
| @@ -5,6 +5,7 @@ struct DomainAvailabilityService { | |||
| 5 | 5 | ||
| 6 | static func check( | 6 | static func check( |
| 7 | domain: String, | 7 | domain: String, |
| 8 | allowsRDAP: Bool = true, | ||
| 8 | rdapTransport: RDAPTransport = URLSessionRDAPTransport(), | 9 | rdapTransport: RDAPTransport = URLSessionRDAPTransport(), |
| 9 | dns: DNSLookup = DNSLookupService() | 10 | dns: DNSLookup = DNSLookupService() |
| 10 | ) async -> DomainAvailabilityResult { | 11 | ) async -> DomainAvailabilityResult { |
| @@ -14,7 +15,10 @@ struct DomainAvailabilityService { | |||
| 14 | } | 15 | } |
| 15 | 16 | ||
| 16 | // RDAP is the registry's own record, so it settles both directions. | 17 | // RDAP is the registry's own record, so it settles both directions. |
| 17 | if let registryStatus = await checkViaRDAP(domain: normalizedDomain, transport: rdapTransport) { | 18 | // Declining it leaves only the fallback below, which is why availability |
| 19 | // then reports `.unknown` rather than `.available`. | ||
| 20 | if allowsRDAP, | ||
| 21 | let registryStatus = await checkViaRDAP(domain: normalizedDomain, transport: rdapTransport) { | ||
| 18 | return DomainAvailabilityResult(domain: normalizedDomain, status: registryStatus) | 22 | return DomainAvailabilityResult(domain: normalizedDomain, status: registryStatus) |
| 19 | } | 23 | } |
| 20 | 24 | ||
DomainDig/DomainDigIntents.swift +4 −1
| @@ -35,7 +35,10 @@ struct InspectDomainIntent: AppIntent { | |||
| 35 | throw InspectDomainError.emptyDomain | 35 | throw InspectDomainError.emptyDomain |
| 36 | } | 36 | } |
| 37 | 37 | ||
| 38 | let snapshot = await DomainInspectionService().inspectSnapshot(domain: requested) | 38 | let snapshot = await DomainInspectionService().inspectSnapshot( |
| 39 | domain: requested, | ||
| 40 | scope: .current() | ||
| 41 | ) | ||
| 39 | let report = DomainReportBuilder().build(from: snapshot) | 42 | let report = DomainReportBuilder().build(from: snapshot) |
| 40 | 43 | ||
| 41 | let summary = Self.summaryText(for: report) | 44 | let summary = Self.summaryText(for: report) |
DomainDig/DomainMonitoringService.swift +5 −1
| @@ -326,6 +326,9 @@ final class DomainMonitoringService { | |||
| 326 | } else { | 326 | } else { |
| 327 | notificationsAuthorized = false | 327 | notificationsAuthorized = false |
| 328 | } | 328 | } |
| 329 | // Monitoring inspects on the user's behalf, so it runs with the profile | ||
| 330 | // and the enrichment choice they set for their own lookups. | ||
| 331 | let monitoringScope = InspectionScope.current() | ||
| 329 | var results: [MonitoringDomainResult] = [] | 332 | var results: [MonitoringDomainResult] = [] |
| 330 | var errors: [String] = [] | 333 | var errors: [String] = [] |
| 331 | var alertsTriggered = 0 | 334 | var alertsTriggered = 0 |
| @@ -339,7 +342,8 @@ final class DomainMonitoringService { | |||
| 339 | let previousSnapshot = latestSnapshot(for: trackedDomain, history: history) | 342 | let previousSnapshot = latestSnapshot(for: trackedDomain, history: history) |
| 340 | let inspectedSnapshot = await inspectionService.inspectSnapshot( | 343 | let inspectedSnapshot = await inspectionService.inspectSnapshot( |
| 341 | domain: trackedDomain.domain, | 344 | domain: trackedDomain.domain, |
| 342 | previousSnapshot: previousSnapshot | 345 | previousSnapshot: previousSnapshot, |
| 346 | scope: monitoringScope | ||
| 343 | ) | 347 | ) |
| 344 | let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot) | 348 | let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot) |
| 345 | // When the fallback fires, `snapshot` *is* `previousSnapshot`, so | 349 | // When the fallback fires, `snapshot` *is* `previousSnapshot`, so |
DomainDig/DomainViewModel.swift +18 −6
| @@ -1325,7 +1325,11 @@ final class DomainViewModel { | |||
| 1325 | } | 1325 | } |
| 1326 | 1326 | ||
| 1327 | let previous = historyEntries(for: normalizedDomain).first?.snapshot | 1327 | let previous = historyEntries(for: normalizedDomain).first?.snapshot |
| 1328 | let snapshot = await inspectionService.inspectSnapshot(domain: normalizedDomain, previousSnapshot: previous) | 1328 | let snapshot = await inspectionService.inspectSnapshot( |
| 1329 | domain: normalizedDomain, | ||
| 1330 | previousSnapshot: previous, | ||
| 1331 | scope: InspectionScope.current(defaults: defaults) | ||
| 1332 | ) | ||
| 1329 | guard let entry = saveHistoryEntry( | 1333 | guard let entry = saveHistoryEntry( |
| 1330 | from: snapshot, | 1334 | from: snapshot, |
| 1331 | replaceLatest: false, | 1335 | replaceLatest: false, |
| @@ -1433,7 +1437,11 @@ final class DomainViewModel { | |||
| 1433 | trackedDomainID: currentTrackedDomain?.id, | 1437 | trackedDomainID: currentTrackedDomain?.id, |
| 1434 | replacingLatest: false | 1438 | replacingLatest: false |
| 1435 | ) | 1439 | ) |
| 1436 | let inspectedSnapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previous) | 1440 | let inspectedSnapshot = await inspectionService.inspectSnapshot( |
| 1441 | domain: domain, | ||
| 1442 | previousSnapshot: previous, | ||
| 1443 | scope: InspectionScope.current(defaults: defaults) | ||
| 1444 | ) | ||
| 1437 | DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)") | 1445 | DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)") |
| 1438 | guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil } | 1446 | guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil } |
| 1439 | 1447 | ||
| @@ -1519,10 +1527,14 @@ final class DomainViewModel { | |||
| 1519 | } | 1527 | } |
| 1520 | } | 1528 | } |
| 1521 | 1529 | ||
| 1522 | private static func performBatchLookup(domain: String, previousSnapshot: LookupSnapshot?) async -> BatchLookupPayload? { | 1530 | private static func performBatchLookup( |
| 1531 | domain: String, | ||
| 1532 | previousSnapshot: LookupSnapshot?, | ||
| 1533 | scope: InspectionScope | ||
| 1534 | ) async -> BatchLookupPayload? { | ||
| 1523 | guard !Task.isCancelled else { return nil } | 1535 | guard !Task.isCancelled else { return nil } |
| 1524 | let inspectionService = DomainInspectionService() | 1536 | let inspectionService = DomainInspectionService() |
| 1525 | let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot) | 1537 | let snapshot = await inspectionService.inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot, scope: scope) |
| 1526 | guard !Task.isCancelled else { return nil } | 1538 | guard !Task.isCancelled else { return nil } |
| 1527 | return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot)) | 1539 | return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot)) |
| 1528 | } | 1540 | } |
| @@ -2141,8 +2153,8 @@ final class DomainViewModel { | |||
| 2141 | updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil) | 2153 | updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil) |
| 2142 | let previousSnapshot = previousSnapshot(for: domain, trackedDomainID: trackedDomain(for: domain)?.id, replacingLatest: false) | 2154 | let previousSnapshot = previousSnapshot(for: domain, trackedDomainID: trackedDomain(for: domain)?.id, replacingLatest: false) |
| 2143 | 2155 | ||
| 2144 | group.addTask { [domain, previousSnapshot] in | 2156 | group.addTask { [domain, previousSnapshot, scope = InspectionScope.current(defaults: defaults)] in |
| 2145 | let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot) | 2157 | let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot, scope: scope) |
| 2146 | return (domain, payload) | 2158 | return (domain, payload) |
| 2147 | } | 2159 | } |
| 2148 | } | 2160 | } |
DomainDig/InspectionScope.swift added +131
| @@ -0,0 +1,131 @@ | |||
| 1 | import Foundation | ||
| 2 | |||
| 3 | /// How much of an inspection to run. | ||
| 4 | /// | ||
| 5 | /// Opted out of the project's MainActor default isolation, along with | ||
| 6 | /// `InspectionScope` below: monitoring and the batch pipeline build a scope | ||
| 7 | /// from a background context. | ||
| 8 | nonisolated enum InspectionProfile: String, Codable, CaseIterable, Sendable, Identifiable { | ||
| 9 | /// Registration, ownership, TLS, HSTS, HTTP, redirects and PTR: the | ||
| 10 | /// sections that answer "what is this domain" without probing ports or | ||
| 11 | /// enumerating hosts. | ||
| 12 | case quick | ||
| 13 | /// Every section. | ||
| 14 | case full | ||
| 15 | |||
| 16 | var id: String { rawValue } | ||
| 17 | |||
| 18 | var title: String { | ||
| 19 | switch self { | ||
| 20 | case .quick: | ||
| 21 | return "Quick" | ||
| 22 | case .full: | ||
| 23 | return "Full" | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | var detail: String { | ||
| 28 | switch self { | ||
| 29 | case .quick: | ||
| 30 | return "DNS, registration, ownership, TLS and HTTP. Skips port scanning, reachability, subdomain discovery, IP geolocation and name suggestions." | ||
| 31 | case .full: | ||
| 32 | return "Every section." | ||
| 33 | } | ||
| 34 | } | ||
| 35 | } | ||
| 36 | |||
| 37 | /// What a single inspection is allowed to do. | ||
| 38 | /// | ||
| 39 | /// This is a parameter of `inspectSnapshot` with no default value, so each of | ||
| 40 | /// the six call sites has to state its scope and none can inherit one silently. | ||
| 41 | nonisolated struct InspectionScope: Sendable, Equatable { | ||
| 42 | var profile: InspectionProfile | ||
| 43 | /// Whether the inspection may contact `rdap.org`, `crt.sh` and `ipapi.co`. | ||
| 44 | var allowsThirdPartyEnrichment: Bool | ||
| 45 | |||
| 46 | static let profileDefaultsKey = "inspection.profile" | ||
| 47 | static let enrichmentDefaultsKey = "inspection.allowsThirdPartyEnrichment" | ||
| 48 | |||
| 49 | /// Every section against every service. The Local API answers with this | ||
| 50 | /// unless a request asks otherwise, so `v1` consumers see no change. | ||
| 51 | static let full = InspectionScope(profile: .full, allowsThirdPartyEnrichment: true) | ||
| 52 | |||
| 53 | /// The scope the user has chosen, for the app's own lookups and for | ||
| 54 | /// monitoring. Both settings default on, as they behaved before they | ||
| 55 | /// existed. | ||
| 56 | static func current(defaults: UserDefaults = .standard) -> InspectionScope { | ||
| 57 | let storedProfile = defaults.string(forKey: profileDefaultsKey) | ||
| 58 | return InspectionScope( | ||
| 59 | profile: storedProfile.flatMap(InspectionProfile.init(rawValue:)) ?? .full, | ||
| 60 | allowsThirdPartyEnrichment: defaults.object(forKey: enrichmentDefaultsKey) as? Bool ?? true | ||
| 61 | ) | ||
| 62 | } | ||
| 63 | |||
| 64 | /// The scope a Local API request asks for. | ||
| 65 | /// | ||
| 66 | /// The profile defaults to Full, so a `v1` consumer that sends no `profile` | ||
| 67 | /// gets what it always did. The enrichment setting is the device owner's | ||
| 68 | /// consent decision rather than a per-request option, so it applies here | ||
| 69 | /// too and a request cannot override it. | ||
| 70 | /// | ||
| 71 | /// Returns `nil` for a `profile` value that names no known profile, which | ||
| 72 | /// the caller answers as a request error rather than silently running Full. | ||
| 73 | static func requested( | ||
| 74 | from queryItems: [URLQueryItem], | ||
| 75 | defaults: UserDefaults = .standard | ||
| 76 | ) -> InspectionScope? { | ||
| 77 | let requested = queryItems.first { $0.name == "profile" }?.value? | ||
| 78 | .trimmingCharacters(in: .whitespacesAndNewlines) | ||
| 79 | .lowercased() | ||
| 80 | let profile: InspectionProfile | ||
| 81 | if let requested, !requested.isEmpty { | ||
| 82 | guard let parsed = InspectionProfile(rawValue: requested) else { return nil } | ||
| 83 | profile = parsed | ||
| 84 | } else { | ||
| 85 | profile = .full | ||
| 86 | } | ||
| 87 | return InspectionScope( | ||
| 88 | profile: profile, | ||
| 89 | allowsThirdPartyEnrichment: current(defaults: defaults).allowsThirdPartyEnrichment | ||
| 90 | ) | ||
| 91 | } | ||
| 92 | |||
| 93 | /// Whether this scope runs `section`. | ||
| 94 | /// | ||
| 95 | /// `availability` always runs: declining enrichment drops its RDAP half, | ||
| 96 | /// leaving the DNS fallback, which still recognises a domain that resolves. | ||
| 97 | func runs(_ section: LookupSectionKind) -> Bool { | ||
| 98 | switch section { | ||
| 99 | case .dns, .availability, .ssl, .hsts, .httpHeaders, .emailSecurity, .ptr, .redirectChain: | ||
| 100 | return true | ||
| 101 | case .ownership: | ||
| 102 | return allowsThirdPartyEnrichment | ||
| 103 | case .reachability, .portScan: | ||
| 104 | return profile == .full | ||
| 105 | case .ipGeolocation, .subdomains, .suggestions: | ||
| 106 | return profile == .full && allowsThirdPartyEnrichment | ||
| 107 | } | ||
| 108 | } | ||
| 109 | |||
| 110 | /// Whether `DomainAvailabilityService` may ask RDAP, as opposed to deciding | ||
| 111 | /// registration from DNS alone. | ||
| 112 | var allowsRDAP: Bool { allowsThirdPartyEnrichment } | ||
| 113 | |||
| 114 | /// What to show in place of a section this scope did not run. | ||
| 115 | func skipReason(for section: LookupSectionKind) -> String? { | ||
| 116 | guard !runs(section) else { return nil } | ||
| 117 | if !allowsThirdPartyEnrichment, Self.needsThirdParty(section) { | ||
| 118 | return "Not run: third-party enrichment is off in Settings." | ||
| 119 | } | ||
| 120 | return "Not run in the Quick profile." | ||
| 121 | } | ||
| 122 | |||
| 123 | private static func needsThirdParty(_ section: LookupSectionKind) -> Bool { | ||
| 124 | switch section { | ||
| 125 | case .ownership, .ipGeolocation, .subdomains, .suggestions: | ||
| 126 | return true | ||
| 127 | case .dns, .availability, .ssl, .hsts, .httpHeaders, .emailSecurity, .ptr, .redirectChain, .reachability, .portScan: | ||
| 128 | return false | ||
| 129 | } | ||
| 130 | } | ||
| 131 | } | ||
DomainDig/LookupRuntime.swift +2 −2
| @@ -65,9 +65,9 @@ actor LookupRuntime { | |||
| 65 | ) | 65 | ) |
| 66 | } | 66 | } |
| 67 | 67 | ||
| 68 | func availability(domain: String) async -> CachedLookupResult<DomainAvailabilityResult> { | 68 | func availability(domain: String, allowsRDAP: Bool) async -> CachedLookupResult<DomainAvailabilityResult> { |
| 69 | CachedLookupResult( | 69 | CachedLookupResult( |
| 70 | value: await DomainAvailabilityService.check(domain: domain), | 70 | value: await DomainAvailabilityService.check(domain: domain, allowsRDAP: allowsRDAP), |
| 71 | source: .live | 71 | source: .live |
| 72 | ) | 72 | ) |
| 73 | } | 73 | } |
DomainDig/SettingsViews.swift +29
| @@ -141,10 +141,23 @@ private struct HistoryNetworkSettingsView: View { | |||
| 141 | @Bindable var viewModel: DomainViewModel | 141 | @Bindable var viewModel: DomainViewModel |
| 142 | @AppStorage(DNSResolverOption.userDefaultsKey) private var storedResolverURL = DNSResolverOption.defaultURLString | 142 | @AppStorage(DNSResolverOption.userDefaultsKey) private var storedResolverURL = DNSResolverOption.defaultURLString |
| 143 | @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue | 143 | @AppStorage(AppDensity.userDefaultsKey) private var storedDensity = AppDensity.compact.rawValue |
| 144 | @AppStorage(InspectionScope.profileDefaultsKey) private var storedProfile = InspectionProfile.full.rawValue | ||
| 145 | @AppStorage(InspectionScope.enrichmentDefaultsKey) private var allowsThirdPartyEnrichment = true | ||
| 144 | 146 | ||
| 145 | @State private var resolverOption: DNSResolverOption = .cloudflare | 147 | @State private var resolverOption: DNSResolverOption = .cloudflare |
| 146 | @State private var customResolverURL = DNSResolverOption.defaultURLString | 148 | @State private var customResolverURL = DNSResolverOption.defaultURLString |
| 147 | 149 | ||
| 150 | private static let enrichmentCaption = """ | ||
| 151 | On, DomainDig asks rdap.org for registration and ownership, crt.sh for subdomain discovery, \ | ||
| 152 | and ipapi.co for IP location. Off, it contacts none of them: ownership, subdomain discovery, \ | ||
| 153 | IP location and name suggestions become unavailable, and registration is decided from DNS \ | ||
| 154 | alone, so a domain that resolves reads as registered and anything else as unknown. | ||
| 155 | """ | ||
| 156 | |||
| 157 | private var selectedProfile: InspectionProfile { | ||
| 158 | InspectionProfile(rawValue: storedProfile) ?? .full | ||
| 159 | } | ||
| 160 | |||
| 148 | private var customResolverError: String? { | 161 | private var customResolverError: String? { |
| 149 | guard resolverOption == .custom else { return nil } | 162 | guard resolverOption == .custom else { return nil } |
| 150 | return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://" | 163 | return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://" |
| @@ -189,6 +202,22 @@ private struct HistoryNetworkSettingsView: View { | |||
| 189 | .foregroundStyle(Color(.statusCritical)) | 202 | .foregroundStyle(Color(.statusCritical)) |
| 190 | } | 203 | } |
| 191 | } | 204 | } |
| 205 | |||
| 206 | Picker("Lookup profile", selection: $storedProfile) { | ||
| 207 | ForEach(InspectionProfile.allCases) { profile in | ||
| 208 | Text(profile.title).tag(profile.rawValue) | ||
| 209 | } | ||
| 210 | } | ||
| 211 | |||
| 212 | Text(selectedProfile.detail) | ||
| 213 | .font(appDensity.font(.caption, design: .default)) | ||
| 214 | .foregroundStyle(Color(.appTextSecondary)) | ||
| 215 | |||
| 216 | Toggle("Allow third-party enrichment", isOn: $allowsThirdPartyEnrichment) | ||
| 217 | |||
| 218 | Text(Self.enrichmentCaption) | ||
| 219 | .font(appDensity.font(.caption, design: .default)) | ||
| 220 | .foregroundStyle(Color(.appTextSecondary)) | ||
| 192 | } | 221 | } |
| 193 | } | 222 | } |
| 194 | .navigationTitle("History & Network") | 223 | .navigationTitle("History & Network") |
DomainDigTests/AvailabilityTests.swift +63
| @@ -141,6 +141,69 @@ final class DomainAvailabilityTests: XCTestCase { | |||
| 141 | XCTAssertEqual(results.map(\.domain), ["example.net", "example.io"]) | 141 | XCTAssertEqual(results.map(\.domain), ["example.net", "example.io"]) |
| 142 | XCTAssertEqual(results.map(\.status), [.available, .registered]) | 142 | XCTAssertEqual(results.map(\.status), [.available, .registered]) |
| 143 | } | 143 | } |
| 144 | |||
| 145 | // MARK: Declining RDAP | ||
| 146 | |||
| 147 | /// With third-party enrichment off, `rdap.org` is not contacted at all, and | ||
| 148 | /// registration is decided from DNS: a name that resolves is registered. | ||
| 149 | func testDecliningRDAPDecidesRegisteredFromDNSWithoutContactingRDAP() async { | ||
| 150 | let transport = StubRDAPTransport { _ in | ||
| 151 | XCTFail("declining RDAP should not reach rdap.org") | ||
| 152 | return (Data(), stubHTTPResponse(status: 200, host: "rdap.org", domain: "")) | ||
| 153 | } | ||
| 154 | let dns = StubDNSLookup(records: [.A: [DNSRecord(value: "203.0.113.10", ttl: 300)]]) | ||
| 155 | |||
| 156 | let result = await DomainAvailabilityService.check( | ||
| 157 | domain: "example.com", | ||
| 158 | allowsRDAP: false, | ||
| 159 | rdapTransport: transport, | ||
| 160 | dns: dns | ||
| 161 | ) | ||
| 162 | |||
| 163 | XCTAssertEqual(result.status, .registered) | ||
| 164 | XCTAssertEqual(transport.requestedDomains, []) | ||
| 165 | XCTAssertGreaterThan(dns.lookupCount, 0, "the DNS fallback is the only source left") | ||
| 166 | } | ||
| 167 | |||
| 168 | /// The fallback can only prove registration. Without RDAP an unregistered | ||
| 169 | /// name is `.unknown`, never `.available` — the whole point of keeping the | ||
| 170 | /// two apart is that DoH drops NXDOMAIN. | ||
| 171 | func testDecliningRDAPNeverReportsAvailable() async { | ||
| 172 | let transport = StubRDAPTransport { _ in | ||
| 173 | XCTFail("declining RDAP should not reach rdap.org") | ||
| 174 | return (Data(), stubHTTPResponse(status: 404, host: "rdap.verisign.com", domain: "example.com")) | ||
| 175 | } | ||
| 176 | let dns = StubDNSLookup(records: [:]) | ||
| 177 | |||
| 178 | let result = await DomainAvailabilityService.check( | ||
| 179 | domain: "example.com", | ||
| 180 | allowsRDAP: false, | ||
| 181 | rdapTransport: transport, | ||
| 182 | dns: dns | ||
| 183 | ) | ||
| 184 | |||
| 185 | XCTAssertEqual(result.status, .unknown) | ||
| 186 | XCTAssertEqual(transport.requestedDomains, []) | ||
| 187 | } | ||
| 188 | |||
| 189 | /// Blank input is still rejected before either source. | ||
| 190 | func testDecliningRDAPStillRejectsBlankInput() async { | ||
| 191 | let transport = StubRDAPTransport { _ in | ||
| 192 | XCTFail("blank input should not reach the network") | ||
| 193 | return (Data(), stubHTTPResponse(status: 200, host: "rdap.org", domain: "")) | ||
| 194 | } | ||
| 195 | let dns = StubDNSLookup(records: [:]) | ||
| 196 | |||
| 197 | let result = await DomainAvailabilityService.check( | ||
| 198 | domain: " ", | ||
| 199 | allowsRDAP: false, | ||
| 200 | rdapTransport: transport, | ||
| 201 | dns: dns | ||
| 202 | ) | ||
| 203 | |||
| 204 | XCTAssertEqual(result.status, .unknown) | ||
| 205 | XCTAssertEqual(dns.lookupCount, 0) | ||
| 206 | } | ||
| 144 | } | 207 | } |
| 145 | 208 | ||
| 146 | private final class StubRDAPTransport: RDAPTransport { | 209 | private final class StubRDAPTransport: RDAPTransport { |
DomainDigTests/InspectionScopeTests.swift added +193
| @@ -0,0 +1,193 @@ | |||
| 1 | import XCTest | ||
| 2 | @testable import DomainDig | ||
| 3 | |||
| 4 | /// Section selection and the enrichment choice reach the inspection through | ||
| 5 | /// `inspectSnapshot`'s signature, so what each scope runs is a pure function | ||
| 6 | /// and these are what pin it. The inspection service itself takes a concrete | ||
| 7 | /// `LookupRuntime`, so there is no seam to assert the network calls through — | ||
| 8 | /// `DomainAvailabilityTests` covers the one service that can be stubbed. | ||
| 9 | final class InspectionScopeTests: XCTestCase { | ||
| 10 | |||
| 11 | private var scratch: UserDefaults! | ||
| 12 | private var suiteName: String! | ||
| 13 | |||
| 14 | override func setUpWithError() throws { | ||
| 15 | try super.setUpWithError() | ||
| 16 | suiteName = "net.cleberg.DomainDig.tests.scope.\(UUID().uuidString)" | ||
| 17 | scratch = try XCTUnwrap(UserDefaults(suiteName: suiteName)) | ||
| 18 | } | ||
| 19 | |||
| 20 | override func tearDownWithError() throws { | ||
| 21 | scratch.removePersistentDomain(forName: suiteName) | ||
| 22 | scratch = nil | ||
| 23 | suiteName = nil | ||
| 24 | try super.tearDownWithError() | ||
| 25 | } | ||
| 26 | |||
| 27 | // MARK: What each scope runs | ||
| 28 | |||
| 29 | func testFullWithEnrichmentRunsEverySection() { | ||
| 30 | let scope = InspectionScope.full | ||
| 31 | |||
| 32 | for section in LookupSectionKind.allCases { | ||
| 33 | XCTAssertTrue(scope.runs(section), "full should run \(section.rawValue)") | ||
| 34 | XCTAssertNil(scope.skipReason(for: section)) | ||
| 35 | } | ||
| 36 | } | ||
| 37 | |||
| 38 | func testQuickSkipsTheExpensiveSections() { | ||
| 39 | let scope = InspectionScope(profile: .quick, allowsThirdPartyEnrichment: true) | ||
| 40 | |||
| 41 | let skipped = LookupSectionKind.allCases.filter { !scope.runs($0) } | ||
| 42 | |||
| 43 | XCTAssertEqual( | ||
| 44 | Set(skipped), | ||
| 45 | [.reachability, .portScan, .ipGeolocation, .subdomains, .suggestions] | ||
| 46 | ) | ||
| 47 | } | ||
| 48 | |||
| 49 | func testQuickStillRunsTheCoreSections() { | ||
| 50 | let scope = InspectionScope(profile: .quick, allowsThirdPartyEnrichment: true) | ||
| 51 | |||
| 52 | for section in [LookupSectionKind.dns, .availability, .ownership, .ssl, .hsts, .httpHeaders, .redirectChain, .ptr, .emailSecurity] { | ||
| 53 | XCTAssertTrue(scope.runs(section), "quick should still run \(section.rawValue)") | ||
| 54 | } | ||
| 55 | } | ||
| 56 | |||
| 57 | func testDecliningEnrichmentSkipsOnlyTheThirdPartySections() { | ||
| 58 | let scope = InspectionScope(profile: .full, allowsThirdPartyEnrichment: false) | ||
| 59 | |||
| 60 | let skipped = LookupSectionKind.allCases.filter { !scope.runs($0) } | ||
| 61 | |||
| 62 | XCTAssertEqual(Set(skipped), [.ownership, .ipGeolocation, .subdomains, .suggestions]) | ||
| 63 | } | ||
| 64 | |||
| 65 | /// Availability keeps running without enrichment: RDAP is only half of it, | ||
| 66 | /// and the DNS fallback still recognises a domain that resolves. | ||
| 67 | func testDecliningEnrichmentKeepsAvailabilityButDropsItsRDAPHalf() { | ||
| 68 | let scope = InspectionScope(profile: .full, allowsThirdPartyEnrichment: false) | ||
| 69 | |||
| 70 | XCTAssertTrue(scope.runs(.availability)) | ||
| 71 | XCTAssertFalse(scope.allowsRDAP) | ||
| 72 | XCTAssertTrue(InspectionScope.full.allowsRDAP) | ||
| 73 | } | ||
| 74 | |||
| 75 | func testDecliningEnrichmentOnQuickSkipsTheUnionOfBoth() { | ||
| 76 | let scope = InspectionScope(profile: .quick, allowsThirdPartyEnrichment: false) | ||
| 77 | |||
| 78 | let skipped = LookupSectionKind.allCases.filter { !scope.runs($0) } | ||
| 79 | |||
| 80 | XCTAssertEqual( | ||
| 81 | Set(skipped), | ||
| 82 | [.ownership, .reachability, .portScan, .ipGeolocation, .subdomains, .suggestions] | ||
| 83 | ) | ||
| 84 | } | ||
| 85 | |||
| 86 | // MARK: Skip reasons | ||
| 87 | |||
| 88 | /// A skipped section shows why, so the UI does not read as a failed lookup. | ||
| 89 | func testTheSkipReasonNamesTheProfileOrTheEnrichmentSetting() { | ||
| 90 | let quick = InspectionScope(profile: .quick, allowsThirdPartyEnrichment: true) | ||
| 91 | let declined = InspectionScope(profile: .full, allowsThirdPartyEnrichment: false) | ||
| 92 | |||
| 93 | XCTAssertEqual(quick.skipReason(for: .portScan), "Not run in the Quick profile.") | ||
| 94 | XCTAssertEqual(declined.skipReason(for: .ownership), "Not run: third-party enrichment is off in Settings.") | ||
| 95 | } | ||
| 96 | |||
| 97 | /// When both apply, the consent decision is the one worth reporting. | ||
| 98 | func testEnrichmentOutranksTheProfileInTheSkipReason() { | ||
| 99 | let scope = InspectionScope(profile: .quick, allowsThirdPartyEnrichment: false) | ||
| 100 | |||
| 101 | XCTAssertEqual(scope.skipReason(for: .subdomains), "Not run: third-party enrichment is off in Settings.") | ||
| 102 | XCTAssertEqual(scope.skipReason(for: .portScan), "Not run in the Quick profile.") | ||
| 103 | } | ||
| 104 | |||
| 105 | func testASectionThatRunsHasNoSkipReason() { | ||
| 106 | XCTAssertNil(InspectionScope.full.skipReason(for: .dns)) | ||
| 107 | XCTAssertNil(InspectionScope(profile: .quick, allowsThirdPartyEnrichment: false).skipReason(for: .dns)) | ||
| 108 | } | ||
| 109 | |||
| 110 | // MARK: The stored setting | ||
| 111 | |||
| 112 | /// Both settings default on, which is how the app behaved before they | ||
| 113 | /// existed. | ||
| 114 | func testAnEmptyStoreReadsAsFullWithEnrichment() { | ||
| 115 | XCTAssertEqual(InspectionScope.current(defaults: scratch), .full) | ||
| 116 | } | ||
| 117 | |||
| 118 | func testStoredValuesAreRead() { | ||
| 119 | scratch.set(InspectionProfile.quick.rawValue, forKey: InspectionScope.profileDefaultsKey) | ||
| 120 | scratch.set(false, forKey: InspectionScope.enrichmentDefaultsKey) | ||
| 121 | |||
| 122 | XCTAssertEqual( | ||
| 123 | InspectionScope.current(defaults: scratch), | ||
| 124 | InspectionScope(profile: .quick, allowsThirdPartyEnrichment: false) | ||
| 125 | ) | ||
| 126 | } | ||
| 127 | |||
| 128 | /// A profile string the app does not know falls back to Full rather than | ||
| 129 | /// quietly reducing what a lookup covers. | ||
| 130 | func testAnUnknownStoredProfileFallsBackToFull() { | ||
| 131 | scratch.set("exhaustive", forKey: InspectionScope.profileDefaultsKey) | ||
| 132 | |||
| 133 | XCTAssertEqual(InspectionScope.current(defaults: scratch).profile, .full) | ||
| 134 | } | ||
| 135 | |||
| 136 | // MARK: The Local API's profile parameter | ||
| 137 | |||
| 138 | private func apiProfile(_ queryItems: [URLQueryItem]) throws -> InspectionProfile { | ||
| 139 | try XCTUnwrap(InspectionScope.requested(from: queryItems, defaults: scratch)).profile | ||
| 140 | } | ||
| 141 | |||
| 142 | /// A `v1` consumer sends no `profile`, so it has to keep getting Full. | ||
| 143 | func testTheLocalAPIDefaultsToFullWithoutAProfileParameter() throws { | ||
| 144 | XCTAssertEqual(try apiProfile([]), InspectionProfile.full) | ||
| 145 | XCTAssertEqual( | ||
| 146 | try apiProfile([URLQueryItem(name: "other", value: "quick")]), | ||
| 147 | InspectionProfile.full | ||
| 148 | ) | ||
| 149 | } | ||
| 150 | |||
| 151 | func testTheLocalAPIReadsAnExplicitProfile() throws { | ||
| 152 | XCTAssertEqual( | ||
| 153 | try apiProfile([URLQueryItem(name: "profile", value: "quick")]), | ||
| 154 | InspectionProfile.quick | ||
| 155 | ) | ||
| 156 | XCTAssertEqual( | ||
| 157 | try apiProfile([URLQueryItem(name: "profile", value: " FULL ")]), | ||
| 158 | InspectionProfile.full | ||
| 159 | ) | ||
| 160 | } | ||
| 161 | |||
| 162 | /// An unrecognised profile is a request error rather than a silent Full, so | ||
| 163 | /// a typo does not look like it worked. | ||
| 164 | func testTheLocalAPIRejectsAnUnknownProfile() { | ||
| 165 | XCTAssertNil(InspectionScope.requested(from: [URLQueryItem(name: "profile", value: "deep")], defaults: scratch)) | ||
| 166 | } | ||
| 167 | |||
| 168 | func testAnEmptyProfileValueIsTreatedAsAbsent() throws { | ||
| 169 | for value in ["", " ", nil] { | ||
| 170 | XCTAssertEqual( | ||
| 171 | try apiProfile([URLQueryItem(name: "profile", value: value)]), | ||
| 172 | InspectionProfile.full, | ||
| 173 | "an empty profile should read as absent, not as an error" | ||
| 174 | ) | ||
| 175 | } | ||
| 176 | } | ||
| 177 | |||
| 178 | /// The enrichment setting is the device owner's consent decision, so the | ||
| 179 | /// Local API follows it and a request cannot turn it back on. | ||
| 180 | func testTheLocalAPIFollowsTheStoredEnrichmentSetting() throws { | ||
| 181 | scratch.set(false, forKey: InspectionScope.enrichmentDefaultsKey) | ||
| 182 | |||
| 183 | let scope = try XCTUnwrap( | ||
| 184 | InspectionScope.requested( | ||
| 185 | from: [URLQueryItem(name: "profile", value: "full")], | ||
| 186 | defaults: scratch | ||
| 187 | ) | ||
| 188 | ) | ||
| 189 | |||
| 190 | XCTAssertEqual(scope.profile, InspectionProfile.full) | ||
| 191 | XCTAssertFalse(scope.allowsThirdPartyEnrichment) | ||
| 192 | } | ||
| 193 | } | ||
DomainInspectionService.swift +77 −36
| @@ -8,27 +8,39 @@ struct DomainInspectionService { | |||
| 8 | self.runtime = runtime | 8 | self.runtime = runtime |
| 9 | } | 9 | } |
| 10 | 10 | ||
| 11 | func inspect(domain: String, previousSnapshot: LookupSnapshot? = nil) async -> DomainReport { | 11 | func inspect( |
| 12 | let snapshot = await inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot) | 12 | domain: String, |
| 13 | previousSnapshot: LookupSnapshot? = nil, | ||
| 14 | scope: InspectionScope | ||
| 15 | ) async -> DomainReport { | ||
| 16 | let snapshot = await inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot, scope: scope) | ||
| 13 | return reportBuilder.build(from: snapshot) | 17 | return reportBuilder.build(from: snapshot) |
| 14 | } | 18 | } |
| 15 | 19 | ||
| 16 | func inspectSnapshot(domain: String, previousSnapshot: LookupSnapshot? = nil) async -> LookupSnapshot { | 20 | func inspectSnapshot( |
| 21 | domain: String, | ||
| 22 | previousSnapshot: LookupSnapshot? = nil, | ||
| 23 | scope: InspectionScope | ||
| 24 | ) async -> LookupSnapshot { | ||
| 17 | let normalizedDomain = normalize(domain) | 25 | let normalizedDomain = normalize(domain) |
| 18 | let inspectionStartedAt = DomainDebugLog.signpostStart("Inspection.inspectSnapshot", domain: normalizedDomain) | 26 | let inspectionStartedAt = DomainDebugLog.signpostStart("Inspection.inspectSnapshot", domain: normalizedDomain) |
| 19 | let startedAt = Date() | 27 | let startedAt = Date() |
| 20 | let resolverDisplayName = DNSLookupService.currentResolverDisplayName() | 28 | let resolverDisplayName = DNSLookupService.currentResolverDisplayName() |
| 21 | let resolverURLString = DNSLookupService.currentResolverURLString() | 29 | let resolverURLString = DNSLookupService.currentResolverURLString() |
| 22 | var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName) | 30 | var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName, scope: scope) |
| 23 | 31 | ||
| 24 | async let dnsFetch = runtime.dns(domain: normalizedDomain) | 32 | async let dnsFetch = runtime.dns(domain: normalizedDomain) |
| 25 | async let availabilityFetch = runtime.availability(domain: normalizedDomain) | 33 | async let availabilityFetch = runtime.availability(domain: normalizedDomain, allowsRDAP: scope.allowsRDAP) |
| 26 | async let sslFetch = runtime.ssl(domain: normalizedDomain) | 34 | async let sslFetch = runtime.ssl(domain: normalizedDomain) |
| 27 | async let hstsFetch = runtime.hsts(domain: normalizedDomain) | 35 | async let hstsFetch = runtime.hsts(domain: normalizedDomain) |
| 28 | async let httpFetch = runtime.http(domain: normalizedDomain) | 36 | async let httpFetch = runtime.http(domain: normalizedDomain) |
| 29 | async let ownershipFetch = runtime.ownership(domain: normalizedDomain) | 37 | async let ownershipFetch = whenInScope(.ownership, scope) { |
| 38 | await runtime.ownership(domain: normalizedDomain) | ||
| 39 | } | ||
| 30 | async let redirectFetch = runtime.redirectChain(domain: normalizedDomain) | 40 | async let redirectFetch = runtime.redirectChain(domain: normalizedDomain) |
| 31 | async let subdomainFetch = runtime.subdomains(domain: normalizedDomain) | 41 | async let subdomainFetch = whenInScope(.subdomains, scope) { |
| 42 | await runtime.subdomains(domain: normalizedDomain) | ||
| 43 | } | ||
| 32 | 44 | ||
| 33 | let resolvedDNS = await dnsFetch | 45 | let resolvedDNS = await dnsFetch |
| 34 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)") | 46 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)") |
| @@ -59,8 +71,10 @@ struct DomainInspectionService { | |||
| 59 | let resolvedOwnership = await ownershipFetch | 71 | let resolvedOwnership = await ownershipFetch |
| 60 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)") | 72 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)") |
| 61 | let ownershipResult = normalizeErrors(in: resolvedOwnership.value) | 73 | let ownershipResult = normalizeErrors(in: resolvedOwnership.value) |
| 62 | ledger.track(.ownership, source: resolvedOwnership.source) | 74 | if scope.runs(.ownership) { |
| 63 | ledger.captureFailure(for: .ownership, result: ownershipResult) | 75 | ledger.track(.ownership, source: resolvedOwnership.source) |
| 76 | ledger.captureFailure(for: .ownership, result: ownershipResult) | ||
| 77 | } | ||
| 64 | 78 | ||
| 65 | let redirects = await redirectFetch | 79 | let redirects = await redirectFetch |
| 66 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)") | 80 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)") |
| @@ -71,8 +85,10 @@ struct DomainInspectionService { | |||
| 71 | let resolvedSubdomains = await subdomainFetch | 85 | let resolvedSubdomains = await subdomainFetch |
| 72 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)") | 86 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)") |
| 73 | let subdomainResult = normalizeErrors(in: resolvedSubdomains.value) | 87 | let subdomainResult = normalizeErrors(in: resolvedSubdomains.value) |
| 74 | ledger.track(.subdomains, source: resolvedSubdomains.source) | 88 | if scope.runs(.subdomains) { |
| 75 | ledger.captureFailure(for: .subdomains, result: subdomainResult) | 89 | ledger.track(.subdomains, source: resolvedSubdomains.source) |
| 90 | ledger.captureFailure(for: .subdomains, result: subdomainResult) | ||
| 91 | } | ||
| 76 | 92 | ||
| 77 | let dnsSections = mapServiceResult(dnsResult, emptyValue: []) | 93 | let dnsSections = mapServiceResult(dnsResult, emptyValue: []) |
| 78 | let sslInfo = mapOptionalValueServiceResult(sslResult) | 94 | let sslInfo = mapOptionalValueServiceResult(sslResult) |
| @@ -90,29 +106,37 @@ struct DomainInspectionService { | |||
| 90 | let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value) | 106 | let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value) |
| 91 | let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP) | 107 | let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP) |
| 92 | 108 | ||
| 93 | let reachabilityOutcome = await whenRoutable(hasNetworkTarget) { | 109 | let reachabilityOutcome = await whenInScope(.reachability, scope) { |
| 94 | await runtime.reachability(domain: normalizedDomain) | 110 | await whenRoutable(hasNetworkTarget) { |
| 111 | await runtime.reachability(domain: normalizedDomain) | ||
| 112 | } | ||
| 95 | } | 113 | } |
| 96 | let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value) | 114 | let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value) |
| 97 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)") | 115 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)") |
| 98 | ledger.track(.reachability, source: reachabilityOutcome.source) | 116 | if scope.runs(.reachability) { |
| 99 | if hasNetworkTarget { | 117 | ledger.track(.reachability, source: reachabilityOutcome.source) |
| 100 | ledger.captureFailure(for: .reachability, result: reachabilityResult) | 118 | if hasNetworkTarget { |
| 119 | ledger.captureFailure(for: .reachability, result: reachabilityResult) | ||
| 120 | } | ||
| 101 | } | 121 | } |
| 102 | let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: []) | 122 | let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: []) |
| 103 | 123 | ||
| 104 | let portScanOutcome = await whenRoutable(hasNetworkTarget) { | 124 | let portScanOutcome = await whenInScope(.portScan, scope) { |
| 105 | await runtime.portScan(domain: normalizedDomain) | 125 | await whenRoutable(hasNetworkTarget) { |
| 126 | await runtime.portScan(domain: normalizedDomain) | ||
| 127 | } | ||
| 106 | } | 128 | } |
| 107 | let portScanResult = normalizeErrors(in: portScanOutcome.value) | 129 | let portScanResult = normalizeErrors(in: portScanOutcome.value) |
| 108 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)") | 130 | DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)") |
| 109 | ledger.track(.portScan, source: portScanOutcome.source) | 131 | if scope.runs(.portScan) { |
| 110 | if hasNetworkTarget { | 132 | ledger.track(.portScan, source: portScanOutcome.source) |
| 111 | ledger.captureFailure(for: .portScan, result: portScanResult) | 133 | if hasNetworkTarget { |
| 134 | ledger.captureFailure(for: .portScan, result: portScanResult) | ||
| 135 | } | ||
| 112 | } | 136 | } |
| 113 | let portScanResults = hasNetworkTarget | 137 | let portScanResults = scope.runs(.portScan) && hasNetworkTarget |
| 114 | ? await mapPortScanResult(portScanResult, domain: normalizedDomain) | 138 | ? await mapPortScanResult(portScanResult, domain: normalizedDomain) |
| 115 | : (value: [], message: nil) | 139 | : (value: [], message: scope.skipReason(for: .portScan)) |
| 116 | 140 | ||
| 117 | let emailOutcome = await reusingPrevious( | 141 | let emailOutcome = await reusingPrevious( |
| 118 | previousSnapshot?.emailSecurity, | 142 | previousSnapshot?.emailSecurity, |
| @@ -127,7 +151,7 @@ struct DomainInspectionService { | |||
| 127 | ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult) | 151 | ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult) |
| 128 | 152 | ||
| 129 | let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]> | 153 | let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]> |
| 130 | if availability.value.status == .registered { | 154 | if scope.runs(.suggestions), availability.value.status == .registered { |
| 131 | suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain) | 155 | suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain) |
| 132 | ledger.track(.suggestions, source: suggestionsOutcome.source) | 156 | ledger.track(.suggestions, source: suggestionsOutcome.source) |
| 133 | } else { | 157 | } else { |
| @@ -144,17 +168,21 @@ struct DomainInspectionService { | |||
| 144 | ) { | 168 | ) { |
| 145 | await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString) | 169 | await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString) |
| 146 | } | 170 | } |
| 147 | let geo = await reusingPrevious( | 171 | let geo = await whenInScope(.ipGeolocation, scope) { |
| 148 | previousSnapshot?.ipGeolocation, | 172 | await reusingPrevious( |
| 149 | error: previousSnapshot?.ipGeolocationError, | 173 | previousSnapshot?.ipGeolocation, |
| 150 | when: canReuseIPDependents | 174 | error: previousSnapshot?.ipGeolocationError, |
| 151 | ) { | 175 | when: canReuseIPDependents |
| 152 | await runtime.ipGeolocation(ip: primaryIP) | 176 | ) { |
| 177 | await runtime.ipGeolocation(ip: primaryIP) | ||
| 178 | } | ||
| 153 | } | 179 | } |
| 154 | ledger.track(.ptr, source: ptr.source) | 180 | ledger.track(.ptr, source: ptr.source) |
| 155 | ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value)) | 181 | ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value)) |
| 156 | ledger.track(.ipGeolocation, source: geo.source) | 182 | if scope.runs(.ipGeolocation) { |
| 157 | ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value)) | 183 | ledger.track(.ipGeolocation, source: geo.source) |
| 184 | ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value)) | ||
| 185 | } | ||
| 158 | ptrOutcome = ptr | 186 | ptrOutcome = ptr |
| 159 | geoOutcome = geo | 187 | geoOutcome = geo |
| 160 | } else { | 188 | } else { |
| @@ -267,6 +295,16 @@ struct DomainInspectionService { | |||
| 267 | .lowercased() ?? domain.lowercased() | 295 | .lowercased() ?? domain.lowercased() |
| 268 | } | 296 | } |
| 269 | 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 | |||
| 270 | /// A lookup that needs an address to reach, or an empty result when the | 308 | /// A lookup that needs an address to reach, or an empty result when the |
| 271 | /// domain has none. | 309 | /// domain has none. |
| 272 | private func whenRoutable<Value>( | 310 | private func whenRoutable<Value>( |
| @@ -300,7 +338,8 @@ struct DomainInspectionService { | |||
| 300 | for section: LookupSectionKind, | 338 | for section: LookupSectionKind, |
| 301 | source: LookupResultSource, | 339 | source: LookupResultSource, |
| 302 | collectedAt: Date, | 340 | collectedAt: Date, |
| 303 | resolverDisplayName: String | 341 | resolverDisplayName: String, |
| 342 | allowsRDAP: Bool | ||
| 304 | ) -> SectionProvenance { | 343 | ) -> SectionProvenance { |
| 305 | switch section { | 344 | switch section { |
| 306 | case .dns, .ptr: | 345 | case .dns, .ptr: |
| @@ -313,9 +352,9 @@ struct DomainInspectionService { | |||
| 313 | ) | 352 | ) |
| 314 | case .availability: | 353 | case .availability: |
| 315 | return SectionProvenance( | 354 | return SectionProvenance( |
| 316 | source: "RDAP lookup with DNS fallback", | 355 | source: allowsRDAP ? "RDAP lookup with DNS fallback" : "DNS query", |
| 317 | collectedAt: collectedAt, | 356 | collectedAt: collectedAt, |
| 318 | provider: "rdap.org / selected resolver", | 357 | provider: allowsRDAP ? "rdap.org / selected resolver" : "Selected DoH resolver", |
| 319 | resolver: resolverDisplayName, | 358 | resolver: resolverDisplayName, |
| 320 | resultSource: source | 359 | resultSource: source |
| 321 | ) | 360 | ) |
| @@ -590,6 +629,7 @@ struct DomainInspectionService { | |||
| 590 | /// from, which were served from cache, and which failed. | 629 | /// from, which were served from cache, and which failed. |
| 591 | private struct InspectionLedger { | 630 | private struct InspectionLedger { |
| 592 | let resolverDisplayName: String | 631 | let resolverDisplayName: String |
| 632 | let scope: InspectionScope | ||
| 593 | var cachedSections = Set<LookupSectionKind>() | 633 | var cachedSections = Set<LookupSectionKind>() |
| 594 | var sectionSources: [LookupResultSource] = [] | 634 | var sectionSources: [LookupResultSource] = [] |
| 595 | var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:] | 635 | var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:] |
| @@ -601,7 +641,8 @@ private struct InspectionLedger { | |||
| 601 | for: section, | 641 | for: section, |
| 602 | source: source, | 642 | source: source, |
| 603 | collectedAt: Date(), | 643 | collectedAt: Date(), |
| 604 | resolverDisplayName: resolverDisplayName | 644 | resolverDisplayName: resolverDisplayName, |
| 645 | allowsRDAP: scope.allowsRDAP | ||
| 605 | ) | 646 | ) |
| 606 | sectionSources.append(source) | 647 | sectionSources.append(source) |
| 607 | provenanceBySection[section] = provenance | 648 | provenanceBySection[section] = provenance |
LocalAPIService.swift +24 −6
| @@ -555,9 +555,15 @@ struct LocalAPIRequestHandler { | |||
| 555 | case .monitoring: | 555 | case .monitoring: |
| 556 | return successResponse(monitoringPayload()) | 556 | return successResponse(monitoringPayload()) |
| 557 | case .inspectFromBody: | 557 | case .inspectFromBody: |
| 558 | return await inspectBodyResponse(request.body) | 558 | guard let scope = InspectionScope.requested(from: request.queryItems) else { |
| 559 | return Self.invalidProfileResponse | ||
| 560 | } | ||
| 561 | return await inspectBodyResponse(request.body, scope: scope) | ||
| 559 | case let .inspect(domain): | 562 | case let .inspect(domain): |
| 560 | return await inspectResponse(for: domain) | 563 | guard let scope = InspectionScope.requested(from: request.queryItems) else { |
| 564 | return Self.invalidProfileResponse | ||
| 565 | } | ||
| 566 | return await inspectResponse(for: domain, scope: scope) | ||
| 561 | case let .setMonitoring(domain, enabled): | 567 | case let .setMonitoring(domain, enabled): |
| 562 | return await setMonitoring(enabled: enabled, for: domain) | 568 | return await setMonitoring(enabled: enabled, for: domain) |
| 563 | } | 569 | } |
| @@ -609,22 +615,34 @@ struct LocalAPIRequestHandler { | |||
| 609 | ) | 615 | ) |
| 610 | } | 616 | } |
| 611 | 617 | ||
| 612 | private func inspectBodyResponse(_ body: Data) async -> LocalAPIHTTPResponse { | 618 | private static var invalidProfileResponse: LocalAPIHTTPResponse { |
| 619 | .error( | ||
| 620 | statusCode: 400, | ||
| 621 | code: "invalid_profile", | ||
| 622 | message: "profile must be one of: \(InspectionProfile.allCases.map(\.rawValue).joined(separator: ", "))." | ||
| 623 | ) | ||
| 624 | } | ||
| 625 | |||
| 626 | private func inspectBodyResponse(_ body: Data, scope: InspectionScope) async -> LocalAPIHTTPResponse { | ||
| 613 | guard let payload = try? decoder.decode(InspectRequestPayload.self, from: body) else { | 627 | guard let payload = try? decoder.decode(InspectRequestPayload.self, from: body) else { |
| 614 | return .error(statusCode: 400, code: "invalid_body", message: "Expected JSON body: {\"domain\":\"example.com\"}.") | 628 | return .error(statusCode: 400, code: "invalid_body", message: "Expected JSON body: {\"domain\":\"example.com\"}.") |
| 615 | } | 629 | } |
| 616 | 630 | ||
| 617 | return await inspectResponse(for: payload.domain) | 631 | return await inspectResponse(for: payload.domain, scope: scope) |
| 618 | } | 632 | } |
| 619 | 633 | ||
| 620 | private func inspectResponse(for domain: String) async -> LocalAPIHTTPResponse { | 634 | private func inspectResponse(for domain: String, scope: InspectionScope) async -> LocalAPIHTTPResponse { |
| 621 | let normalized = normalizedDomain(domain) | 635 | let normalized = normalizedDomain(domain) |
| 622 | guard !normalized.isEmpty else { | 636 | guard !normalized.isEmpty else { |
| 623 | return .error(statusCode: 400, code: "invalid_domain", message: "A valid domain is required.") | 637 | return .error(statusCode: 400, code: "invalid_domain", message: "A valid domain is required.") |
| 624 | } | 638 | } |
| 625 | 639 | ||
| 626 | let previousSnapshot = latestHistoryEntry(for: normalized)?.snapshot | 640 | let previousSnapshot = latestHistoryEntry(for: normalized)?.snapshot |
| 627 | let report = await inspectionService.inspect(domain: normalized, previousSnapshot: previousSnapshot) | 641 | let report = await inspectionService.inspect( |
| 642 | domain: normalized, | ||
| 643 | previousSnapshot: previousSnapshot, | ||
| 644 | scope: scope | ||
| 645 | ) | ||
| 628 | return successResponse(InspectResponsePayload(report: report)) | 646 | return successResponse(InspectResponsePayload(report: report)) |
| 629 | } | 647 | } |
| 630 | 648 | ||