Commit 86b2b1a65e

86b2b1a65e949fcc05d4827512c3e80763d5d5dc

parent: 31f090e160

Unsigned

cmc <hello@cleberg.net> · 2026-10-25 08:54 UTC

Give an inspection a scope: Quick/Full and enrichment consent (!35)

Closes U1 from the review catalogue.

`inspectSnapshot` and `inspect` take a required `InspectionScope` — a profile
plus an enrichment flag. There is no default value, so each of the six call
sites states its scope: three in `DomainViewModel` (single lookup, audit
session, batch), plus `DomainMonitoringService`, `DomainDigIntents` and the
Local API. The catalogue said three; it missed the intent and two of the view
model's.

Quick runs DNS, registration, ownership, TLS, HSTS, HTTP, redirects, PTR and
email security. It leaves out reachability, port scanning, subdomain discovery,
IP geolocation and name suggestions. A skipped section carries a message saying
why, so it does not read as a failed lookup, and the ledger does not record
provenance or a failure for a section that was never run.

Settings → Network gets a profile picker and one "Allow third-party enrichment"
toggle covering rdap.org, crt.sh and ipapi.co, defaulting on.

Declining enrichment degrades availability rather than removing it.
`rdap.org` is the only RDAP path — there is no registry-direct fallback — but
`DomainAvailabilityService.check` already falls back to DNS, which recognises a
domain that resolves. So availability reports `registered` or `unknown` and
never `available`, which is the existing rule that DoH drops NXDOMAIN. Ownership
has no such fallback and is simply unavailable, as are subdomain discovery, IP
geolocation and suggestions. The toggle's caption says all of this, and the
availability provenance no longer names rdap.org when it was not asked, so
confidence drops from high to medium instead of overstating the source.

Monitoring follows the same settings. The Local API defaults to Full and takes
an optional `profile` query parameter, so a `v1` consumer that sends none sees
no change; an unknown value is a 400 `invalid_profile` rather than a silent
Full. It follows the enrichment setting, which a request cannot override: that
is the device owner's consent decision, not a per-request option. This is wider
than the plan's D7, which mentioned only the profile for the API — a consent
setting the device's own API ignores would not be consent.

Gated sections are not called at all rather than called and discarded, so no
degraded value reaches `LookupRuntime`'s cache. Availability is not cached
(it returns `.live` directly), so its RDAP-less result cannot be reused either.

`InspectionScope` and `InspectionProfile` opt out of the project's MainActor
default isolation, as `CachedLookupResult` does, because monitoring and the
batch pipeline build a scope from a background context.

20 new tests: what each scope runs, the skip reasons, the stored setting, the
Local API's profile parsing, and three against `DomainAvailabilityService`'s
stub transports proving that declining enrichment does not contact rdap.org and
never reports `available`. 277 green on iOS 18.6 and 27.0. Complexity ratchet
unchanged at 280, nothing over it.

The inspection service takes a concrete `LookupRuntime`, so there is no seam to
assert the other sections' calls through; the availability tests cover the one
service that can be stubbed.

Layout: unified · split

Docs/local-api.txt +14
@@ -78,6 +78,19 @@ Every response — success or error — is wrapped in the same envelope:
7878
7979`certificateWarningLevel` encodes as `"none"`, `"warning"`, or `"critical"`.
8080
81Both `/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
83before. `quick` runs DNS, registration, ownership, TLS, HSTS, HTTP, redirects
84and PTR, and leaves out reachability, port scanning, subdomain discovery, IP
85geolocation and name suggestions; each omitted section carries a message saying
86it was not run.
87
88When the device owner has turned off third-party enrichment in Settings, both
89routes follow that setting and a request cannot override it: ownership,
90subdomain discovery, IP geolocation and name suggestions are not collected, and
91registration is decided from DNS alone, which reports `registered` or
92`unknown` but never `available`.
93
8194`DomainReport` is the app's canonical report model (the same shape the JSON
8295export produces); see `DomainReportBuilder.swift` for its fields. It is a large
8396object and is treated as an additive contract: new fields may appear without a
@@ -90,6 +103,7 @@ version bump.
90103| 400 | `bad_request` | The HTTP request line/path could not be parsed |
91104| 400 | `invalid_body` | `POST /inspect` body was not `{ "domain": "…" }` |
92105| 400 | `invalid_domain` | A path/body domain was empty or invalid |
106| 400 | `invalid_profile` | `profile` was present but named no known profile |
93107| 401 | `unauthorized` | Missing or incorrect token |
94108| 404 | `not_found` | No such route |
95109| 404 | `domain_not_found` | No local data / tracked domain for the given name |
DomainDig.xcodeproj/project.pbxproj +4
@@ -36,6 +36,7 @@
3636 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001201 /* HistoryStoreTests.swift */; };
3737 A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001401 /* SectionStateTests.swift */; };
3838 A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */; };
39 A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000001601 /* InspectionScopeTests.swift */; };
3940 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
4041 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
4142 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
@@ -119,6 +120,7 @@
119120 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryStoreTests.swift; sourceTree = "<group>"; };
120121 A1B2C3D40000000000001401 /* SectionStateTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = SectionStateTests.swift; sourceTree = "<group>"; };
121122 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>"; };
122124 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
123125 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
124126 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
@@ -267,6 +269,7 @@
267269 A1B2C3D40000000000001201 /* HistoryStoreTests.swift */,
268270 A1B2C3D40000000000001401 /* SectionStateTests.swift */,
269271 A1B2C3D40000000000001501 /* PortfolioDashboardTests.swift */,
272 A1B2C3D40000000000001601 /* InspectionScopeTests.swift */,
270273 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
271274 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
272275 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
@@ -540,6 +543,7 @@
540543 A1B2C3D40000000000001202 /* HistoryStoreTests.swift in Sources */,
541544 A1B2C3D40000000000001402 /* SectionStateTests.swift in Sources */,
542545 A1B2C3D40000000000001502 /* PortfolioDashboardTests.swift in Sources */,
546 A1B2C3D40000000000001602 /* InspectionScopeTests.swift in Sources */,
543547 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
544548 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
545549 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
DomainDig/DomainAvailabilityService.swift +5 −1
@@ -5,6 +5,7 @@ struct DomainAvailabilityService {
55
66 static func check(
77 domain: String,
8 allowsRDAP: Bool = true,
89 rdapTransport: RDAPTransport = URLSessionRDAPTransport(),
910 dns: DNSLookup = DNSLookupService()
1011 ) async -> DomainAvailabilityResult {
@@ -14,7 +15,10 @@ struct DomainAvailabilityService {
1415 }
1516
1617 // 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) {
1822 return DomainAvailabilityResult(domain: normalizedDomain, status: registryStatus)
1923 }
2024
DomainDig/DomainDigIntents.swift +4 −1
@@ -35,7 +35,10 @@ struct InspectDomainIntent: AppIntent {
3535 throw InspectDomainError.emptyDomain
3636 }
3737
38 let snapshot = await DomainInspectionService().inspectSnapshot(domain: requested)
38 let snapshot = await DomainInspectionService().inspectSnapshot(
39 domain: requested,
40 scope: .current()
41 )
3942 let report = DomainReportBuilder().build(from: snapshot)
4043
4144 let summary = Self.summaryText(for: report)
DomainDig/DomainMonitoringService.swift +5 −1
@@ -326,6 +326,9 @@ final class DomainMonitoringService {
326326 } else {
327327 notificationsAuthorized = false
328328 }
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()
329332 var results: [MonitoringDomainResult] = []
330333 var errors: [String] = []
331334 var alertsTriggered = 0
@@ -339,7 +342,8 @@ final class DomainMonitoringService {
339342 let previousSnapshot = latestSnapshot(for: trackedDomain, history: history)
340343 let inspectedSnapshot = await inspectionService.inspectSnapshot(
341344 domain: trackedDomain.domain,
342 previousSnapshot: previousSnapshot
345 previousSnapshot: previousSnapshot,
346 scope: monitoringScope
343347 )
344348 let snapshot = inspectedSnapshot.resolvedAfterFallback(to: previousSnapshot)
345349 // When the fallback fires, `snapshot` *is* `previousSnapshot`, so
DomainDig/DomainViewModel.swift +18 −6
@@ -1325,7 +1325,11 @@ final class DomainViewModel {
13251325 }
13261326
13271327 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 )
13291333 guard let entry = saveHistoryEntry(
13301334 from: snapshot,
13311335 replaceLatest: false,
@@ -1433,7 +1437,11 @@ final class DomainViewModel {
14331437 trackedDomainID: currentTrackedDomain?.id,
14341438 replacingLatest: false
14351439 )
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 )
14371445 DomainDebugLog.debug("DomainViewModel.performLookup inspectionReturned domain=\(domain)")
14381446 guard !Task.isCancelled, isCurrentLookup(lookupID) else { return nil }
14391447
@@ -1519,10 +1527,14 @@ final class DomainViewModel {
15191527 }
15201528 }
15211529
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? {
15231535 guard !Task.isCancelled else { return nil }
15241536 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)
15261538 guard !Task.isCancelled else { return nil }
15271539 return BatchLookupPayload(snapshot: snapshot.resolvedAfterFallback(to: previousSnapshot))
15281540 }
@@ -2141,8 +2153,8 @@ final class DomainViewModel {
21412153 updateBatchResult(domain: domain, status: .running, quickStatus: "Running", entry: nil, errorMessage: nil)
21422154 let previousSnapshot = previousSnapshot(for: domain, trackedDomainID: trackedDomain(for: domain)?.id, replacingLatest: false)
21432155
2144 group.addTask { [domain, previousSnapshot] in
2145 let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot)
2156 group.addTask { [domain, previousSnapshot, scope = InspectionScope.current(defaults: defaults)] in
2157 let payload = await Self.performBatchLookup(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
21462158 return (domain, payload)
21472159 }
21482160 }
DomainDig/InspectionScope.swift added +131
@@ -0,0 +1,131 @@
1import 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.
8nonisolated 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.
41nonisolated 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 {
6565 )
6666 }
6767
68 func availability(domain: String) async -> CachedLookupResult<DomainAvailabilityResult> {
68 func availability(domain: String, allowsRDAP: Bool) async -> CachedLookupResult<DomainAvailabilityResult> {
6969 CachedLookupResult(
70 value: await DomainAvailabilityService.check(domain: domain),
70 value: await DomainAvailabilityService.check(domain: domain, allowsRDAP: allowsRDAP),
7171 source: .live
7272 )
7373 }
DomainDig/SettingsViews.swift +29
@@ -141,10 +141,23 @@ private struct HistoryNetworkSettingsView: View {
141141 @Bindable var viewModel: DomainViewModel
142142 @AppStorage(DNSResolverOption.userDefaultsKey) private var storedResolverURL = DNSResolverOption.defaultURLString
143143 @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
144146
145147 @State private var resolverOption: DNSResolverOption = .cloudflare
146148 @State private var customResolverURL = DNSResolverOption.defaultURLString
147149
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
148161 private var customResolverError: String? {
149162 guard resolverOption == .custom else { return nil }
150163 return DNSResolverOption.isValidCustomURL(customResolverURL) ? nil : "Resolver URL must start with https://"
@@ -189,6 +202,22 @@ private struct HistoryNetworkSettingsView: View {
189202 .foregroundStyle(Color(.statusCritical))
190203 }
191204 }
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))
192221 }
193222 }
194223 .navigationTitle("History & Network")
DomainDigTests/AvailabilityTests.swift +63
@@ -141,6 +141,69 @@ final class DomainAvailabilityTests: XCTestCase {
141141 XCTAssertEqual(results.map(\.domain), ["example.net", "example.io"])
142142 XCTAssertEqual(results.map(\.status), [.available, .registered])
143143 }
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 }
144207}
145208
146209private final class StubRDAPTransport: RDAPTransport {
DomainDigTests/InspectionScopeTests.swift added +193
@@ -0,0 +1,193 @@
1import 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.
9final 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 {
88 self.runtime = runtime
99 }
1010
11 func inspect(domain: String, previousSnapshot: LookupSnapshot? = nil) async -> DomainReport {
12 let snapshot = await inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot)
11 func inspect(
12 domain: String,
13 previousSnapshot: LookupSnapshot? = nil,
14 scope: InspectionScope
15 ) async -> DomainReport {
16 let snapshot = await inspectSnapshot(domain: domain, previousSnapshot: previousSnapshot, scope: scope)
1317 return reportBuilder.build(from: snapshot)
1418 }
1519
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 {
1725 let normalizedDomain = normalize(domain)
1826 let inspectionStartedAt = DomainDebugLog.signpostStart("Inspection.inspectSnapshot", domain: normalizedDomain)
1927 let startedAt = Date()
2028 let resolverDisplayName = DNSLookupService.currentResolverDisplayName()
2129 let resolverURLString = DNSLookupService.currentResolverURLString()
22 var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName)
30 var ledger = InspectionLedger(resolverDisplayName: resolverDisplayName, scope: scope)
2331
2432 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)
2634 async let sslFetch = runtime.ssl(domain: normalizedDomain)
2735 async let hstsFetch = runtime.hsts(domain: normalizedDomain)
2836 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 }
3040 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 }
3244
3345 let resolvedDNS = await dnsFetch
3446 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=dns source=\(resolvedDNS.source.rawValue)")
@@ -59,8 +71,10 @@ struct DomainInspectionService {
5971 let resolvedOwnership = await ownershipFetch
6072 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=ownership source=\(resolvedOwnership.source.rawValue)")
6173 let ownershipResult = normalizeErrors(in: resolvedOwnership.value)
62 ledger.track(.ownership, source: resolvedOwnership.source)
63 ledger.captureFailure(for: .ownership, result: ownershipResult)
74 if scope.runs(.ownership) {
75 ledger.track(.ownership, source: resolvedOwnership.source)
76 ledger.captureFailure(for: .ownership, result: ownershipResult)
77 }
6478
6579 let redirects = await redirectFetch
6680 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=redirect source=\(redirects.source.rawValue)")
@@ -71,8 +85,10 @@ struct DomainInspectionService {
7185 let resolvedSubdomains = await subdomainFetch
7286 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=subdomains source=\(resolvedSubdomains.source.rawValue)")
7387 let subdomainResult = normalizeErrors(in: resolvedSubdomains.value)
74 ledger.track(.subdomains, source: resolvedSubdomains.source)
75 ledger.captureFailure(for: .subdomains, result: subdomainResult)
88 if scope.runs(.subdomains) {
89 ledger.track(.subdomains, source: resolvedSubdomains.source)
90 ledger.captureFailure(for: .subdomains, result: subdomainResult)
91 }
7692
7793 let dnsSections = mapServiceResult(dnsResult, emptyValue: [])
7894 let sslInfo = mapOptionalValueServiceResult(sslResult)
@@ -90,29 +106,37 @@ struct DomainInspectionService {
90106 let canReuseDNSDependents = canReuseDependentSections(from: previousSnapshot, dnsSections: dnsSections.value)
91107 let canReuseIPDependents = canReuseIPBasedSections(from: previousSnapshot, primaryIP: primaryIP)
92108
93 let reachabilityOutcome = await whenRoutable(hasNetworkTarget) {
94 await runtime.reachability(domain: normalizedDomain)
109 let reachabilityOutcome = await whenInScope(.reachability, scope) {
110 await whenRoutable(hasNetworkTarget) {
111 await runtime.reachability(domain: normalizedDomain)
112 }
95113 }
96114 let reachabilityResult = normalizeErrors(in: reachabilityOutcome.value)
97115 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=reachability hasNetworkTarget=\(hasNetworkTarget) source=\(reachabilityOutcome.source.rawValue)")
98 ledger.track(.reachability, source: reachabilityOutcome.source)
99 if hasNetworkTarget {
100 ledger.captureFailure(for: .reachability, result: reachabilityResult)
116 if scope.runs(.reachability) {
117 ledger.track(.reachability, source: reachabilityOutcome.source)
118 if hasNetworkTarget {
119 ledger.captureFailure(for: .reachability, result: reachabilityResult)
120 }
101121 }
102122 let reachabilityResultValue = mapServiceResult(reachabilityResult, emptyValue: [])
103123
104 let portScanOutcome = await whenRoutable(hasNetworkTarget) {
105 await runtime.portScan(domain: normalizedDomain)
124 let portScanOutcome = await whenInScope(.portScan, scope) {
125 await whenRoutable(hasNetworkTarget) {
126 await runtime.portScan(domain: normalizedDomain)
127 }
106128 }
107129 let portScanResult = normalizeErrors(in: portScanOutcome.value)
108130 DomainDebugLog.debug("Inspection.sectionComplete domain=\(normalizedDomain) section=portScan hasNetworkTarget=\(hasNetworkTarget) source=\(portScanOutcome.source.rawValue)")
109 ledger.track(.portScan, source: portScanOutcome.source)
110 if hasNetworkTarget {
111 ledger.captureFailure(for: .portScan, result: portScanResult)
131 if scope.runs(.portScan) {
132 ledger.track(.portScan, source: portScanOutcome.source)
133 if hasNetworkTarget {
134 ledger.captureFailure(for: .portScan, result: portScanResult)
135 }
112136 }
113 let portScanResults = hasNetworkTarget
137 let portScanResults = scope.runs(.portScan) && hasNetworkTarget
114138 ? await mapPortScanResult(portScanResult, domain: normalizedDomain)
115 : (value: [], message: nil)
139 : (value: [], message: scope.skipReason(for: .portScan))
116140
117141 let emailOutcome = await reusingPrevious(
118142 previousSnapshot?.emailSecurity,
@@ -127,7 +151,7 @@ struct DomainInspectionService {
127151 ledger.captureFailure(for: .emailSecurity, result: normalizedEmailResult)
128152
129153 let suggestionsOutcome: CachedLookupResult<[DomainSuggestionResult]>
130 if availability.value.status == .registered {
154 if scope.runs(.suggestions), availability.value.status == .registered {
131155 suggestionsOutcome = await runtime.suggestions(domain: normalizedDomain)
132156 ledger.track(.suggestions, source: suggestionsOutcome.source)
133157 } else {
@@ -144,17 +168,21 @@ struct DomainInspectionService {
144168 ) {
145169 await runtime.ptr(ip: primaryIP, resolverURLString: resolverURLString)
146170 }
147 let geo = await reusingPrevious(
148 previousSnapshot?.ipGeolocation,
149 error: previousSnapshot?.ipGeolocationError,
150 when: canReuseIPDependents
151 ) {
152 await runtime.ipGeolocation(ip: primaryIP)
171 let geo = await whenInScope(.ipGeolocation, scope) {
172 await reusingPrevious(
173 previousSnapshot?.ipGeolocation,
174 error: previousSnapshot?.ipGeolocationError,
175 when: canReuseIPDependents
176 ) {
177 await runtime.ipGeolocation(ip: primaryIP)
178 }
153179 }
154180 ledger.track(.ptr, source: ptr.source)
155181 ledger.captureFailure(for: .ptr, result: normalizeErrors(in: ptr.value))
156 ledger.track(.ipGeolocation, source: geo.source)
157 ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value))
182 if scope.runs(.ipGeolocation) {
183 ledger.track(.ipGeolocation, source: geo.source)
184 ledger.captureFailure(for: .ipGeolocation, result: normalizeErrors(in: geo.value))
185 }
158186 ptrOutcome = ptr
159187 geoOutcome = geo
160188 } else {
@@ -267,6 +295,16 @@ struct DomainInspectionService {
267295 .lowercased() ?? domain.lowercased()
268296 }
269297
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
270308 /// A lookup that needs an address to reach, or an empty result when the
271309 /// domain has none.
272310 private func whenRoutable<Value>(
@@ -300,7 +338,8 @@ struct DomainInspectionService {
300338 for section: LookupSectionKind,
301339 source: LookupResultSource,
302340 collectedAt: Date,
303 resolverDisplayName: String
341 resolverDisplayName: String,
342 allowsRDAP: Bool
304343 ) -> SectionProvenance {
305344 switch section {
306345 case .dns, .ptr:
@@ -313,9 +352,9 @@ struct DomainInspectionService {
313352 )
314353 case .availability:
315354 return SectionProvenance(
316 source: "RDAP lookup with DNS fallback",
355 source: allowsRDAP ? "RDAP lookup with DNS fallback" : "DNS query",
317356 collectedAt: collectedAt,
318 provider: "rdap.org / selected resolver",
357 provider: allowsRDAP ? "rdap.org / selected resolver" : "Selected DoH resolver",
319358 resolver: resolverDisplayName,
320359 resultSource: source
321360 )
@@ -590,6 +629,7 @@ struct DomainInspectionService {
590629/// from, which were served from cache, and which failed.
591630private struct InspectionLedger {
592631 let resolverDisplayName: String
632 let scope: InspectionScope
593633 var cachedSections = Set<LookupSectionKind>()
594634 var sectionSources: [LookupResultSource] = []
595635 var provenanceBySection: [LookupSectionKind: SectionProvenance] = [:]
@@ -601,7 +641,8 @@ private struct InspectionLedger {
601641 for: section,
602642 source: source,
603643 collectedAt: Date(),
604 resolverDisplayName: resolverDisplayName
644 resolverDisplayName: resolverDisplayName,
645 allowsRDAP: scope.allowsRDAP
605646 )
606647 sectionSources.append(source)
607648 provenanceBySection[section] = provenance
LocalAPIService.swift +24 −6
@@ -555,9 +555,15 @@ struct LocalAPIRequestHandler {
555555 case .monitoring:
556556 return successResponse(monitoringPayload())
557557 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)
559562 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)
561567 case let .setMonitoring(domain, enabled):
562568 return await setMonitoring(enabled: enabled, for: domain)
563569 }
@@ -609,22 +615,34 @@ struct LocalAPIRequestHandler {
609615 )
610616 }
611617
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 {
613627 guard let payload = try? decoder.decode(InspectRequestPayload.self, from: body) else {
614628 return .error(statusCode: 400, code: "invalid_body", message: "Expected JSON body: {\"domain\":\"example.com\"}.")
615629 }
616630
617 return await inspectResponse(for: payload.domain)
631 return await inspectResponse(for: payload.domain, scope: scope)
618632 }
619633
620 private func inspectResponse(for domain: String) async -> LocalAPIHTTPResponse {
634 private func inspectResponse(for domain: String, scope: InspectionScope) async -> LocalAPIHTTPResponse {
621635 let normalized = normalizedDomain(domain)
622636 guard !normalized.isEmpty else {
623637 return .error(statusCode: 400, code: "invalid_domain", message: "A valid domain is required.")
624638 }
625639
626640 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 )
628646 return successResponse(InspectResponsePayload(report: report))
629647 }
630648