Fix four shipping defects !3

merged merged by cmc on 2026-10-24 03:19 UTC · krz/domain-dig:shipping-defects into cleanup

13 files changed, +218 −33

Layout: unified · split

DomainDig.xcodeproj/project.pbxproj +4
@@ -26,6 +26,7 @@
2626 A5AF921BC1C2E6E940CC05DC /* SnapshotFixture.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CA789D3607B55E3612E6FFA /* SnapshotFixture.swift */; };
2727 C7CA9E02B0DC2708DE7A8563 /* DomainDataPortabilityServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */; };
2828 E959C4D24DAAB3CB80D854B2 /* DiffServiceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 15A25DF2B8BB52589D49986B /* DiffServiceTests.swift */; };
29 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1B2C3D40000000000000201 /* InspectionInputTests.swift */; };
2930 EA12012CDB4C21ABB4217D86 /* LocalAPIContractTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D85A44C5F315A1644AC9073 /* LocalAPIContractTests.swift */; };
3031/* End PBXBuildFile section */
3132
@@ -96,6 +97,7 @@
9697 8BDC00010000000000000001 /* DomainDigUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DomainDigUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
9798 8BF9DA842F9B13FB00EF41D5 /* DomainDataPortabilityService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityService.swift; sourceTree = "<group>"; };
9899 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = HistoryEntryCodableTests.swift; sourceTree = "<group>"; };
100 A1B2C3D40000000000000201 /* InspectionInputTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = InspectionInputTests.swift; sourceTree = "<group>"; };
99101 A77F7ED29E7C6669F5E61C04 /* DomainDigTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = DomainDigTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
100102 CC948A02EC0184228BC4630E /* DomainDataPortabilityServiceTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = DomainDataPortabilityServiceTests.swift; sourceTree = "<group>"; };
101103 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; };
@@ -233,6 +235,7 @@
233235 435AFB3F99D579D3D7B58279 /* DataMigrationServiceTests.swift */,
234236 499B99A1866999A38AC475F5 /* AppInfoTests.swift */,
235237 A1B2C3D40000000000000101 /* HistoryEntryCodableTests.swift */,
238 A1B2C3D40000000000000201 /* InspectionInputTests.swift */,
236239 );
237240 path = DomainDigTests;
238241 sourceTree = "<group>";
@@ -493,6 +496,7 @@
493496 EA12012CDB4C21ABB4217D86 /* LocalAPIContractTests.swift in Sources */,
494497 4F96CEB875EC3501E784CE39 /* DataMigrationServiceTests.swift in Sources */,
495498 99024E91EED2275FD80E83A9 /* AppInfoTests.swift in Sources */,
499 A1B2C3D40000000000000202 /* InspectionInputTests.swift in Sources */,
496500 );
497501 runOnlyForDeploymentPostprocessing = 0;
498502 };
DomainDig/DomainAvailabilityService.swift +7 −6
@@ -9,15 +9,16 @@ struct DomainAvailabilityService {
99 return DomainAvailabilityResult(domain: domain, status: .unknown)
1010 }
1111
12 if await checkViaRDAP(domain: normalizedDomain) == .registered {
13 return DomainAvailabilityResult(domain: normalizedDomain, status: .registered)
12 // RDAP is the registry's own record, so it settles both directions.
13 if let registryStatus = await checkViaRDAP(domain: normalizedDomain) {
14 return DomainAvailabilityResult(domain: normalizedDomain, status: registryStatus)
1415 }
1516
17 // Without a registry answer only "registered" is decidable: a name that
18 // resolves is registered. Absence of records is not evidence of
19 // availability, because the DoH layer drops the response code, so
20 // NXDOMAIN and a resolver failure arrive here identically.
1621 let fallbackStatus = await checkViaDNSFallback(domain: normalizedDomain)
17 if fallbackStatus == .registered {
18 return DomainAvailabilityResult(domain: normalizedDomain, status: .unknown)
19 }
20
2122 return DomainAvailabilityResult(domain: normalizedDomain, status: fallbackStatus)
2223 }
2324
DomainDig/DomainHostURL.swift added +30
@@ -0,0 +1,30 @@
1import Foundation
2
3/// Request URLs for an inspected host.
4///
5/// The inspected domain is free text, so it cannot be forced into a URL:
6/// `URL(string: "https://exa mple.com")` is nil, and a section service that
7/// built its request with `!` trapped on any host carrying a space, a tab or a
8/// control character — reachable by typing `example .com`, or by separating
9/// bulk input with spaces instead of commas or newlines.
10enum DomainHostURL {
11 static func https(_ host: String) -> URL? {
12 url(scheme: "https", host: host)
13 }
14
15 static func http(_ host: String) -> URL? {
16 url(scheme: "http", host: host)
17 }
18
19 /// `nil` when `host` cannot form a URL with a host component.
20 static func url(scheme: String, host: String) -> URL? {
21 let trimmedHost = host.trimmingCharacters(in: .whitespacesAndNewlines)
22 guard !trimmedHost.isEmpty,
23 trimmedHost.rangeOfCharacter(from: .whitespacesAndNewlines) == nil,
24 let url = URL(string: "\(scheme)://\(trimmedHost)"),
25 url.host?.isEmpty == false else {
26 return nil
27 }
28 return url
29 }
30}
DomainDig/HTTPHeadersService.swift +4 −1
@@ -36,7 +36,10 @@ struct HTTPHeadersResult {
3636
3737struct HTTPHeadersService {
3838 static func fetch(domain: String) async -> ServiceResult<HTTPHeadersResult> {
39 let url = URL(string: "https://\(domain)")!
39 guard let url = DomainHostURL.https(domain) else {
40 return .error("Not a valid domain name")
41 }
42
4043 var request = URLRequest(url: url, timeoutInterval: 10)
4144 request.httpMethod = "HEAD"
4245 let metricsDelegate = TaskMetricsDelegate()
DomainDig/IPGeolocationService.swift +4 −1
@@ -2,7 +2,10 @@ import Foundation
22
33struct IPGeolocationService {
44 static func lookup(ip: String) async -> ServiceResult<IPGeolocation> {
5 let url = URL(string: "https://ipapi.co/\(ip)/json/")!
5 guard let url = URL(string: "https://ipapi.co/\(ip)/json/") else {
6 return .error("Not a valid IP address")
7 }
8
69 let request = URLRequest(url: url, timeoutInterval: 10)
710
811 do {
DomainDig/Info.plist +8 −4
@@ -2,10 +2,6 @@
22<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
33<plist version="1.0">
44<dict>
5 <key>Allow ​Arbitrary ​Loads (or NSAllows​Arbitrary​Loads) </key>
6 <true/>
7 <key>App ​Transport ​Security ​Settings (or NSApp​Transport​Security)</key>
8 <dict/>
95 <key>BGTaskSchedulerPermittedIdentifiers</key>
106 <array>
117 <string>net.cleberg.DomainDig.monitor.refresh</string>
@@ -24,6 +20,14 @@
2420 </array>
2521 <key>CKSharingSupported</key>
2622 <true/>
23 <!-- The app inspects hosts the user names, including tracing the
24 http -> https redirect that is the point of the redirect check, so
25 requests cannot be restricted to TLS. -->
26 <key>NSAppTransportSecurity</key>
27 <dict>
28 <key>NSAllowsArbitraryLoads</key>
29 <true/>
30 </dict>
2731 <key>NSSupportsLiveActivities</key>
2832 <true/>
2933 <key>UIBackgroundModes</key>
DomainDig/IntegrationService.swift +14 −1
@@ -586,6 +586,7 @@ private enum IntegrationError: LocalizedError {
586586 case missingSecret
587587 case invalidResponse(Int)
588588 case invalidSMTPPort
589 case insecureCredentials
589590 case smtp(String)
590591 case streamClosed
591592
@@ -601,6 +602,8 @@ private enum IntegrationError: LocalizedError {
601602 return "The remote endpoint returned \(statusCode)."
602603 case .invalidSMTPPort:
603604 return "The SMTP port is invalid."
605 case .insecureCredentials:
606 return "SMTP credentials cannot be sent over an unencrypted connection. Use Direct TLS, usually on port 465."
604607 case .smtp(let message):
605608 return message
606609 case .streamClosed:
@@ -669,10 +672,20 @@ private enum SMTPClient {
669672 configuration: EmailIntegrationConfiguration,
670673 password: String
671674 ) async throws {
672 guard let port = NWEndpoint.Port(rawValue: UInt16(configuration.port)) else {
675 // `UInt16(_:)` traps above 65535, which the editor's port field allows.
676 guard let portNumber = UInt16(exactly: configuration.port),
677 let port = NWEndpoint.Port(rawValue: portNumber) else {
673678 throw IntegrationError.invalidSMTPPort
674679 }
675680
681 // AUTH LOGIN sends the username and password base64-encoded, which is
682 // not encryption. Without TLS from the first byte they would go out in
683 // the clear, so refuse before the connection opens. STARTTLS is not an
684 // option here: NWConnection cannot upgrade an established connection.
685 guard configuration.username.isEmpty || configuration.securityMode == .directTLS else {
686 throw IntegrationError.insecureCredentials
687 }
688
676689 let parameters: NWParameters = {
677690 switch configuration.securityMode {
678691 case .plain:
DomainDig/IntegrationsView.swift +4
@@ -468,6 +468,10 @@ private struct IntegrationEditorView: View {
468468 validationMessage = "SMTP password is required."
469469 return
470470 }
471 if smtpSecurity != .directTLS, !emailUsername.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
472 validationMessage = "A username needs Direct TLS, usually on port 465. Without it the password would be sent in cleartext."
473 return
474 }
471475
472476 let target = IntegrationTarget(
473477 id: targetID,
DomainDig/Models.swift +1 −1
@@ -1808,7 +1808,7 @@ enum SMTPSecurityMode: String, Codable, CaseIterable, Identifiable, Sendable {
18081808 var title: String {
18091809 switch self {
18101810 case .plain:
1811 return "Plain"
1811 return "None (no TLS)"
18121812 case .directTLS:
18131813 return "Direct TLS"
18141814 }
DomainDig/RDAPService.swift +47 −16
@@ -1,20 +1,34 @@
11import Foundation
22
33enum RDAPService {
4 /// The registry's answer about `domain`, or nil when the registry did not
5 /// give one.
46 static func registrationStatus(for domain: String) async -> DomainAvailabilityStatus? {
57 let normalizedDomain = normalize(domain)
68 guard !normalizedDomain.isEmpty else { return nil }
79
810 switch await fetchRDAPResponse(for: normalizedDomain) {
9 case let .success(response):
10 return response.isDomainRecord ? .registered : nil
11 case .empty:
12 return nil
13 case .error:
11 case .found:
12 return .registered
13 case .notRegistered:
14 return .available
15 case .empty, .failed:
1416 return nil
1517 }
1618 }
1719
20 /// Whether an RDAP response came from a registry's own server rather than
21 /// from the `rdap.org` bootstrap redirector.
22 ///
23 /// `rdap.org` answers 404 both for a domain its registry does not hold and
24 /// for a TLD it knows no RDAP server for; only the first says anything about
25 /// registration. `URLSession` follows the bootstrap redirect, so a response
26 /// URL on another host is the registry's own answer.
27 static func answeredByRegistry(responseURL: URL?) -> Bool {
28 guard let host = responseURL?.host?.lowercased() else { return false }
29 return host != bootstrapHost && !host.hasSuffix(".\(bootstrapHost)")
30 }
31
1832 static func ownership(for domain: String) async -> ServiceResult<DomainOwnership> {
1933 let normalizedDomain = normalize(domain)
2034 guard !normalizedDomain.isEmpty else {
@@ -22,7 +36,7 @@ enum RDAPService {
2236 }
2337
2438 switch await fetchRDAPResponse(for: normalizedDomain) {
25 case let .success(response):
39 case let .found(response):
2640 let ownership = DomainOwnership(
2741 registrar: response.registrarName,
2842 registrant: response.registrantName,
@@ -33,9 +47,11 @@ enum RDAPService {
3347 abuseEmail: response.abuseEmail
3448 )
3549 return .success(ownership)
50 case .notRegistered:
51 return .empty("Unavailable")
3652 case let .empty(message):
3753 return .empty(message)
38 case let .error(message):
54 case let .failed(message):
3955 return .error(message)
4056 }
4157 }
@@ -47,10 +63,24 @@ enum RDAPService {
4763 }
4864}
4965
50private func fetchRDAPResponse(for domain: String) async -> ServiceResult<RDAPDomainResponse> {
66private let bootstrapHost = "rdap.org"
67
68/// What a single RDAP fetch established.
69private enum RDAPFetchOutcome {
70 /// A domain record, from whichever server answered.
71 case found(RDAPDomainResponse)
72 /// The registry's own RDAP server reported no such domain.
73 case notRegistered
74 /// An answer that settles nothing: a non-domain record, or a 404 from the
75 /// bootstrap redirector rather than from a registry.
76 case empty(String)
77 case failed(String)
78}
79
80private func fetchRDAPResponse(for domain: String) async -> RDAPFetchOutcome {
5181 let startedAt = DomainDebugLog.signpostStart("RDAP.fetch", domain: domain)
52 guard let url = URL(string: "https://rdap.org/domain/\(domain)") else {
53 return .error("Unavailable")
82 guard let url = URL(string: "https://\(bootstrapHost)/domain/\(domain)") else {
83 return .failed("Unavailable")
5484 }
5585
5686 do {
@@ -61,7 +91,7 @@ private func fetchRDAPResponse(for domain: String) async -> ServiceResult<RDAPDo
6191 let (data, response) = try await URLSession.shared.data(for: request)
6292 guard let httpResponse = response as? HTTPURLResponse else {
6393 DomainDebugLog.error("RDAP.badResponse domain=\(domain) response=nil")
64 return .error(URLError(.badServerResponse).localizedDescription)
94 return .failed(URLError(.badServerResponse).localizedDescription)
6595 }
6696
6797 switch httpResponse.statusCode {
@@ -73,19 +103,20 @@ private func fetchRDAPResponse(for domain: String) async -> ServiceResult<RDAPDo
73103 return .empty("Unavailable")
74104 }
75105 DomainDebugLog.signpostEnd("RDAP.fetch", start: startedAt, domain: domain, extra: "status=200 bytes=\(data.count)")
76 return .success(rdapResponse)
106 return .found(rdapResponse)
77107 case 404:
78 DomainDebugLog.signpostEnd("RDAP.fetch", start: startedAt, domain: domain, extra: "status=404")
79 return .empty("Unavailable")
108 let fromRegistry = RDAPService.answeredByRegistry(responseURL: httpResponse.url)
109 DomainDebugLog.signpostEnd("RDAP.fetch", start: startedAt, domain: domain, extra: "status=404 registry=\(fromRegistry)")
110 return fromRegistry ? .notRegistered : .empty("Unavailable")
80111 default:
81112 DomainDebugLog.error("RDAP.httpError domain=\(domain) status=\(httpResponse.statusCode)")
82113 DomainDebugLog.signpostEnd("RDAP.fetch", start: startedAt, domain: domain, extra: "status=\(httpResponse.statusCode)")
83 return .error("Unavailable")
114 return .failed("Unavailable")
84115 }
85116 } catch {
86117 DomainDebugLog.error("RDAP.error domain=\(domain) error=\(error.localizedDescription)")
87118 DomainDebugLog.signpostEnd("RDAP.fetch", start: startedAt, domain: domain, extra: "error")
88 return .error(error.localizedDescription)
119 return .failed(error.localizedDescription)
89120 }
90121}
91122
DomainDig/RedirectChainService.swift +10 −2
@@ -2,12 +2,20 @@ import Foundation
22
33struct RedirectChainService {
44 static func trace(domain: String) async -> ServiceResult<[RedirectHop]> {
5 guard let httpsURL = DomainHostURL.https(domain) else {
6 return .error("Not a valid domain name")
7 }
8
59 do {
6 let hops = try await followChain(startingURL: URL(string: "https://\(domain)")!)
10 let hops = try await followChain(startingURL: httpsURL)
711 return hops.isEmpty ? .empty("No redirect data available") : .success(hops)
812 } catch {
13 guard let httpURL = DomainHostURL.http(domain) else {
14 return .error(error.localizedDescription)
15 }
16
917 do {
10 let hops = try await followChain(startingURL: URL(string: "http://\(domain)")!)
18 let hops = try await followChain(startingURL: httpURL)
1119 return hops.isEmpty ? .empty("No redirect data available") : .success(hops)
1220 } catch {
1321 return .error(error.localizedDescription)
DomainDig/SSLCheckService.swift +4 −1
@@ -4,6 +4,10 @@ import Security
44struct SSLCheckService {
55
66 static func check(domain: String) async -> ServiceResult<SSLCertificateInfo> {
7 guard let url = DomainHostURL.https(domain) else {
8 return .error("Not a valid domain name")
9 }
10
711 let delegate = SSLSessionDelegate()
812 let session = URLSession(
913 configuration: .ephemeral,
@@ -12,7 +16,6 @@ struct SSLCheckService {
1216 )
1317 defer { session.invalidateAndCancel() }
1418
15 let url = URL(string: "https://\(domain)")!
1619 let request = URLRequest(url: url, timeoutInterval: 10)
1720
1821 do {
DomainDigTests/InspectionInputTests.swift added +81
@@ -0,0 +1,81 @@
1import XCTest
2@testable import DomainDig
3
4/// The inspected domain is free text, and the section services used to force it
5/// into a URL with `!`. These pin the two pure helpers that replaced that.
6final class DomainHostURLTests: XCTestCase {
7
8 func testBuildsHTTPSURLForAPlainHost() {
9 XCTAssertEqual(DomainHostURL.https("example.com")?.absoluteString, "https://example.com")
10 }
11
12 func testBuildsHTTPURLForAPlainHost() {
13 XCTAssertEqual(DomainHostURL.http("example.com")?.absoluteString, "http://example.com")
14 }
15
16 func testTrimsSurroundingWhitespace() {
17 XCTAssertEqual(DomainHostURL.https(" example.com\n")?.absoluteString, "https://example.com")
18 }
19
20 /// The crash this replaced: `URL(string: "https://exa mple.com")` is nil, so
21 /// the force-unwrap trapped. Reachable by typing `example .com`, or by
22 /// separating bulk input with spaces instead of commas or newlines.
23 func testRejectsAnInteriorSpace() {
24 XCTAssertNil(DomainHostURL.https("exa mple.com"))
25 }
26
27 func testRejectsAnInteriorTab() {
28 XCTAssertNil(DomainHostURL.https("exa\tmple.com"))
29 }
30
31 func testRejectsAControlCharacter() {
32 XCTAssertNil(DomainHostURL.https("exa\u{0}mple.com"))
33 }
34
35 func testRejectsInputWithNoHostComponent() {
36 XCTAssertNil(DomainHostURL.https(""))
37 XCTAssertNil(DomainHostURL.https(" "))
38 XCTAssertNil(DomainHostURL.https("/"))
39 XCTAssertNil(DomainHostURL.https(":443"))
40 }
41
42 func testEncodesAnInternationalizedHost() {
43 XCTAssertEqual(DomainHostURL.https("münchen.de")?.host, "xn--mnchen-3ya.de")
44 }
45}
46
47/// `rdap.org` answers 404 both for a domain its registry does not hold and for a
48/// TLD it knows no RDAP server for. Only the first means "available", so the
49/// availability check turns on which server answered.
50final class RDAPRegistryOriginTests: XCTestCase {
51
52 func testRegistryResponseCountsAsAnAnswer() {
53 let url = URL(string: "https://rdap.verisign.com/com/v1/domain/example.com")
54 XCTAssertTrue(RDAPService.answeredByRegistry(responseURL: url))
55 }
56
57 func testBootstrapResponseDoesNotCountAsAnAnswer() {
58 let url = URL(string: "https://rdap.org/domain/example.invalidtld")
59 XCTAssertFalse(RDAPService.answeredByRegistry(responseURL: url))
60 }
61
62 func testBootstrapSubdomainDoesNotCountAsAnAnswer() {
63 let url = URL(string: "https://www.rdap.org/domain/example.invalidtld")
64 XCTAssertFalse(RDAPService.answeredByRegistry(responseURL: url))
65 }
66
67 func testHostMatchIsCaseInsensitive() {
68 let url = URL(string: "https://RDAP.ORG/domain/example.com")
69 XCTAssertFalse(RDAPService.answeredByRegistry(responseURL: url))
70 }
71
72 func testMissingResponseURLDoesNotCountAsAnAnswer() {
73 XCTAssertFalse(RDAPService.answeredByRegistry(responseURL: nil))
74 }
75
76 /// A host that merely ends in the bootstrap name is a different domain.
77 func testLookalikeHostCountsAsAnAnswer() {
78 let url = URL(string: "https://notrdap.org/domain/example.com")
79 XCTAssertTrue(RDAPService.answeredByRegistry(responseURL: url))
80 }
81}