diff --git a/Sources/Common/Extensions/URLExtension.swift b/Sources/Common/Extensions/URLExtension.swift index 786bf87d4..83d48dd3b 100644 --- a/Sources/Common/Extensions/URLExtension.swift +++ b/Sources/Common/Extensions/URLExtension.swift @@ -17,6 +17,7 @@ // import Foundation +import Network extension URL { @@ -193,6 +194,12 @@ extension URL { // could be a local domain but user needs to use the protocol to specify that return nil } + if IPv4Address(String(hostname)) != nil { + // Require 4 octets specified explicitly for an IPv4 address (avoid 1.4 -> 1.0.0.4 expansion) + guard hostname.split(separator: ".").count == 4 else { + return nil + } + } } else { return nil } diff --git a/Tests/CommonTests/Extensions/URLExtensionTests.swift b/Tests/CommonTests/Extensions/URLExtensionTests.swift index 48ea5acee..bd42c7cf8 100644 --- a/Tests/CommonTests/Extensions/URLExtensionTests.swift +++ b/Tests/CommonTests/Extensions/URLExtensionTests.swift @@ -89,6 +89,16 @@ final class URLExtensionTests: XCTestCase { XCTAssertNil("localdomain".url) } + func testThatIPv4AddressMustContainFourOctets() { + XCTAssertNil("1.4".url) + XCTAssertNil("1.4/3.4".url) + XCTAssertNil("1.0.4".url) + XCTAssertNil("127.0.1".url) + + XCTAssertEqual("127.0.0.1".url?.absoluteString, "http://127.0.0.1") + XCTAssertEqual("1.0.0.4/3.4".url?.absoluteString, "http://1.0.0.4/3.4") + } + func testWhenNakedIsCalled_ThenURLWithNoSchemeWWWPrefixAndLastSlashIsReturned() { let url = URL(string: "http://duckduckgo.com")! let duplicate = URL(string: "https://www.duckduckgo.com/")!