Test seam and coverage for the domain-availability path !6

merged merged by cmc on 2026-10-24 03:43 UTC · krz/domain-dig:availability-seam into main

8 files changed, +244 −49

Layout: unified · split

Docs/integrations.txt deleted −28
@@ -1,28 +0,0 @@
1# DomainDig Integrations
2
3## SMTP submission
4
5Email integrations support implicit TLS ("Direct TLS") on port 465. STARTTLS
6on port 587 is not supported.
7
8`SMTPSecurityMode` has two cases: `.plain` and `.directTLS`. Sending with a
9username configured and `.plain` selected throws
10`IntegrationError.insecureCredentials`, and the integration editor refuses to
11save that combination.
12
13Why STARTTLS is not implemented:
14
15- `NWConnection` cannot add TLS to an established connection. The protocol
16 stack is fixed when `NWParameters` is constructed, so the plaintext SMTP
17 greeting and the `STARTTLS` exchange cannot be followed by a TLS handshake
18 on the same connection.
19- The alternative is CFStream, which can negotiate TLS in place through
20 `kCFStreamPropertySSLSettings`. `CFStreamCreatePairWithSocketToHost` is
21 deprecated in favour of Network.framework, which is the API that cannot do
22 this. CFStream also has no handshake-completion callback and needs its own
23 run-loop thread. A correct implementation must discard any bytes buffered
24 before the upgrade; otherwise it is open to the STARTTLS plaintext-injection
25 attack (CVE-2011-0411).
26- RFC 8314 prefers implicit TLS over STARTTLS for mail submission. It also
27 asks that both be offered during the transition, so supporting 465 alone is
28 narrower than the RFC wants; the transport constraints above are the reason.
DomainDig.xcodeproj/project.pbxproj +4
@@ -27,6 +27,7 @@
2727 C7CA9E02B0DC2708DE7A8563 /* DomainDataPortabilityServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */; };
2828 E959C4D24DAAB3CB80D854B2 /* DiffServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */; };
2929 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; };
30 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000301 /* AvailabilityTests.swift */; };
3031 EA12012CDB4C21ABB4217D86 /* LocalAPIContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D85A44C5F315A1644AC9073 /* LocalAPIContractTests.swift */; };
3132/* End PBXBuildFile section */
3233
@@ -98,6 +99,7 @@
9899 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityService.swift; sourceTree = "<group>"; };
99100 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryEntryCodableTests.swift; sourceTree = "<group>"; };
100101 A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; };
102 A1B2C3D40000000000000301 /* AvailabilityTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = AvailabilityTests.swift; sourceTree = "<group>"; };
101103 A77F7ED29E7C6669F5E61C04 /* DomainDigTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DomainDigTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
102104 CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityServiceTests.swift; sourceTree = "<group>"; };
103105 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; };
@@ -236,6 +238,7 @@
236238 499B99A1866999A38AC475F5 /* AppInfoTests.swift */,
237239 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */,
238240 A1B2C3D40000000000000201 /* InspectionInputTests.swift */,
241 A1B2C3D40000000000000301 /* AvailabilityTests.swift */,
239242 );
240243 path = DomainDigTests;
241244 sourceTree = "<group>";
@@ -497,6 +500,7 @@
497500 4F96CEB875EC3501E784CE39 /* DataMigrationServiceTests.swift in Sources */,
498501 99024E91EED2275FD80E83A9 /* AppInfoTests.swift in Sources */,
499502 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */,
503 A1B2C3D40000000000000302 /* AvailabilityTests.swift in Sources */,
500504 );
501505 runOnlyForDeploymentPostprocessing = 0;
502506 };
DomainDig/DNSLookupService.swift +12
@@ -56,6 +56,12 @@ enum DNSResolverOption: String, CaseIterable, Identifiable {
5656 }
5757}
5858
59/// A single record lookup, injectable so callers that branch on its result can
60/// be exercised without network.
61protocol DNSLookup {
62 func lookup(domain: String, recordType: DNSRecordType) async throws -> [DNSRecord]
63}
64
5965struct DNSLookupService {
6066 private static let internetClass = 1
6167
@@ -532,6 +538,12 @@ struct DNSLookupService {
532538 }
533539}
534540
541extension DNSLookupService: DNSLookup {
542 func lookup(domain: String, recordType: DNSRecordType) async throws -> [DNSRecord] {
543 try await Self.lookup(domain: domain, recordType: recordType)
544 }
545}
546
535547private struct DNSLookupResponse {
536548 let answers: [CloudflareDNSResponse.CloudflareDNSAnswer]
537549 let authenticatedData: Bool
DomainDig/DomainAvailabilityService.swift +19 −10
@@ -3,14 +3,18 @@ import Foundation
33struct DomainAvailabilityService {
44 private static let suggestionTLDs = ["net", "io", "dev", "app", "co", "org"]
55
6 static func check(domain: String) async -> DomainAvailabilityResult {
6 static func check(
7 domain: String,
8 rdapTransport: RDAPTransport = URLSessionRDAPTransport(),
9 dns: DNSLookup = DNSLookupService()
10 ) async -> DomainAvailabilityResult {
711 let normalizedDomain = normalize(domain)
812 guard !normalizedDomain.isEmpty else {
913 return DomainAvailabilityResult(domain: domain, status: .unknown)
1014 }
1115
1216 // RDAP is the registry's own record, so it settles both directions.
13 if let registryStatus = await checkViaRDAP(domain: normalizedDomain) {
17 if let registryStatus = await checkViaRDAP(domain: normalizedDomain, transport: rdapTransport) {
1418 return DomainAvailabilityResult(domain: normalizedDomain, status: registryStatus)
1519 }
1620
@@ -18,11 +22,16 @@ struct DomainAvailabilityService {
1822 // resolves is registered. Absence of records is not evidence of
1923 // availability, because the DoH layer drops the response code, so
2024 // NXDOMAIN and a resolver failure arrive here identically.
21 let fallbackStatus = await checkViaDNSFallback(domain: normalizedDomain)
25 let fallbackStatus = await checkViaDNSFallback(domain: normalizedDomain, dns: dns)
2226 return DomainAvailabilityResult(domain: normalizedDomain, status: fallbackStatus)
2327 }
2428
25 static func suggestions(for domain: String, limit: Int = 6) async -> [DomainSuggestionResult] {
29 static func suggestions(
30 for domain: String,
31 limit: Int = 6,
32 rdapTransport: RDAPTransport = URLSessionRDAPTransport(),
33 dns: DNSLookup = DNSLookupService()
34 ) async -> [DomainSuggestionResult] {
2635 let normalizedDomain = normalize(domain)
2736 let candidates = suggestionCandidates(for: normalizedDomain, limit: limit)
2837 guard !candidates.isEmpty else { return [] }
@@ -30,20 +39,20 @@ struct DomainAvailabilityService {
3039 var results: [DomainSuggestionResult] = []
3140 for candidate in candidates {
3241 if Task.isCancelled { break }
33 let result = await check(domain: candidate)
42 let result = await check(domain: candidate, rdapTransport: rdapTransport, dns: dns)
3443 results.append(DomainSuggestionResult(domain: result.domain, status: result.status))
3544 }
3645 return results
3746 }
3847
39 private static func checkViaRDAP(domain: String) async -> DomainAvailabilityStatus? {
40 let status = await RDAPService.registrationStatus(for: domain)
48 private static func checkViaRDAP(domain: String, transport: RDAPTransport) async -> DomainAvailabilityStatus? {
49 let status = await RDAPService.registrationStatus(for: domain, transport: transport)
4150 return status
4251 }
4352
44 private static func checkViaDNSFallback(domain: String) async -> DomainAvailabilityStatus {
53 private static func checkViaDNSFallback(domain: String, dns: DNSLookup) async -> DomainAvailabilityStatus {
4554 do {
46 let aRecords = try await DNSLookupService.lookup(domain: domain, recordType: .A)
55 let aRecords = try await dns.lookup(domain: domain, recordType: .A)
4756 if !aRecords.isEmpty {
4857 return .registered
4958 }
@@ -52,7 +61,7 @@ struct DomainAvailabilityService {
5261 }
5362
5463 do {
55 let nsRecords = try await DNSLookupService.lookup(domain: domain, recordType: .NS)
64 let nsRecords = try await dns.lookup(domain: domain, recordType: .NS)
5665 if !nsRecords.isEmpty {
5766 return .registered
5867 }
DomainDig/IntegrationsView.swift −4
@@ -290,10 +290,6 @@ private struct IntegrationEditorView: View {
290290 TextField("Port", text: $emailPort)
291291 .keyboardType(.numberPad)
292292
293 Text("Port 465 with Direct TLS is supported. Port 587 (STARTTLS) is not.")
294 .font(.caption)
295 .foregroundStyle(Color(.appTextSecondary))
296
297293 TextField("Username", text: $emailUsername)
298294 .textInputAutocapitalization(.never)
299295 .autocorrectionDisabled()
DomainDig/RDAPService.swift +24 −6
@@ -1,13 +1,28 @@
11import Foundation
22
3/// The HTTP fetch behind an RDAP query, injectable so the status mapping can be
4/// exercised without network.
5protocol RDAPTransport {
6 func fetch(_ request: URLRequest) async throws -> (Data, URLResponse)
7}
8
9struct URLSessionRDAPTransport: RDAPTransport {
10 func fetch(_ request: URLRequest) async throws -> (Data, URLResponse) {
11 try await URLSession.shared.data(for: request)
12 }
13}
14
315enum RDAPService {
416 /// The registry's answer about `domain`, or nil when the registry did not
517 /// give one.
6 static func registrationStatus(for domain: String) async -> DomainAvailabilityStatus? {
18 static func registrationStatus(
19 for domain: String,
20 transport: RDAPTransport = URLSessionRDAPTransport()
21 ) async -> DomainAvailabilityStatus? {
722 let normalizedDomain = normalize(domain)
823 guard !normalizedDomain.isEmpty else { return nil }
924
10 switch await fetchRDAPResponse(for: normalizedDomain) {
25 switch await fetchRDAPResponse(for: normalizedDomain, transport: transport) {
1126 case .found:
1227 return .registered
1328 case .notRegistered:
@@ -29,13 +44,16 @@ enum RDAPService {
2944 return host != bootstrapHost && !host.hasSuffix(".\(bootstrapHost)")
3045 }
3146
32 static func ownership(for domain: String) async -> ServiceResult<DomainOwnership> {
47 static func ownership(
48 for domain: String,
49 transport: RDAPTransport = URLSessionRDAPTransport()
50 ) async -> ServiceResult<DomainOwnership> {
3351 let normalizedDomain = normalize(domain)
3452 guard !normalizedDomain.isEmpty else {
3553 return .empty("Unavailable")
3654 }
3755
38 switch await fetchRDAPResponse(for: normalizedDomain) {
56 switch await fetchRDAPResponse(for: normalizedDomain, transport: transport) {
3957 case let .found(response):
4058 let ownership = DomainOwnership(
4159 registrar: response.registrarName,
@@ -77,7 +95,7 @@ private enum RDAPFetchOutcome {
7795 case failed(String)
7896}
7997
80private func fetchRDAPResponse(for domain: String) async -> RDAPFetchOutcome {
98private func fetchRDAPResponse(for domain: String, transport: RDAPTransport) async -> RDAPFetchOutcome {
8199 let startedAt = DomainDebugLog.signpostStart("RDAP.fetch", domain: domain)
82100 guard let url = URL(string: "https://\(bootstrapHost)/domain/\(domain)") else {
83101 return .failed("Unavailable")
@@ -88,7 +106,7 @@ private func fetchRDAPResponse(for domain: String) async -> RDAPFetchOutcome {
88106 request.setValue("application/rdap+json, application/json", forHTTPHeaderField: "Accept")
89107 DomainDebugLog.debug("RDAP.request url=\(url.absoluteString) timeout=8")
90108
91 let (data, response) = try await URLSession.shared.data(for: request)
109 let (data, response) = try await transport.fetch(request)
92110 guard let httpResponse = response as? HTTPURLResponse else {
93111 DomainDebugLog.error("RDAP.badResponse domain=\(domain) response=nil")
94112 return .failed(URLError(.badServerResponse).localizedDescription)
DomainDigTests/AvailabilityTests.swift added +185
@@ -0,0 +1,185 @@
1import XCTest
2@testable import DomainDig
3
4/// Availability has two sources that disagree about what silence means: a
5/// registry 404 means the name is free, while a DNS lookup with no records
6/// means nothing, because the DoH layer drops the response code. These pin the
7/// mapping for each path through `DomainAvailabilityService.check`.
8final class DomainAvailabilityTests: XCTestCase {
9
10 /// A resolving name under a TLD with no RDAP server: the 404 comes from the
11 /// bootstrap redirector, which says nothing about registration, so DNS
12 /// decides.
13 func testBootstrapNotFoundWithDNSRecordsIsRegistered() async {
14 let transport = StubRDAPTransport { _ in
15 (Data(), stubHTTPResponse(status: 404, host: "rdap.org", domain: "example.quux"))
16 }
17 let dns = StubDNSLookup(records: [.A: [DNSRecord(value: "203.0.113.10", ttl: 300)]])
18
19 let result = await DomainAvailabilityService.check(
20 domain: "example.quux",
21 rdapTransport: transport,
22 dns: dns
23 )
24
25 XCTAssertEqual(result.status, .registered)
26 }
27
28 func testRegistryNotFoundIsAvailable() async {
29 let transport = StubRDAPTransport { _ in
30 (Data(), stubHTTPResponse(status: 404, host: "rdap.verisign.com", domain: "example.com"))
31 }
32 let dns = StubDNSLookup(records: [:])
33
34 let result = await DomainAvailabilityService.check(
35 domain: "example.com",
36 rdapTransport: transport,
37 dns: dns
38 )
39
40 XCTAssertEqual(result.status, .available)
41 XCTAssertEqual(dns.lookupCount, 0)
42 }
43
44 func testDomainRecordIsRegistered() async {
45 let transport = StubRDAPTransport { _ in
46 (domainRecordBody, stubHTTPResponse(status: 200, host: "rdap.verisign.com", domain: "example.com"))
47 }
48 let dns = StubDNSLookup(records: [:])
49
50 let result = await DomainAvailabilityService.check(
51 domain: "example.com",
52 rdapTransport: transport,
53 dns: dns
54 )
55
56 XCTAssertEqual(result.status, .registered)
57 XCTAssertEqual(dns.lookupCount, 0)
58 }
59
60 func testNonDomainRecordFallsBackToDNS() async {
61 let transport = StubRDAPTransport { _ in
62 (nonDomainRecordBody, stubHTTPResponse(status: 200, host: "rdap.verisign.com", domain: "example.com"))
63 }
64 let dns = StubDNSLookup(records: [.NS: [DNSRecord(value: "ns1.example.net", ttl: 300)]])
65
66 let result = await DomainAvailabilityService.check(
67 domain: "example.com",
68 rdapTransport: transport,
69 dns: dns
70 )
71
72 XCTAssertEqual(result.status, .registered)
73 XCTAssertEqual(dns.lookupCount, 2)
74 }
75
76 func testTransportErrorWithDNSRecordsIsRegistered() async {
77 let transport = StubRDAPTransport { _ in throw URLError(.timedOut) }
78 let dns = StubDNSLookup(records: [.A: [DNSRecord(value: "203.0.113.10", ttl: 300)]])
79
80 let result = await DomainAvailabilityService.check(
81 domain: "example.com",
82 rdapTransport: transport,
83 dns: dns
84 )
85
86 XCTAssertEqual(result.status, .registered)
87 }
88
89 /// No RDAP answer and no DNS records is undecided, not available: a
90 /// resolver failure and NXDOMAIN arrive here identically.
91 func testTransportErrorWithoutDNSRecordsIsUnknown() async {
92 let transport = StubRDAPTransport { _ in throw URLError(.timedOut) }
93 let dns = StubDNSLookup(records: [:])
94
95 let result = await DomainAvailabilityService.check(
96 domain: "example.com",
97 rdapTransport: transport,
98 dns: dns
99 )
100
101 XCTAssertEqual(result.status, .unknown)
102 }
103
104 func testBlankInputIsUnknownWithoutALookup() async {
105 let transport = StubRDAPTransport { _ in
106 XCTFail("blank input should not reach the network")
107 return (Data(), stubHTTPResponse(status: 200, host: "rdap.org", domain: ""))
108 }
109 let dns = StubDNSLookup(records: [:])
110
111 for input in ["", " \n"] {
112 let result = await DomainAvailabilityService.check(
113 domain: input,
114 rdapTransport: transport,
115 dns: dns
116 )
117 XCTAssertEqual(result.status, .unknown)
118 }
119
120 XCTAssertEqual(transport.requestedDomains, [])
121 XCTAssertEqual(dns.lookupCount, 0)
122 }
123
124 func testSuggestionsMapEachCandidateStatus() async {
125 let transport = StubRDAPTransport { request in
126 let domain = request.url?.lastPathComponent ?? ""
127 if domain == "example.net" {
128 return (Data(), stubHTTPResponse(status: 404, host: "rdap.nic.net", domain: domain))
129 }
130 return (domainRecordBody, stubHTTPResponse(status: 200, host: "rdap.nic.io", domain: domain))
131 }
132 let dns = StubDNSLookup(records: [:])
133
134 let results = await DomainAvailabilityService.suggestions(
135 for: "example.com",
136 limit: 2,
137 rdapTransport: transport,
138 dns: dns
139 )
140
141 XCTAssertEqual(results.map(\.domain), ["example.net", "example.io"])
142 XCTAssertEqual(results.map(\.status), [.available, .registered])
143 }
144}
145
146private final class StubRDAPTransport: RDAPTransport {
147 private let respond: (URLRequest) throws -> (Data, URLResponse)
148 private(set) var requestedDomains: [String] = []
149
150 init(respond: @escaping (URLRequest) throws -> (Data, URLResponse)) {
151 self.respond = respond
152 }
153
154 func fetch(_ request: URLRequest) async throws -> (Data, URLResponse) {
155 if let domain = request.url?.lastPathComponent {
156 requestedDomains.append(domain)
157 }
158 return try respond(request)
159 }
160}
161
162private final class StubDNSLookup: DNSLookup {
163 private let records: [DNSRecordType: [DNSRecord]]
164 private(set) var lookupCount = 0
165
166 init(records: [DNSRecordType: [DNSRecord]]) {
167 self.records = records
168 }
169
170 func lookup(domain: String, recordType: DNSRecordType) async throws -> [DNSRecord] {
171 lookupCount += 1
172 return records[recordType] ?? []
173 }
174}
175
176private let domainRecordBody = Data(#"{"objectClassName":"domain","ldhName":"example.com"}"#.utf8)
177
178private let nonDomainRecordBody = Data(#"{"objectClassName":"help"}"#.utf8)
179
180/// The response URL matters as much as the status code: it is how a registry's
181/// 404 is told apart from the bootstrap redirector's.
182private func stubHTTPResponse(status: Int, host: String, domain: String) -> URLResponse {
183 let url = URL(string: "https://\(host)/domain/\(domain)")!
184 return HTTPURLResponse(url: url, statusCode: status, httpVersion: nil, headerFields: nil)!
185}
README.org −1
@@ -68,7 +68,6 @@ git config core.hooksPath .githooks
6868#+begin_example
6969local api: Docs/local-api.txt
7070data migration: Docs/data-migration.txt
71integrations: Docs/integrations.txt
7271accessibility: Docs/ACCESSIBILITY.txt
7372security: SECURITY.txt
7473#+end_example