From 5986adb9b681a5d11e1483da3adee240be2906ac Mon Sep 17 00:00:00 2001 From: Benjamin Sergeant Date: Tue, 17 Nov 2026 12:46:57 -0800 Subject: [PATCH] Keep redirect credentials within the same origin --- docs/usage.md | 7 ++ ixwebsocket/IXHttpClient.cpp | 13 ++- ixwebsocket/IXUrlParser.cpp | 13 +++ ixwebsocket/IXUrlParser.h | 3 + ixwebsocket/IXWebSocketTransport.cpp | 8 +- test/IXHttpClientResponseTest.cpp | 137 +++++++++++++++++++++++++++ test/IXUrlParserTest.cpp | 27 ++++++ 7 files changed, 203 insertions(+), 5 deletions(-) diff --git a/docs/usage.md b/docs/usage.md index 04112cc1..7a378fa3 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -675,6 +675,13 @@ following redirects. Reusing an arguments object shares that flag across its submitted requests; use separate arguments objects for independently cancellable requests. HTTP connection reuse is not provided by this behavior. +Automatic HTTP and WebSocket redirects retain caller-supplied `Authorization` and `Cookie` +headers only while the scheme, hostname and port stay the same. Once a redirect +changes origin, these headers remain removed for the rest of that redirect chain. +The caller's original request arguments are preserved. Other custom headers are +forwarded; applications should avoid putting credentials in those headers when +following redirects to untrusted destinations. + See this [issue](https://github.com/machinezone/IXWebSocket/issues/209) for links about uploading files with HTTP multipart. ## HTTP server API diff --git a/ixwebsocket/IXHttpClient.cpp b/ixwebsocket/IXHttpClient.cpp index 9e1ae400..420b1e2b 100644 --- a/ixwebsocket/IXHttpClient.cpp +++ b/ixwebsocket/IXHttpClient.cpp @@ -453,11 +453,16 @@ namespace ix downloadSize); } - // Recurse - std::string location = headers["Location"]; + const std::string& location = headers.at("Location"); + auto redirected = snapshotRequest(*args); + // Credentials are scoped to the same scheme, host and port. + if (!UrlParser::isSameOrigin(url, location)) + { + redirected->extraHeaders.erase("Authorization"); + redirected->extraHeaders.erase("Cookie"); + } if (code == 303 && verb != kHead) { - auto redirected = snapshotRequest(*args); redirected->extraHeaders.erase("Content-Length"); redirected->extraHeaders.erase("Content-Type"); redirected->extraHeaders.erase("Content-Encoding"); @@ -466,7 +471,7 @@ namespace ix return requestImpl( location, kGet, std::string(), redirected, cancel, redirects + 1); } - return requestImpl(location, verb, body, args, cancel, redirects + 1); + return requestImpl(location, verb, body, redirected, cancel, redirects + 1); } if (verb == "HEAD") diff --git a/ixwebsocket/IXUrlParser.cpp b/ixwebsocket/IXUrlParser.cpp index 0c545e76..15b8fc41 100644 --- a/ixwebsocket/IXUrlParser.cpp +++ b/ixwebsocket/IXUrlParser.cpp @@ -31,6 +31,7 @@ #include "IXUrlParser.h" +#include "IXStrCaseCompare.h" #include #include #include @@ -405,6 +406,18 @@ namespace namespace ix { + bool UrlParser::isSameOrigin(const std::string& first, const std::string& second) + { + std::string firstProtocol, firstHost, firstPath, firstQuery; + std::string secondProtocol, secondHost, secondPath, secondQuery; + int firstPort, secondPort; + return parse(first, firstProtocol, firstHost, firstPath, firstQuery, firstPort) && + parse(second, secondProtocol, secondHost, secondPath, secondQuery, secondPort) && + firstProtocol == secondProtocol && firstPort == secondPort && + !CaseInsensitiveLess::cmp(firstHost, secondHost) && + !CaseInsensitiveLess::cmp(secondHost, firstHost); + } + bool UrlParser::parse(const std::string& url, std::string& protocol, std::string& host, diff --git a/ixwebsocket/IXUrlParser.h b/ixwebsocket/IXUrlParser.h index 2737fa8b..36658c88 100644 --- a/ixwebsocket/IXUrlParser.h +++ b/ixwebsocket/IXUrlParser.h @@ -13,6 +13,9 @@ namespace ix class UrlParser { public: + // Compare scheme, case-insensitive hostname and effective port. + static bool isSameOrigin(const std::string& first, const std::string& second); + static bool parse(const std::string& url, std::string& protocol, std::string& host, diff --git a/ixwebsocket/IXWebSocketTransport.cpp b/ixwebsocket/IXWebSocketTransport.cpp index 1411595b..88c06323 100644 --- a/ixwebsocket/IXWebSocketTransport.cpp +++ b/ixwebsocket/IXWebSocketTransport.cpp @@ -117,6 +117,7 @@ namespace ix std::string protocol, host, path, query; int port; std::string remoteUrl(url); + WebSocketHttpHeaders requestHeaders(headers); WebSocketInitResult result; const int maxRedirections = 10; @@ -147,7 +148,7 @@ namespace ix _enablePerMessageDeflate); result = webSocketHandshake.clientHandshake(remoteUrl, - headers, + requestHeaders, protocol, host, path, @@ -167,6 +168,11 @@ namespace ix break; } + if (!UrlParser::isSameOrigin(remoteUrl, it->second)) + { + requestHeaders.erase("Authorization"); + requestHeaders.erase("Cookie"); + } remoteUrl = it->second; continue; } diff --git a/test/IXHttpClientResponseTest.cpp b/test/IXHttpClientResponseTest.cpp index 1e041c67..2bab7718 100644 --- a/test/IXHttpClientResponseTest.cpp +++ b/test/IXHttpClientResponseTest.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace @@ -164,6 +165,142 @@ TEST_CASE("307 and 308 redirects preserve the request method and body", "[http][ CHECK(requests[1]->body == "body"); } +TEST_CASE("HTTP redirects keep credentials within the original origin", + "[http][redirect_credentials]") +{ + const bool crossOrigin = GENERATE(false, true); + const int status = GENERATE(301, 302, 303, 307, 308); + const std::string ok = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; + ResponseServer target([&](const ix::HttpRequestPtr&, size_t) { return ok; }); + target.startServing(); + std::string location; + ResponseServer source( + [&](const ix::HttpRequestPtr&, size_t index) + { + return index == 0 + ? "HTTP/1.1 " + std::to_string(status) + + " Redirect\r\nLocation: " + location + "\r\nContent-Length: 0\r\n\r\n" + : ok; + }); + location = crossOrigin ? target.url() : source.url(); + source.startServing(); + ix::HttpClient client; + auto args = options(client); + args->extraHeaders["authorization"] = "Bearer secret"; + args->extraHeaders["cOoKiE"] = "session=secret"; + args->extraHeaders["X-Trace"] = "trace"; + auto response = client.request(source.url(), "POST", "body", args); + REQUIRE(response->errorCode == ix::HttpErrorCode::Ok); + CHECK(response->statusCode == 200); + const auto initial = source.requests(); + REQUIRE(initial.size() == (crossOrigin ? 1 : 2)); + CHECK(initial[0]->headers.at("Authorization") == "Bearer secret"); + CHECK(initial[0]->headers.at("Cookie") == "session=secret"); + const auto redirected = crossOrigin ? target.requests() : initial; + REQUIRE_FALSE(redirected.empty()); + CHECK(redirected.back()->headers.count("Authorization") == (crossOrigin ? 0 : 1)); + CHECK(redirected.back()->headers.count("Cookie") == (crossOrigin ? 0 : 1)); + CHECK(redirected.back()->headers.at("X-Trace") == "trace"); + CHECK(args->extraHeaders.at("Authorization") == "Bearer secret"); + CHECK(args->extraHeaders.at("Cookie") == "session=secret"); +} + +TEST_CASE("WebSocket redirects keep credentials within the original origin", + "[websocket][redirect_credentials]") +{ + const bool crossOrigin = GENERATE(false, true); + const std::string rejected = "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n"; + ResponseServer target([&](const ix::HttpRequestPtr&, size_t) { return rejected; }); + target.startServing(); + std::string location; + ResponseServer source( + [&](const ix::HttpRequestPtr&, size_t index) + { + return index == 0 ? "HTTP/1.1 302 Found\r\nLocation: " + location + + "\r\nContent-Length: 0\r\n\r\n" + : rejected; + }); + std::string originalUrl = source.url(); + originalUrl.replace(0, 4, "ws"); + location = crossOrigin ? target.url() : source.url(); + location.replace(0, 4, "ws"); + source.startServing(); + ix::WebSocket client; + client.setUrl(originalUrl); + const ix::WebSocketHttpHeaders headers = { + {"authorization", "Bearer secret"}, {"cOoKiE", "session=secret"}, {"X-Trace", "trace"}}; + client.setExtraHeaders(headers); + auto result = client.connect(1); + CHECK_FALSE(result.success); + CHECK(result.http_status == 401); + const auto initial = source.requests(); + REQUIRE(initial.size() == (crossOrigin ? 1 : 2)); + CHECK(initial[0]->headers.at("Authorization") == "Bearer secret"); + CHECK(initial[0]->headers.at("Cookie") == "session=secret"); + const auto redirected = crossOrigin ? target.requests() : initial; + REQUIRE_FALSE(redirected.empty()); + CHECK(redirected.back()->headers.count("Authorization") == (crossOrigin ? 0 : 1)); + CHECK(redirected.back()->headers.count("Cookie") == (crossOrigin ? 0 : 1)); + CHECK(redirected.back()->headers.at("X-Trace") == "trace"); + CHECK(client.connect(1).http_status == 401); + const auto retried = source.requests(); + CHECK(retried.back()->headers.at("Authorization") == "Bearer secret"); + CHECK(retried.back()->headers.at("Cookie") == "session=secret"); +} + +TEST_CASE("Returning to the original origin does not restore redirect credentials", + "[http][redirect_credentials]") +{ + const bool websocket = GENERATE(false, true); + std::string originalUrl; + ResponseServer target( + [&](const ix::HttpRequestPtr&, size_t) + { + return "HTTP/1.1 302 Found\r\nLocation: " + originalUrl + + "\r\nContent-Length: 0\r\n\r\n"; + }); + REQUIRE(target.listen().first); + std::string targetUrl = target.url(); + if (websocket) targetUrl.replace(0, 4, "ws"); + ResponseServer source( + [&](const ix::HttpRequestPtr&, size_t index) + { + return index == 0 ? "HTTP/1.1 302 Found\r\nLocation: " + targetUrl + + "\r\nContent-Length: 0\r\n\r\n" + : "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; + }); + originalUrl = source.url(); + if (websocket) originalUrl.replace(0, 4, "ws"); + REQUIRE(source.listen().first); + target.start(); + source.start(); + ix::HttpClient client; + auto args = options(client); + args->extraHeaders["Authorization"] = "Bearer secret"; + args->extraHeaders["Cookie"] = "session=secret"; + if (websocket) + { + ix::WebSocket webSocket; + webSocket.setUrl(originalUrl); + webSocket.setExtraHeaders(args->extraHeaders); + CHECK(webSocket.connect(1).http_status == 200); + } + else + { + REQUIRE(client.get(originalUrl, args)->errorCode == ix::HttpErrorCode::Ok); + } + const auto requests = source.requests(); + REQUIRE(requests.size() == 2); + CHECK(requests[0]->headers.count("Authorization") == 1); + CHECK(requests[0]->headers.count("Cookie") == 1); + CHECK(requests[1]->headers.count("Authorization") == 0); + CHECK(requests[1]->headers.count("Cookie") == 0); + const auto targetRequests = target.requests(); + REQUIRE(targetRequests.size() == 1); + CHECK(targetRequests[0]->headers.count("Authorization") == 0); + CHECK(targetRequests[0]->headers.count("Cookie") == 0); +} + TEST_CASE("Invalid HTTP content lengths are rejected", "[http][response]") { const std::string length = GENERATE(std::string("-1"), diff --git a/test/IXUrlParserTest.cpp b/test/IXUrlParserTest.cpp index 364065f3..9151f183 100644 --- a/test/IXUrlParserTest.cpp +++ b/test/IXUrlParserTest.cpp @@ -316,3 +316,30 @@ TEST_CASE("URLs reject raw whitespace and control characters", "[url][components ix::UrlParser::parse(prefix + character + "text", protocol, host, path, query, port)); CHECK(ix::UrlParser::parse("http://example.com/a%20b", protocol, host, path, query, port)); } + +TEST_CASE("URL origins compare scheme, hostname and effective port", "[url][origin]") +{ + struct Example + { + const char* first; + const char* second; + bool same; + }; + const Example examples[] = { + {"HTTP://EXAMPLE.com/a", "http://example.COM:80/b?query#fragment", true}, + {"https://example.com/a", "https://example.com:443/b", true}, + {"ws://example.com", "ws://example.com:80/", true}, + {"wss://[FE80::ABCD]", "wss://[fe80::abcd]:443/", true}, + {"https://example.com", "http://example.com:443", false}, + {"http://example.com", "http://other.example.com", false}, + {"http://example.com", "http://example.com:8080", false}, + {"ws://example.com", "http://example.com", false}, + {"http://example.com", "http://example.com:0", false}, + {"invalid", "invalid", false}}; + for (const auto& example : examples) + { + CAPTURE(example.first, example.second); + CHECK(ix::UrlParser::isSameOrigin(example.first, example.second) == example.same); + CHECK(ix::UrlParser::isSameOrigin(example.second, example.first) == example.same); + } +}