Skip to content

Don't encode colon if URLComponents path starts with colon #1139

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions Sources/FoundationEssentials/URL/URLComponents.swift
Original file line number Diff line number Diff line change
Expand Up @@ -367,14 +367,23 @@ public struct URLComponents: Hashable, Equatable, Sendable {
}

private var percentEncodedPathNoColon: String {
guard percentEncodedPath.utf8.first(where: { $0 == ._colon || $0 == ._slash }) == ._colon else {
return percentEncodedPath
let p = percentEncodedPath
guard p.utf8.first(where: { $0 == ._colon || $0 == ._slash }) == ._colon else {
return p
}
let colonEncodedPath = Array(percentEncodedPath.utf8).replacing(
if p.utf8.first == ._colon {
// In the rare case that an app relies on URL allowing an empty
// scheme and passes its URL string directly to URLComponents
// to modify other components, we need to return the path without
// encoding the colons.
return p
}
let firstSlash = p.utf8.firstIndex(of: ._slash) ?? p.endIndex
let colonEncodedSegment = Array(p[..<firstSlash].utf8).replacing(
[._colon],
with: [UInt8(ascii: "%"), UInt8(ascii: "3"), UInt8(ascii: "A")]
)
return String(decoding: colonEncodedPath, as: UTF8.self)
return String(decoding: colonEncodedSegment, as: UTF8.self) + p[firstSlash...]
}

mutating func setPercentEncodedPath(_ newValue: String) throws {
Expand Down
10 changes: 10 additions & 0 deletions Tests/FoundationEssentialsTests/URLTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1355,6 +1355,16 @@ final class URLTests : XCTestCase {

XCTAssertNotNil(URL(string: comp.string!))
XCTAssertNotNil(URLComponents(string: comp.string!))

// In rare cases, an app might rely on URL allowing an empty scheme,
// but then take that string and pass it to URLComponents to modify
// other components of the URL. We shouldn't percent-encode the colon
// in these cases.

let url = try XCTUnwrap(URL(string: "://host/path"))
comp = try XCTUnwrap(URLComponents(string: url.absoluteString))
comp.query = "key=value"
XCTAssertEqual(comp.string, "://host/path?key=value")
}

func testURLComponentsInvalidPaths() {
Expand Down