Skip to content

Commit

Permalink
Failing unit test to show that forwarder doesn't close connection whe…
Browse files Browse the repository at this point in the history
…n remote server does.
  • Loading branch information
tsoiland committed May 12, 2021
1 parent b87f21b commit 4a7afbc
Showing 1 changed file with 43 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,17 @@
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.sshd.server.forward.AcceptAllForwardingFilter;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.stream.Collectors;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
Expand Down Expand Up @@ -72,6 +74,45 @@ public void shouldDynamicallyForwardPortForLocalhost() throws IOException {
assertThat(httpGet("127.0.0.1", bind.getPort()), equalTo(200));
}

@Test
public void shouldHaveHttpServerThatClosesConnectionAfterResponse() throws IOException {
// Just to check that the test server does close connections before we try through the forwarder...
httpGetAndAssertConnectionClosedByServer(8080);
}

@Test(timeout = 10_000)
public void shouldCloseConnectionWhenRemoteServerClosesConnection() throws IOException {
SSHClient sshClient = getFixtureClient();
RemotePortForwarder.Forward bind = forwardPort(sshClient, "127.0.0.1", new SinglePort(0));

httpGetAndAssertConnectionClosedByServer(bind.getPort());
}

private static void httpGetAndAssertConnectionClosedByServer(int port) throws IOException {
System.out.println("HTTP GET to port: " + port);
try (Socket socket = new Socket("localhost", port)) {
// Send a basic HTTP GET
// It returns 400 Bad Request because it's missing a bunch of info, but the HTTP response doesn't matter, we just want to test the connection closing.
OutputStream outputStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream);
writer.println("GET / HTTP/1.1");
writer.println("");
writer.flush();

// Read the HTTP response
InputStream inputStream = socket.getInputStream();
String result = new BufferedReader(new InputStreamReader(inputStream))
.lines().collect(Collectors.joining("\n"));
System.out.println(result);

// Attempt to read more. If the server has closed the connection this will return -1
int read = inputStream.read();

// Assert input stream was closed by server.
Assert.assertEquals(-1, read);
}
}

@Test
public void shouldDynamicallyForwardPortForAllIPv4() throws IOException {
SSHClient sshClient = getFixtureClient();
Expand Down

0 comments on commit 4a7afbc

Please sign in to comment.