Validate the domain input before starting a lookup !8

merged merged by cmc on 2026-10-24 04:10 UTC · krz/domain-dig:domain-validation into main

5 files changed, +292 −5

Layout: unified · split

DomainDig.xcodeproj/project.pbxproj +4
@@ -29,6 +29,7 @@
29 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; }; 29 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; };
30 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; }; 30 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
31 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; }; 31 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */; };
32 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000501 /* DomainNameTests.swift */; };
32 EA12012CDB4C21ABB4217D86 /* LocalAPIContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D85A44C5F315A1644AC9073 /* LocalAPIContractTests.swift */; }; 33 EA12012CDB4C21ABB4217D86 /* LocalAPIContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D85A44C5F315A1644AC9073 /* LocalAPIContractTests.swift */; };
33/* End PBXBuildFile section */ 34/* End PBXBuildFile section */
34 35
@@ -102,6 +103,7 @@
102 A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; }; 103 A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; };
103 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; }; 104 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
104 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; }; 105 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = CloudSyncMergeTests.swift; sourceTree = "<group>"; };
106 A1B2C3D40000000000000501 /* DomainNameTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainNameTests.swift; sourceTree = "<group>"; };
105 A77F7ED29E7C6669F5E61C04 /* DomainDigTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DomainDigTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 107 A77F7ED29E7C6669F5E61C04 /* DomainDigTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DomainDigTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
106 CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityServiceTests.swift; sourceTree = "<group>"; }; 108 CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityServiceTests.swift; sourceTree = "<group>"; };
107 DE8B269A01CC5E593DA3DFC2 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS26.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; 109 DE8B269A01CC5E593DA3DFC2 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS26.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; };
@@ -242,6 +244,7 @@
242 A1B2C3D40000000000000201 /* InspectionInputTests.swift */, 244 A1B2C3D40000000000000201 /* InspectionInputTests.swift */,
243 A1B2C3D40000000000000301 /* AvailabilityTests.swift */, 245 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
244 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */, 246 A1B2C3D40000000000000401 /* CloudSyncMergeTests.swift */,
247 A1B2C3D40000000000000501 /* DomainNameTests.swift */,
245 ); 248 );
246 path = DomainDigTests; 249 path = DomainDigTests;
247 sourceTree = "<group>"; 250 sourceTree = "<group>";
@@ -505,6 +508,7 @@
505 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */, 508 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */,
506 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */, 509 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
507 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */, 510 A1B2C3D40000000000000402 /* CloudSyncMergeTests.swift in Sources */,
511 A1B2C3D40000000000000502 /* DomainNameTests.swift in Sources */,
508 ); 512 );
509 runOnlyForDeploymentPostprocessing = 0; 513 runOnlyForDeploymentPostprocessing = 0;
510 }; 514 };
DomainDig/ContentView.swift +8
@@ -214,6 +214,7 @@ struct ContentView: View {
214 focusedInputField = newValue == .single ? .singleDomain : .bulkDomains 214 focusedInputField = newValue == .single ? .singleDomain : .bulkDomains
215 } 215 }
216 .onChange(of: viewModel.domain) { _, newValue in 216 .onChange(of: viewModel.domain) { _, newValue in
217 viewModel.domainInputError = nil
217 guard inputMode == .single else { return } 218 guard inputMode == .single else { return }
218 let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines) 219 let normalized = newValue.trimmingCharacters(in: .whitespacesAndNewlines)
219 guard normalized != viewModel.searchedDomain else { return } 220 guard normalized != viewModel.searchedDomain else { return }
@@ -318,6 +319,13 @@ struct ContentView: View {
318 viewModel.run() 319 viewModel.run()
319 } 320 }
320 321
322 if let domainInputError = viewModel.domainInputError {
323 Text(domainInputError)
324 .font(appDensity.font(.caption))
325 .foregroundStyle(Color(.statusCritical))
326 .frame(maxWidth: .infinity, alignment: .leading)
327 }
328
321 Button { 329 Button {
322 focusedInputField = nil 330 focusedInputField = nil
323 viewModel.run() 331 viewModel.run()
DomainDig/DomainName.swift added +137
@@ -0,0 +1,137 @@
1import Foundation
2
3/// Validation for the inspected domain, applied at the two input boundaries:
4/// `DomainViewModel.run()` and the bulk paste field.
5///
6/// Nothing downstream routes through this. `DomainViewModel.normalizedDomain` is
7/// the key that matches already-stored rows, and the import and automation paths
8/// accept whatever is already on disk, so tightening those would turn tracking,
9/// workflow lookups and imports into silent no-ops for any stored domain these
10/// rules reject.
11///
12/// The invariant runs one way: everything `validate` accepts can be built into a
13/// request URL by `DomainHostURL`. The reverse does not hold — `-x.com` forms a
14/// URL and is still rejected here.
15enum DomainName {
16 private static let maximumLabelBytes = 63
17 private static let maximumHostBytes = 253
18 private static let probeLabelCharacters = 8
19
20 /// The normalized host on success. A Unicode host is returned as typed; only
21 /// the length limits are measured on its IDNA-encoded form.
22 static func validate(_ raw: String) -> Result<String, DomainNameError> {
23 let host = normalize(raw)
24 guard !host.isEmpty else { return .failure(.empty) }
25
26 // `%`-escapes are rejected rather than decoded: `DomainHostURL` reads
27 // `https://ex%20ample.com` as host `ex ample.com`, so decoding here
28 // would hand the sections a host with a space in it.
29 if let invalid = host.first(where: { !isHostCharacter($0) }) {
30 return .failure(.invalidCharacter(invalid))
31 }
32
33 let labels = host.components(separatedBy: ".")
34 guard labels.count > 1 else { return .failure(.singleLabel) }
35
36 if let malformed = labels.first(where: { $0.isEmpty || $0.first == "-" || $0.last == "-" }) {
37 return .failure(.malformedLabel(malformed))
38 }
39
40 // The limits apply to the encoded host, which is what the section
41 // services send, so they are measured on the punycode form.
42 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))) }) {
49 return .failure(.malformedLabel(malformed))
50 }
51 return .failure(.labelTooLong)
52 }
53
54 guard encoded.components(separatedBy: ".").allSatisfy({ $0.utf8.count <= maximumLabelBytes }) else {
55 return .failure(.labelTooLong)
56 }
57 guard encoded.utf8.count <= maximumHostBytes else { return .failure(.tooLong) }
58
59 return .success(host)
60 }
61
62 private static func normalize(_ raw: String) -> String {
63 var host = raw.trimmingCharacters(in: .whitespacesAndNewlines)
64
65 if let separator = host.range(of: "://"), isScheme(host[..<separator.lowerBound]) {
66 host = String(host[separator.upperBound...])
67 }
68
69 // A query can follow the host with no path at all: `example.com?q=1`.
70 host = String(host.prefix { $0 != "/" && $0 != "?" })
71
72 if let userInfo = host.lastIndex(of: "@") {
73 host = String(host[host.index(after: userInfo)...])
74 }
75 if let port = host.lastIndex(of: ":") {
76 host = String(host[..<port])
77 }
78 if host.hasSuffix(".") {
79 host.removeLast()
80 }
81
82 // NFC so a decomposed "ü" measures the same as a precomposed one.
83 return host.lowercased().precomposedStringWithCanonicalMapping
84 }
85
86 private static func isScheme(_ candidate: Substring) -> Bool {
87 guard let first = candidate.first, first.isASCII, first.isLetter else { return false }
88 return candidate.allSatisfy { character in
89 character.isASCII && (character.isLetter || character.isNumber || "+-.".contains(character))
90 }
91 }
92
93 /// Non-ASCII is left to IDNA; whatever it cannot encode fails the
94 /// `DomainHostURL` guard in `validate`.
95 private static func isHostCharacter(_ character: Character) -> Bool {
96 guard character.isASCII else { return !character.isWhitespace }
97 return character.isLetter || character.isNumber || character == "-" || character == "."
98 }
99
100 private static func canEncode(_ label: String) -> Bool {
101 guard label.contains(where: { !$0.isASCII }) else { return true }
102 // The ASCII suffix keeps the probe a two-label host.
103 return DomainHostURL.https("\(label).test") != nil
104 }
105}
106
107enum DomainNameError: LocalizedError, Equatable {
108 case empty
109 case singleLabel
110 case invalidCharacter(Character)
111 case malformedLabel(String)
112 case labelTooLong
113 case tooLong
114
115 var errorDescription: String? {
116 switch self {
117 case .empty:
118 return "Enter a domain to inspect."
119 case .singleLabel:
120 return "Enter a full domain, such as example.com."
121 case .invalidCharacter(let character):
122 if character.isWhitespace {
123 return "A domain cannot contain spaces."
124 }
125 return "A domain cannot contain \(character)."
126 case .malformedLabel(let label):
127 if label.isEmpty {
128 return "A domain cannot contain an empty part."
129 }
130 return "\(label) is not a valid part of a domain name."
131 case .labelTooLong:
132 return "Each part of a domain can be at most 63 bytes."
133 case .tooLong:
134 return "A domain can be at most 253 bytes."
135 }
136 }
137}
DomainDig/DomainViewModel.swift +13 −5
@@ -175,6 +175,7 @@ private struct PortfolioDashboardStamp: Equatable {
175final class DomainViewModel { 175final class DomainViewModel {
176 var domain: String = "" 176 var domain: String = ""
177 var bulkInput: String = "" 177 var bulkInput: String = ""
178 var domainInputError: String?
178 179
179 var dnsSections: [DNSSection] = [] 180 var dnsSections: [DNSSection] = []
180 var dnsLoading = false 181 var dnsLoading = false
@@ -1138,8 +1139,16 @@ final class DomainViewModel {
1138 } 1139 }
1139 1140
1140 func run() { 1141 func run() {
1141 let target = trimmedDomain 1142 let target: String
1142 guard !target.isEmpty else { return } 1143 switch DomainName.validate(trimmedDomain) {
1144 case .success(let host):
1145 target = host
1146 domainInputError = nil
1147 case .failure(let error):
1148 domainInputError = error.localizedDescription
1149 return
1150 }
1151
1143 clearBatchState() 1152 clearBatchState()
1144 let lookupID = beginLookup(for: target) 1153 let lookupID = beginLookup(for: target)
1145 1154
@@ -2166,13 +2175,12 @@ final class DomainViewModel {
2166 } 2175 }
2167 2176
2168 private func parsedDomains(from input: String) -> [String] { 2177 private func parsedDomains(from input: String) -> [String] {
2169 let separators = CharacterSet(charactersIn: ",\n") 2178 let separators = CharacterSet(charactersIn: ",").union(.whitespacesAndNewlines)
2170 var seen = Set<String>() 2179 var seen = Set<String>()
2171 2180
2172 return input 2181 return input
2173 .components(separatedBy: separators) 2182 .components(separatedBy: separators)
2174 .map(normalizedDomain) 2183 .compactMap { try? DomainName.validate($0).get() }
2175 .filter { !$0.isEmpty }
2176 .filter { seen.insert($0).inserted } 2184 .filter { seen.insert($0).inserted }
2177 } 2185 }
2178 2186
DomainDigTests/DomainNameTests.swift added +130
@@ -0,0 +1,130 @@
1import XCTest
2@testable import DomainDig
3
4/// `run()` used to hand anything non-empty to 14 section services, which each
5/// reported their own network error for input that was never a domain. These pin
6/// the input-boundary validator that answers before the lookup starts.
7final class DomainNameTests: XCTestCase {
8
9 func testAcceptsAPlainHost() {
10 XCTAssertEqual(DomainName.validate("example.com"), .success("example.com"))
11 }
12
13 func testLowercasesAndTrims() {
14 XCTAssertEqual(DomainName.validate(" EXAMPLE.COM\n"), .success("example.com"))
15 }
16
17 func testStripsSchemeAndPath() {
18 XCTAssertEqual(DomainName.validate("https://example.com/path?q=1"), .success("example.com"))
19 }
20
21 func testStripsAPort() {
22 XCTAssertEqual(DomainName.validate("example.com:8443"), .success("example.com"))
23 }
24
25 func testStripsUserInfo() {
26 XCTAssertEqual(DomainName.validate("user:pass@example.com"), .success("example.com"))
27 }
28
29 func testStripsAQueryWithNoPath() {
30 XCTAssertEqual(DomainName.validate("example.com?q=1"), .success("example.com"))
31 }
32
33 func testRejectsASingleLabel() {
34 XCTAssertEqual(DomainName.validate("localhost"), .failure(.singleLabel))
35 }
36
37 func testRejectsAnInteriorSpace() {
38 XCTAssertEqual(DomainName.validate("exa mple.com"), .failure(.invalidCharacter(" ")))
39 }
40
41 /// `DomainHostURL` decodes escapes, so it reads `https://ex%20ample.com` as
42 /// host `ex ample.com` and forms a URL no section service can resolve.
43 func testRejectsAPercentEscape() {
44 XCTAssertEqual(DomainName.validate("https://ex%20ample.com"), .failure(.invalidCharacter("%")))
45 }
46
47 func testRejectsAnEmptyLabel() {
48 XCTAssertEqual(DomainName.validate("a..b.com"), .failure(.malformedLabel("")))
49 }
50
51 /// `-x.com` forms a URL, so `DomainHostURL` is not a substitute for these
52 /// label rules — the invariant only runs the other way.
53 func testRejectsALeadingHyphenLabel() {
54 XCTAssertEqual(DomainName.validate("-x.com"), .failure(.malformedLabel("-x")))
55 }
56
57 func testRejectsALabelOver63Bytes() {
58 let label = String(repeating: "a", count: 64)
59 XCTAssertEqual(DomainName.validate("\(label).com"), .failure(.labelTooLong))
60 }
61
62 func testRejectsAHostOver253Bytes() {
63 let label = String(repeating: "a", count: 63)
64 let host = Array(repeating: label, count: 4).joined(separator: ".")
65 XCTAssertEqual(DomainName.validate(host), .failure(.tooLong))
66 }
67
68 /// The limit applies to the IDNA-encoded label, so it turns on the encoded
69 /// size rather than the typed one: these 40 distinct CJK characters encode
70 /// to 83 bytes, while 40 repeats of one character encode to 46 and pass.
71 func testMeasuresLengthOnPunycode() {
72 let label = String((0..<40).compactMap { UnicodeScalar(UInt32(0x4E00 + $0 * 7)).map(Character.init) })
73 XCTAssertEqual(DomainName.validate("\(label).com"), .failure(.labelTooLong))
74 XCTAssertEqual(
75 DomainName.validate("\(String(repeating: "域", count: 40)).com"),
76 .success("\(String(repeating: "域", count: 40)).com")
77 )
78 }
79
80 func testAcceptsAUnicodeHost() {
81 XCTAssertEqual(DomainName.validate("münchen.de"), .success("münchen.de"))
82 }
83
84 func testAcceptsATrailingDot() {
85 XCTAssertEqual(DomainName.validate("example.com."), .success("example.com"))
86 }
87
88 /// One-directional invariant: everything the validator accepts can be built
89 /// into a request URL.
90 func testAcceptedHostsFormARequestURL() {
91 for host in ["example.com", "münchen.de", "a.b.c.example.com"] {
92 guard case .success(let validated) = DomainName.validate(host) else {
93 return XCTFail("\(host) should validate")
94 }
95 XCTAssertNotNil(DomainHostURL.https(validated))
96 }
97 }
98}
99
100/// The validator sits at the input boundary only. `normalizedDomain` is the key
101/// that matches already-stored rows, so it stays lenient: routing it through the
102/// validator would turn tracking and workflow lookups into no-ops for any stored
103/// domain the rules reject.
104@MainActor
105final class DomainViewModelInputTests: XCTestCase {
106 /// Shared and never released: deallocating a `DomainViewModel` runs its
107 /// implicit main-actor-isolated deinit through the iOS 17 back-deployment
108 /// shim, which aborts in the simulator. The app holds one for its whole
109 /// lifetime, so nothing releases one there either.
110 private static let viewModel = DomainViewModel()
111
112 func testAnInvalidDomainDoesNotStartALookup() {
113 let viewModel = Self.viewModel
114 viewModel.domain = "localhost"
115
116 viewModel.run()
117
118 XCTAssertFalse(viewModel.hasRun)
119 XCTAssertNotNil(viewModel.domainInputError)
120 }
121
122 func testAStoredSingleLabelDomainStillTracksAndMatchesWorkflows() {
123 let viewModel = Self.viewModel
124 viewModel.trackedDomains = []
125 viewModel.workflows = [DomainWorkflow(name: "Internal", domains: ["localhost"])]
126
127 XCTAssertTrue(viewModel.trackDomain(domain: "localhost", availabilityStatus: nil))
128 XCTAssertEqual(viewModel.workflowsContaining(domain: "localhost").count, 1)
129 }
130}