Commit 66141c501b

66141c501bb283eb5a9c35ab0910c0a9d9748fc2

parent: 27e8825779

Unsigned

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

Fix three minor findings: C8, A14, A12 (!41)

Closes C8, A14 and A12, and records P3 as needing no change.

**C8 — the validator misreported an unencodable label as too long.** `URL`
refuses a host whose encoded label is over the limit without saying which label
it was, so `DomainName.validate` re-probes to tell "malformed" from "too long".
The probe looked at each label's first eight characters, so an unencodable
character after them made the label report `.labelTooLong`. It now asks per
character, which makes the position irrelevant. The orphaned
`probeLabelCharacters` is gone.

Still not a complete IDNA characterisation, and the comment says so: a label
refused for a combination its characters form, rather than for one of them,
still falls through to `.labelTooLong`. The input is rejected either way and
only the message differs. The test calibrates on whichever candidate scalar
Foundation actually refuses and skips if none does, rather than hard-coding one
— which scalars IDNA rejects is Foundation's business and moves between
releases.

**A14 — `nilIfEmpty` meant two different things.** Seven files declared a
private copy. Six were `isEmpty ? nil : self`; `DomainInsightEngine`'s trimmed
whitespace first, so `"   "` became nil there and stayed `"   "` everywhere
else. Three of the copies carried comments explaining that they could not be
shared *because* of this, which is the duplication the ambiguity caused.

The trimming one becomes `nilIfBlank` — the name `IntegrationsView` already
used for exactly those semantics — and both helpers now have a single copy in
`StringConveniences.swift`, with a note on which question each answers. The
apologetic comments go with the duplication. No call site changes meaning: each
one keeps the semantics it had.

**A12 — provenance came from storage, not from the lookup.** `currentSnapshot`
recovered it from the saved history entry, so it was empty until the snapshot
had been written and `currentHistoryEntryID` pointed at it. `performLookup`
saves immediately, so the live window was short — but a lookup that ends with a
status message returns *before* saving, so a partial or failed lookup showed no
source for any section, which is the case where knowing the source matters
most.

`applySnapshot` now builds an `InspectionMetadata` from the snapshot and
`currentSnapshot` prefers it, falling back to the saved entry when there is no
lookup in flight. It covers the sibling fields read the same way from the same
place — data sources, the five confidences, failures, partial/validation state
and the snapshot indices — because they had the identical defect on adjacent
lines. Cleared when a lookup starts and on reset, so a cleared screen does not
keep claiming a source.

`SectionStateTests` already had a test pinning the old behaviour with a message
asking to be updated when it changed. It now asserts the other direction,
through the same section slice the view consumes.

**P3 — credit ledger writes bypass the injected store.** No change needed: D2
deleted the meter and no `UsageCredit` symbol remains in the tree. Recorded as
closed by that deletion rather than fixed.

4 new tests, 334 green on iOS 18.6 and 27.0. Ratchet unchanged at 280.

Not in this MR: C9, which needs UI-test coverage and its own run, and I1, which
names two layout idioms without saying which should win — restyling either
Inspect or Dashboard is a visible design decision rather than a cleanup.

Layout: unified · split

DomainDig/DomainDataPortabilityService.swift −5
@@ -1639,8 +1639,3 @@ private enum ImportPayload {
16391639 }
16401640}
16411641
1642private extension String {
1643 var nilIfEmpty: String? {
1644 isEmpty ? nil : self
1645 }
1646}
DomainDig/DomainInsightEngine.swift +4 −8
@@ -133,18 +133,18 @@ enum DomainInsightEngine {
133133 title: "Shared nameserver set detected",
134134 groups: groupedDomains(for: reports) {
135135 let value = $0.ownership?.nameservers.sorted().joined(separator: "|")
136 return value?.nilIfEmpty
136 return value?.nilIfBlank
137137 },
138138 into: &insights
139139 )
140140 appendSharedInsights(
141141 title: "Shared registrar detected",
142 groups: groupedDomains(for: reports) { $0.ownership?.registrar?.nilIfEmpty },
142 groups: groupedDomains(for: reports) { $0.ownership?.registrar?.nilIfBlank },
143143 into: &insights
144144 )
145145 appendSharedInsights(
146146 title: "Shared TLS issuer detected",
147 groups: groupedDomains(for: reports) { $0.web.tls?.issuer.nilIfEmpty },
147 groups: groupedDomains(for: reports) { $0.web.tls?.issuer.nilIfBlank },
148148 into: &insights
149149 )
150150
@@ -537,7 +537,7 @@ enum DomainInsightEngine {
537537 for reports: [DomainReport],
538538 keyPath: KeyPath<DomainReport, String?>
539539 ) -> [String: [String]] {
540 groupedDomains(for: reports) { $0[keyPath: keyPath]?.nilIfEmpty }
540 groupedDomains(for: reports) { $0[keyPath: keyPath]?.nilIfBlank }
541541 }
542542
543543 private static func groupedDomains(
@@ -554,8 +554,4 @@ enum DomainInsightEngine {
554554}
555555
556556private extension String {
557 var nilIfEmpty: String? {
558 let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
559 return trimmed.isEmpty ? nil : trimmed
560 }
561557}
DomainDig/DomainName.swift +23 −7
@@ -15,7 +15,6 @@ import Foundation
1515enum DomainName {
1616 private static let maximumLabelBytes = 63
1717 private static let maximumHostBytes = 253
18 private static let probeLabelCharacters = 8
1918
2019 /// The normalized host on success. A Unicode host is returned as typed; only
2120 /// the length limits are measured on its IDNA-encoded form.
@@ -40,12 +39,24 @@ enum DomainName {
4039 // The limits apply to the encoded host, which is what the section
4140 // services send, so they are measured on the punycode form.
4241 guard let encoded = DomainHostURL.https(host)?.host else {
43 // `URL` refuses a host whose encoded label is over the limit instead
44 // of reporting which label it was, so the labels are re-encoded one
45 // at a time: a label that will not encode even truncated to
46 // `probeLabelCharacters` (short enough that it cannot reach the
47 // limit whatever it encodes to) is malformed rather than too long.
48 if let malformed = labels.first(where: { !canEncode(String($0.prefix(probeLabelCharacters))) }) {
42 // `URL` refuses a host whose encoded label is over the limit
43 // instead of reporting which label it was, so the two reasons are
44 // told apart here: a label holding a character that will not encode
45 // on its own is malformed, and anything else that will not encode is
46 // too long.
47 //
48 // Probing per character rather than per prefix is what makes the
49 // position irrelevant. The earlier version probed the label's first
50 // few characters, so an unencodable character after them was
51 // reported as merely too long.
52 //
53 // Not a complete IDNA characterisation: a label refused for a
54 // combination its characters form, rather than for one of them,
55 // still falls through to `.labelTooLong`. The input is rejected
56 // either way and only the message differs.
57 if let malformed = labels.first(where: { label in
58 label.contains { !canEncode(String($0)) }
59 }) {
4960 return .failure(.malformedLabel(malformed))
5061 }
5162 return .failure(.labelTooLong)
@@ -97,6 +108,11 @@ enum DomainName {
97108 return character.isLetter || character.isNumber || character == "-" || character == "."
98109 }
99110
111 /// Whether `label` encodes at all, independent of length.
112 ///
113 /// An all-ASCII label always does, so only non-ASCII input reaches the
114 /// probe. Callers pass a single character to ask whether that character is
115 /// encodable anywhere in a label.
100116 private static func canEncode(_ label: String) -> Bool {
101117 guard label.contains(where: { !$0.isASCII }) else { return true }
102118 // The ASCII suffix keeps the probe a two-label host.
DomainDig/DomainReportExporter.swift −5
@@ -819,8 +819,3 @@ enum DomainReportExporter {
819819 }
820820}
821821
822private extension String {
823 var nilIfEmpty: String? {
824 isEmpty ? nil : self
825 }
826}
DomainDig/DomainViewModel+Export.swift −9
@@ -564,12 +564,3 @@ extension DomainViewModel {
564564 }
565565}
566566
567// Deliberately a private copy rather than a shared one. `nilIfEmpty` means two
568// different things in this codebase: DomainInsightEngine's trims whitespace
569// first, every other copy does not. The exporters moved here were using the
570// non-trimming version, so that is what they keep (A14).
571private extension String {
572 var nilIfEmpty: String? {
573 isEmpty ? nil : self
574 }
575}
DomainDig/DomainViewModel+Workflows.swift −5
@@ -137,8 +137,3 @@ extension DomainViewModel {
137137 }
138138}
139139
140private extension String {
141 var nilIfEmpty: String? {
142 isEmpty ? nil : self
143 }
144}
DomainDig/DomainViewModel.swift +19 −26
@@ -268,6 +268,10 @@ final class DomainViewModel {
268268 private(set) var currentStatusMessage: String?
269269 private(set) var currentSnapshotTimestamp = Date()
270270 private(set) var currentHistoryEntryID: UUID?
271 /// The metadata the current lookup produced, in preference to whatever the
272 /// saved entry holds. Nil outside a lookup, when the saved entry is the
273 /// only source there is.
274 private(set) var currentInspectionMetadata: InspectionMetadata?
271275 private(set) var currentReport: DomainReport?
272276
273277 private static let recentSearchesKey = "recentSearches"
@@ -582,19 +586,19 @@ final class DomainViewModel {
582586 appVersion: AppVersion.current,
583587 resolverDisplayName: resolverDisplayName,
584588 resolverURLString: resolverURLString,
585 dataSources: currentHistoryEntry?.dataSources ?? [],
586 provenanceBySection: currentHistoryEntry?.provenanceBySection ?? [:],
587 availabilityConfidence: currentHistoryEntry?.availabilityConfidence,
588 ownershipConfidence: currentHistoryEntry?.ownershipConfidence,
589 subdomainConfidence: currentHistoryEntry?.subdomainConfidence,
590 emailSecurityConfidence: currentHistoryEntry?.emailSecurityConfidence,
591 geolocationConfidence: currentHistoryEntry?.geolocationConfidence,
592 errorDetails: currentHistoryEntry?.errorDetails ?? [:],
593 isPartialSnapshot: currentHistoryEntry?.isPartialSnapshot ?? false,
594 validationIssues: currentHistoryEntry?.validationIssues ?? [],
589 dataSources: currentInspectionMetadata?.dataSources ?? currentHistoryEntry?.dataSources ?? [],
590 provenanceBySection: currentInspectionMetadata?.provenanceBySection ?? currentHistoryEntry?.provenanceBySection ?? [:],
591 availabilityConfidence: currentInspectionMetadata?.availabilityConfidence ?? currentHistoryEntry?.availabilityConfidence,
592 ownershipConfidence: currentInspectionMetadata?.ownershipConfidence ?? currentHistoryEntry?.ownershipConfidence,
593 subdomainConfidence: currentInspectionMetadata?.subdomainConfidence ?? currentHistoryEntry?.subdomainConfidence,
594 emailSecurityConfidence: currentInspectionMetadata?.emailSecurityConfidence ?? currentHistoryEntry?.emailSecurityConfidence,
595 geolocationConfidence: currentInspectionMetadata?.geolocationConfidence ?? currentHistoryEntry?.geolocationConfidence,
596 errorDetails: currentInspectionMetadata?.errorDetails ?? currentHistoryEntry?.errorDetails ?? [:],
597 isPartialSnapshot: currentInspectionMetadata?.isPartialSnapshot ?? currentHistoryEntry?.isPartialSnapshot ?? false,
598 validationIssues: currentInspectionMetadata?.validationIssues ?? currentHistoryEntry?.validationIssues ?? [],
595599 totalLookupDurationMs: lastLookupDurationMs,
596 snapshotIndex: currentHistoryEntry?.snapshotIndex,
597 previousSnapshotID: currentHistoryEntry?.previousSnapshotID,
600 snapshotIndex: currentInspectionMetadata?.snapshotIndex ?? currentHistoryEntry?.snapshotIndex,
601 previousSnapshotID: currentInspectionMetadata?.previousSnapshotID ?? currentHistoryEntry?.previousSnapshotID,
598602 changeCount: currentHistoryEntry?.changeCount ?? currentChangeSummary?.changedSections.count ?? 0,
599603 severitySummary: currentHistoryEntry?.severitySummary ?? currentChangeSummary?.severity,
600604 dnsSections: dnsSections,
@@ -1477,6 +1481,7 @@ final class DomainViewModel {
14771481 /// Internal so the tests that pin what each section ends up showing can
14781482 /// reach it without a live lookup.
14791483 func applySnapshot(_ snapshot: LookupSnapshot) {
1484 currentInspectionMetadata = InspectionMetadata(snapshot: snapshot)
14801485 currentHistoryEntryID = snapshot.historyEntryID
14811486 currentSnapshotTimestamp = snapshot.timestamp
14821487 currentResultSource = snapshot.resultSource
@@ -2040,6 +2045,7 @@ final class DomainViewModel {
20402045 searchedDomain = target
20412046 hasRun = true
20422047 currentHistoryEntryID = nil
2048 currentInspectionMetadata = nil
20432049 currentSnapshotTimestamp = Date()
20442050 currentResultSource = .live
20452051 currentCachedSections = []
@@ -2330,6 +2336,7 @@ final class DomainViewModel {
23302336 /// results cannot be mistaken for this one's. One assignment per section
23312337 /// now; it used to be three.
23322338 private func clearLookupState() {
2339 currentInspectionMetadata = nil
23332340 dnsState = .idle
23342341 availabilityState = .idle
23352342 suggestionsState = .idle
@@ -3400,17 +3407,3 @@ final class DomainViewModel {
34003407 }
34013408}
34023409
3403// Private, and not shared with the identically named helpers elsewhere:
3404// DomainInsightEngine's `nilIfEmpty` trims whitespace first and these do not,
3405// so one internal version would quietly change behaviour there (A14).
3406private extension String {
3407 var nilIfEmpty: String? {
3408 isEmpty ? nil : self
3409 }
3410}
3411
3412private extension Array where Element == String {
3413 var nilIfEmpty: [String]? {
3414 isEmpty ? nil : self
3415 }
3416}
DomainDig/IntegrationsView.swift −4
@@ -706,8 +706,4 @@ private struct IntegrationEditorView: View {
706706}
707707
708708private extension String {
709 var nilIfBlank: String? {
710 let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
711 return trimmed.isEmpty ? nil : trimmed
712 }
713709}
DomainDig/LookupSnapshot.swift +40
@@ -282,3 +282,43 @@ extension LookupSnapshot {
282282 )
283283 }
284284}
285
286/// The metadata one inspection produced: where each section came from, how
287/// confident it is, what failed, and whether the result is partial.
288///
289/// `DomainViewModel.currentSnapshot` used to recover all of this from the
290/// *saved history entry*, so it was empty until the snapshot had been written
291/// and `currentHistoryEntryID` pointed at it. Two consequences, both fixed by
292/// carrying it from the lookup instead: the cards rendered without provenance
293/// between applying a snapshot and saving it, and a lookup that returns before
294/// saving — any partial or failed one — showed no provenance for any section,
295/// which is the case where knowing the source matters most (A12).
296struct InspectionMetadata: Equatable {
297 var dataSources: [String]
298 var provenanceBySection: [LookupSectionKind: SectionProvenance]
299 var availabilityConfidence: ConfidenceLevel?
300 var ownershipConfidence: ConfidenceLevel?
301 var subdomainConfidence: ConfidenceLevel?
302 var emailSecurityConfidence: ConfidenceLevel?
303 var geolocationConfidence: ConfidenceLevel?
304 var errorDetails: [LookupSectionKind: InspectionFailure]
305 var isPartialSnapshot: Bool
306 var validationIssues: [String]
307 var snapshotIndex: Int?
308 var previousSnapshotID: UUID?
309
310 init(snapshot: LookupSnapshot) {
311 dataSources = snapshot.dataSources
312 provenanceBySection = snapshot.provenanceBySection
313 availabilityConfidence = snapshot.availabilityConfidence
314 ownershipConfidence = snapshot.ownershipConfidence
315 subdomainConfidence = snapshot.subdomainConfidence
316 emailSecurityConfidence = snapshot.emailSecurityConfidence
317 geolocationConfidence = snapshot.geolocationConfidence
318 errorDetails = snapshot.errorDetails
319 isPartialSnapshot = snapshot.isPartialSnapshot
320 validationIssues = snapshot.validationIssues
321 snapshotIndex = snapshot.snapshotIndex
322 previousSnapshotID = snapshot.previousSnapshotID
323 }
324}
DomainDig/ResultPrimitives.swift −5
@@ -284,11 +284,6 @@ extension View {
284284 }
285285}
286286
287private extension String {
288 var nilIfEmpty: String? {
289 isEmpty ? nil : self
290 }
291}
292287
293288extension ChangeImpactClassification {
294289 var tone: AppStatusTone {
DomainDig/StringConveniences.swift added +32
@@ -0,0 +1,32 @@
1import Foundation
2
3/// Two different questions, with two names.
4///
5/// Seven files used to declare a private `nilIfEmpty`, and one of them —
6/// `DomainInsightEngine` — trimmed whitespace first while the rest did not, so
7/// the same name meant two things and nothing could be shared (A14). Naming the
8/// trimming one `nilIfBlank` separates them, which is what lets there be one
9/// copy of each.
10extension String {
11 /// `nil` when there is nothing at all, keeping a string of spaces.
12 ///
13 /// For values already normalised upstream, where whitespace would be
14 /// content rather than noise.
15 var nilIfEmpty: String? {
16 isEmpty ? nil : self
17 }
18
19 /// `nil` when there is nothing but whitespace, and trimmed otherwise.
20 ///
21 /// For values straight from a text field or an imported row.
22 var nilIfBlank: String? {
23 let trimmed = trimmingCharacters(in: .whitespacesAndNewlines)
24 return trimmed.isEmpty ? nil : trimmed
25 }
26}
27
28extension Array where Element == String {
29 var nilIfEmpty: [String]? {
30 isEmpty ? nil : self
31 }
32}
DomainDigTests/DomainNameTests.swift +27
@@ -77,6 +77,33 @@ final class DomainNameTests: XCTestCase {
7777 )
7878 }
7979
80 /// C8: the probe used to look only at a label's first few characters, so
81 /// an unencodable character sitting after them reported `.labelTooLong`
82 /// instead of `.malformedLabel`.
83 ///
84 /// Calibrated on the character rather than hard-coded, because which
85 /// scalars IDNA refuses is Foundation's business and moves between
86 /// releases. If none of the candidates is refused, there is nothing to
87 /// assert on this runtime.
88 func testAnUnencodableCharacterIsMalformedWhereverItSitsInTheLabel() throws {
89 let candidates = ["\u{200B}", "\u{FFFF}", "\u{2E2F}", "\u{1D173}"]
90 guard let unencodable = candidates.first(where: { character in
91 DomainName.validate("\(character).com") == .failure(.malformedLabel(character))
92 }) else {
93 throw XCTSkip("no IDNA-unencodable character among the candidates on this runtime")
94 }
95
96 // Far enough in that the old eight-character prefix probe missed it,
97 // and short enough that the label cannot be over the byte limit.
98 let label = String(repeating: "a", count: 20) + unencodable
99
100 XCTAssertEqual(
101 DomainName.validate("\(label).com"),
102 .failure(.malformedLabel(label)),
103 "an unencodable character past the probe length still makes the label malformed"
104 )
105 }
106
80107 func testAcceptsAUnicodeHost() {
81108 XCTAssertEqual(DomainName.validate("münchen.de"), .success("münchen.de"))
82109 }
DomainDigTests/Fixtures/SnapshotFixture.swift +2 −1
@@ -272,12 +272,13 @@ enum SnapshotFixture {
272272
273273 static func provenance(
274274 source: String = "test",
275 provider: String? = nil,
275276 resultSource: LookupResultSource = .live
276277 ) -> SectionProvenance {
277278 SectionProvenance(
278279 source: source,
279280 collectedAt: referenceDate,
280 provider: nil,
281 provider: provider,
281282 resolver: nil,
282283 resultSource: resultSource
283284 )
DomainDigTests/SectionStateTests.swift +55 −17
@@ -47,6 +47,51 @@ final class SectionStateTests: XCTestCase {
4747 /// Starting a lookup puts every section in flight; applying a snapshot
4848 /// takes them all out of it. Nothing may be left loading, or the section
4949 /// spins forever.
50 // MARK: Provenance (A12)
51
52 /// Provenance used to be recovered from the saved history entry, so it was
53 /// empty until the snapshot had been written. It now comes from the
54 /// snapshot itself, which is visible here because nothing is saved.
55 func testProvenanceIsAvailableBeforeTheSnapshotIsSaved() {
56 let viewModel = makeViewModel()
57 let provenance = SnapshotFixture.provenance(source: "DNS-over-HTTPS query", provider: "Selected DoH resolver")
58
59 viewModel.applySnapshot(
60 SnapshotFixture.snapshot(provenanceBySection: [.dns: provenance])
61 )
62
63 XCTAssertNil(viewModel.currentHistoryEntryID, "nothing should have been saved")
64 XCTAssertEqual(viewModel.currentSnapshot.provenanceBySection[.dns], provenance)
65 }
66
67 /// The case the finding called out: a lookup that ends with a status
68 /// message returns before saving, so this was the state in which every
69 /// section showed no source at all.
70 func testProvenanceSurvivesASnapshotThatWouldNotBeSaved() {
71 let viewModel = makeViewModel()
72 let provenance = SnapshotFixture.provenance(source: "RDAP domain lookup", provider: "rdap.org")
73
74 viewModel.applySnapshot(
75 SnapshotFixture.snapshot(provenanceBySection: [.ownership: provenance])
76 )
77
78 XCTAssertEqual(viewModel.currentSnapshot.provenanceBySection[.ownership], provenance)
79 XCTAssertEqual(viewModel.currentSnapshot.provenanceBySection.count, 1)
80 }
81
82 /// Reset drops it, so a cleared screen does not keep claiming a source.
83 func testResetClearsTheInspectionMetadata() {
84 let viewModel = makeViewModel()
85 viewModel.applySnapshot(
86 SnapshotFixture.snapshot(provenanceBySection: [.dns: SnapshotFixture.provenance()])
87 )
88 XCTAssertFalse(viewModel.currentSnapshot.provenanceBySection.isEmpty)
89
90 viewModel.reset()
91
92 XCTAssertTrue(viewModel.currentSnapshot.provenanceBySection.isEmpty)
93 }
94
5095 func testApplyingASnapshotSettlesEverySection() {
5196 let viewModel = makeViewModel()
5297 _ = viewModel.beginLookup(for: "example.com")
@@ -195,29 +240,22 @@ final class SectionStateTests: XCTestCase {
195240
196241 // MARK: Provenance
197242
198 /// Provenance does not come from the snapshot that was just applied.
199 /// `currentSnapshot` reads it from the saved history entry
200 /// (`DomainViewModel:623`), and `applySnapshot` stores it nowhere — so
201 /// between applying and saving, and on a lookup that ends with a status
202 /// message and is therefore never saved, the cards show no provenance at
203 /// all. Recorded as A12.
243 /// Provenance now comes from the snapshot that was just applied, which is
244 /// A12 closed. It used to be recovered from the saved history entry, so
245 /// between applying and saving — and on a lookup that ends with a status
246 /// message and is therefore never saved — the cards showed none at all.
204247 ///
205 /// This pins the behaviour as it is rather than as it should be, so that
206 /// A2's collapse can carry provenance with the section state and change
207 /// this test deliberately.
208 func testProvenanceIsNotCarriedByTheAppliedSnapshot() {
248 /// This asserts through the section slice the view consumes, which is what
249 /// the earlier version of this test pinned in the opposite direction.
250 func testTheAppliedSnapshotCarriesProvenanceToTheSection() {
209251 let viewModel = makeViewModel()
252 let provenance = SnapshotFixture.provenance(source: "Direct TLS handshake", provider: "Target host")
210253
211254 viewModel.applySnapshot(
212 SnapshotFixture.snapshot(
213 provenanceBySection: [.ssl: SnapshotFixture.provenance(source: "test")]
214 )
255 SnapshotFixture.snapshot(provenanceBySection: [.ssl: provenance])
215256 )
216257
217 XCTAssertNil(
218 viewModel.webSectionData.tls.provenance,
219 "provenance now survives applySnapshot — update this test and close A12"
220 )
258 XCTAssertEqual(viewModel.webSectionData.tls.provenance, provenance)
221259 }
222260
223261 // MARK: A second lookup clears the first one's results