This is an automated email from the ASF dual-hosted git repository.
pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git
The following commit(s) were added to refs/heads/trunk by this push:
new 40c175fa66 TimeStampSimpleHttpClient: follow-ups to redirect
credential handling (#1463)
40c175fa66 is described below
commit 40c175fa661945454f1c2f7ebdb0a6ab1904052f
Author: PJ Fanning <[email protected]>
AuthorDate: Fri Oct 23 00:10:38 2026 +0100
TimeStampSimpleHttpClient: follow-ups to redirect credential handling
(#1463)
- make the 4-arg handleRedirect protected so an override also sees the
redirect hop
- normalize default ports before comparing origins
- resolve relative Location headers against the request url
- disable HttpURLConnection's own redirect handling, which followed
same-protocol
redirects without going through handleRedirect, followRedirects or the
credential check
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../dsig/services/TimeStampSimpleHttpClient.java | 40 ++++++-
.../services/TestTimeStampSimpleHttpClient.java | 128 +++++++++++++++++----
2 files changed, 139 insertions(+), 29 deletions(-)
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
index ad7947bba2..e31bdde67e 100644
---
a/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
+++
b/poi-ooxml/src/main/java/org/apache/poi/poifs/crypt/dsig/services/TimeStampSimpleHttpClient.java
@@ -211,7 +211,17 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
return handleRedirect(url, handler, followRedirect, true);
}
- private TimeStampHttpClientResponse handleRedirect(String url,
MethodHandler handler, boolean followRedirect, boolean sendAuth) throws
IOException {
+ /**
+ * @param url the url to connect to
+ * @param handler sets the request method and payload on the connection
+ * @param followRedirect if true, a single redirect is followed
+ * @param sendAuth if false, the basic authentication header is not sent,
e.g. when following
+ * a redirect to another origin
+ * @return the response
+ * @throws IOException if the request fails
+ * @since 6.0.1
+ */
+ protected TimeStampHttpClientResponse handleRedirect(String url,
MethodHandler handler, boolean followRedirect, boolean sendAuth) throws
IOException {
final HttpURLConnection huc;
try {
huc = (HttpURLConnection)new
URI(url).toURL().openConnection(proxy);
@@ -223,6 +233,8 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
}
huc.setConnectTimeout(20000);
huc.setReadTimeout(20000);
+ // redirects are handled below, so that followRedirects and the
credential checks apply
+ huc.setInstanceFollowRedirects(false);
header.forEach((name, value) -> {
if (sendAuth || !BASIC_AUTH.equals(name)) {
@@ -244,6 +256,12 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
case HttpURLConnection.HTTP_SEE_OTHER:
String newUrl = huc.getHeaderField(REDIRECT_LOCATION);
if (newUrl != null && followRedirect) {
+ // the Location header may be relative to the request
url
+ try {
+ newUrl = new URI(url).resolve(newUrl).toString();
+ } catch (URISyntaxException | IllegalArgumentException
e) {
+ throw new IOException("Invalid redirect location:
" + newUrl, e);
+ }
LOG.atWarn().log("Received redirect: {} -> {}", url,
newUrl);
// don't send the TSP credentials to another origin or
downgrade them to http
return handleRedirect(newUrl, handler, false, sendAuth
&& isAuthForwardable(url, newUrl));
@@ -280,7 +298,7 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
* Credentials are only resent to the same host, either on the same scheme
and port or
* on an http to https upgrade with default ports.
*/
- private static boolean isAuthForwardable(String fromUrl, String toUrl) {
+ static boolean isAuthForwardable(String fromUrl, String toUrl) {
final URI from, to;
try {
from = new URI(fromUrl);
@@ -293,12 +311,24 @@ public class TimeStampSimpleHttpClient implements
TimeStampHttpClient {
}
final String fromScheme =
String.valueOf(from.getScheme()).toLowerCase(Locale.ROOT);
final String toScheme =
String.valueOf(to.getScheme()).toLowerCase(Locale.ROOT);
+ final int fromPort = effectivePort(from.getPort(), fromScheme);
+ final int toPort = effectivePort(to.getPort(), toScheme);
if (fromScheme.equals(toScheme)) {
- return from.getPort() == to.getPort();
+ return fromPort == toPort;
}
return "http".equals(fromScheme) && "https".equals(toScheme)
- && (from.getPort() == -1 || from.getPort() == 80)
- && (to.getPort() == -1 || to.getPort() == 443);
+ && fromPort == 80 && toPort == 443;
+ }
+
+ private static int effectivePort(int port, String scheme) {
+ if (port != -1) {
+ return port;
+ }
+ switch (scheme) {
+ case "http": return 80;
+ case "https": return 443;
+ default: return -1;
+ }
}
protected void recklessConnection(HttpURLConnection conn) throws
IOException {
diff --git
a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/services/TestTimeStampSimpleHttpClient.java
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/services/TestTimeStampSimpleHttpClient.java
index ed3f5bc0ed..05b0d1ab73 100644
---
a/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/services/TestTimeStampSimpleHttpClient.java
+++
b/poi-ooxml/src/test/java/org/apache/poi/poifs/crypt/dsig/services/TestTimeStampSimpleHttpClient.java
@@ -17,9 +17,14 @@
package org.apache.poi.poifs.crypt.dsig.services;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.not;
+import static org.hamcrest.Matchers.startsWithIgnoringCase;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedReader;
@@ -33,6 +38,7 @@ import java.nio.charset.StandardCharsets;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
@@ -44,11 +50,13 @@ import javax.net.ssl.SSLContext;
import org.apache.poi.poifs.crypt.dsig.DummyKeystore;
import org.apache.poi.poifs.crypt.dsig.DummyKeystore.KeyCertPair;
import org.apache.poi.poifs.crypt.dsig.SignatureConfig;
+import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;
class TestTimeStampSimpleHttpClient {
private static final String STORE_PASS = "test";
private static final String LOCALHOST = "127.0.0.1";
+ private static final Matcher<String> AUTHORIZATION =
startsWithIgnoringCase("authorization:");
@Test
void basicAuthNotForwardedOnHttpsToHttpRedirect() throws Exception {
@@ -83,38 +91,110 @@ class TestTimeStampSimpleHttpClient {
assertEquals(200, resp.getResponseCode());
assertArrayEquals("ok".getBytes(StandardCharsets.US_ASCII),
resp.getResponseBytes());
- assertTrue(hasAuthorization(tspReq.get(10, TimeUnit.SECONDS)));
- assertFalse(hasAuthorization(otherReq.get(10, TimeUnit.SECONDS)),
- "Basic credentials were sent to the redirect target over plain
http");
+ assertThat(tspReq.get(10, TimeUnit.SECONDS),
hasItem(AUTHORIZATION));
+ assertThat("Basic credentials were sent to the redirect target
over plain http",
+ otherReq.get(10, TimeUnit.SECONDS),
not(hasItem(AUTHORIZATION)));
}
}
- private static boolean hasAuthorization(List<String> headers) {
- return headers.stream().anyMatch(h ->
h.toLowerCase(Locale.ROOT).startsWith("authorization:"));
+ @Test
+ void relativeRedirectIsResolvedAndPassedToOverride() throws Exception {
+ try (ServerSocket tsp = new ServerSocket(0, 1,
InetAddress.getByName(LOCALHOST))) {
+ CompletableFuture<List<List<String>>> requests = serveAll(tsp,
+ "HTTP/1.1 302 Found\r\nLocation: /tsp2\r\nContent-Length:
0\r\nConnection: close\r\n\r\n",
+ "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection:
close\r\n\r\nok");
+
+ List<String> urls = new ArrayList<>();
+ TimeStampSimpleHttpClient client = new TimeStampSimpleHttpClient()
{
+ @Override
+ protected TimeStampHttpClientResponse handleRedirect(String
url, MethodHandler handler,
+ boolean followRedirect, boolean sendAuth) throws
IOException {
+ urls.add(url);
+ return super.handleRedirect(url, handler, followRedirect,
sendAuth);
+ }
+ };
+ SignatureConfig config = new SignatureConfig();
+ config.setTspUser("user");
+ config.setTspPass("secret");
+ client.init(config);
+ client.setFollowRedirects(true);
+
+ String tspUrl = "http://" + LOCALHOST + ":" + tsp.getLocalPort() +
"/tsp";
+ TimeStampHttpClient.TimeStampHttpClientResponse resp =
client.post(tspUrl, new byte[]{1, 2, 3});
+ assertEquals(200, resp.getResponseCode());
+ assertArrayEquals("ok".getBytes(StandardCharsets.US_ASCII),
resp.getResponseBytes());
+
+ String redirectUrl = "http://" + LOCALHOST + ":" +
tsp.getLocalPort() + "/tsp2";
+ assertEquals(Arrays.asList(tspUrl, redirectUrl), urls);
+
+ List<List<String>> reqs = requests.get(10, TimeUnit.SECONDS);
+ assertEquals("POST /tsp2 HTTP/1.1", reqs.get(1).get(0));
+ assertThat("same origin redirect should keep the credentials",
reqs.get(1), hasItem(AUTHORIZATION));
+ }
+ }
+
+ @Test
+ void sameProtocolRedirectNotFollowedByDefault() throws Exception {
+ try (ServerSocket tsp = new ServerSocket(0, 1,
InetAddress.getByName(LOCALHOST))) {
+ CompletableFuture<List<String>> tspReq = serve(tsp,
+ "HTTP/1.1 302 Found\r\nLocation: /tsp2\r\nContent-Length:
0\r\nConnection: close\r\n\r\n");
+
+ TimeStampSimpleHttpClient client = new TimeStampSimpleHttpClient();
+ client.init(new SignatureConfig());
+
+ String tspUrl = "http://" + LOCALHOST + ":" + tsp.getLocalPort() +
"/tsp";
+ TimeStampHttpClient.TimeStampHttpClientResponse resp =
client.post(tspUrl, new byte[]{1, 2, 3});
+ assertEquals(302, resp.getResponseCode());
+ assertNull(resp.getResponseBytes());
+ assertEquals("POST /tsp HTTP/1.1", tspReq.get(10,
TimeUnit.SECONDS).get(0));
+ }
+ }
+
+ @Test
+ void isAuthForwardableNormalizesDefaultPorts() {
+ assertTrue(TimeStampSimpleHttpClient.isAuthForwardable("https://h/a",
"https://h:443/b"));
+
assertTrue(TimeStampSimpleHttpClient.isAuthForwardable("http://h:80/a",
"http://h/b"));
+
assertTrue(TimeStampSimpleHttpClient.isAuthForwardable("http://h:80/a",
"https://h:443/b"));
+ assertFalse(TimeStampSimpleHttpClient.isAuthForwardable("https://h/a",
"https://h:8443/b"));
+ assertFalse(TimeStampSimpleHttpClient.isAuthForwardable("https://h/a",
"http://h/b"));
+ assertFalse(TimeStampSimpleHttpClient.isAuthForwardable("https://h/a",
"https://other/b"));
}
private static CompletableFuture<List<String>> serve(ServerSocket server,
String response) {
+ return serveAll(server, response).thenApply(reqs -> reqs.get(0));
+ }
+
+ /** answers one request per response, in order, and returns the request
line and headers of each */
+ private static CompletableFuture<List<List<String>>> serveAll(ServerSocket
server, String... responses) {
return CompletableFuture.supplyAsync(() -> {
- try (Socket s = server.accept()) {
- BufferedReader r = new BufferedReader(new
InputStreamReader(s.getInputStream(), StandardCharsets.ISO_8859_1));
- List<String> headers = new ArrayList<>();
- int contentLength = 0;
- for (String line; (line = r.readLine()) != null &&
!line.isEmpty(); ) {
- headers.add(line);
- if
(line.toLowerCase(Locale.ROOT).startsWith("content-length:")) {
- contentLength =
Integer.parseInt(line.substring(15).trim());
- }
- }
- for (int i = 0; i < contentLength; i++) {
- r.read();
- }
- OutputStream os = s.getOutputStream();
- os.write(response.getBytes(StandardCharsets.ISO_8859_1));
- os.flush();
- return headers;
- } catch (IOException e) {
- throw new IllegalStateException(e);
+ List<List<String>> requests = new ArrayList<>();
+ for (String response : responses) {
+ requests.add(serveOne(server, response));
}
+ return requests;
});
}
+
+ private static List<String> serveOne(ServerSocket server, String response)
{
+ try (Socket s = server.accept()) {
+ BufferedReader r = new BufferedReader(new
InputStreamReader(s.getInputStream(), StandardCharsets.ISO_8859_1));
+ List<String> headers = new ArrayList<>();
+ int contentLength = 0;
+ for (String line; (line = r.readLine()) != null &&
!line.isEmpty(); ) {
+ headers.add(line);
+ if
(line.toLowerCase(Locale.ROOT).startsWith("content-length:")) {
+ contentLength =
Integer.parseInt(line.substring(15).trim());
+ }
+ }
+ for (int i = 0; i < contentLength; i++) {
+ r.read();
+ }
+ OutputStream os = s.getOutputStream();
+ os.write(response.getBytes(StandardCharsets.ISO_8859_1));
+ os.flush();
+ return headers;
+ } catch (IOException e) {
+ throw new IllegalStateException(e);
+ }
+ }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]