Skip to content

Commit

Permalink
Require full IPv4 address string to be treated as valid URL (#616)
Browse files Browse the repository at this point in the history
Task/Issue URL: https://app.asana.com/0/0/1206262563462715/f

Description:
When an IPv4-like string is passed to URL constructor, require that it contains 4 octets and otherwise return nil.
This allows clients to fall back to treating the string as search query and constructing search URLs, instead
of making most likely unwanted navigation to an IP address where missing octets are filled with zeros
(e.g. 1.4 -> 1.0.0.4).
  • Loading branch information
ayoy authored Jan 3, 2024
1 parent e9c344c commit 39a5daf
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Sources/Common/Extensions/URLExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
//

import Foundation
import Network

extension URL {

Expand Down Expand Up @@ -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
}
Expand Down
10 changes: 10 additions & 0 deletions Tests/CommonTests/Extensions/URLExtensionTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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/")!
Expand Down

0 comments on commit 39a5daf

Please sign in to comment.