Runway 1.1.1
This commit is contained in:
1 parent
07d5bd7e9a
commit
67d61f339c
28 files changed
+826
-38
No files matched your search
@@ -131,6 +131,64 @@ class AppBackupsScreenTest {
|
||||
assertTrue(sites.exists("acme"), "the source site is untouched");
|
||||
}
|
||||
|
||||
/**
|
||||
* A restore applies the hosts and base URL saved in the backup, so the screen then shows them for review with the
|
||||
* hosts editor; saving it goes through Sites -> Edit hosts and changes the site.
|
||||
*/
|
||||
@Test
|
||||
void aRestoreIsFollowedByTheRestoredHostsWithTheirEditor() throws Exception {
|
||||
Site original = sites.find("acme").orElseThrow();
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
backups.backup("acme", baos); // carries acme.test and https://acme.test
|
||||
try {
|
||||
sites.save(new Site("acme", "Acme", List.of("acme.live"), Locale.ENGLISH, List.of(Locale.ENGLISH), null,
|
||||
SiteStatus.ACTIVE));
|
||||
MockHttpSession admin = sessionFor("admin");
|
||||
MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray());
|
||||
mvc.perform(multipart("/__app/backups/acme/restore").file(file).session(admin)
|
||||
.with(csrf()))
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, "acme"));
|
||||
|
||||
String page = mvc.perform(get("/__app/backups").session(admin))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||
assertTrue(page.contains("Review how site acme is reached"), "the review card is shown");
|
||||
assertTrue(page.contains(">acme.test<"), "the hosts as restored from the backup, not acme.live");
|
||||
assertTrue(page.contains(">https://acme.test<"), "the restored base URL");
|
||||
assertTrue(page.contains("action=\"/__app/sites/acme/hosts\""), "the editor posts to Sites -> Edit hosts");
|
||||
assertTrue(page.contains("value=\"acme.test\""), "the editor starts from the hosts as they stand");
|
||||
|
||||
String plain = mvc.perform(get("/__app/backups").session(admin))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||
assertFalse(plain.contains("Review how site"), "no review card without a restore");
|
||||
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/__app/sites/acme/hosts")
|
||||
.session(admin).with(csrf()).param("hosts", "acme.fixed").param("baseUrl", ""))
|
||||
.andExpect(status().is3xxRedirection());
|
||||
assertEquals(List.of("acme.fixed"), sites.find("acme").orElseThrow().hosts(), "corrected from the review");
|
||||
} finally {
|
||||
sites.save(original);
|
||||
}
|
||||
}
|
||||
|
||||
/** A site created from a backup without hosts is not the default site: the review says nothing reaches it. */
|
||||
@Test
|
||||
void aSiteCreatedWithoutHostsIsReportedUnreachableNotAsTheDefault() throws Exception {
|
||||
ByteArrayOutputStream baos = new ByteArrayOutputStream();
|
||||
backups.backup("acme", baos);
|
||||
MockHttpSession admin = sessionFor("admin");
|
||||
MockMultipartFile file = new MockMultipartFile("file", "acme.zip", "application/zip", baos.toByteArray());
|
||||
mvc.perform(multipart("/__app/backups/create-site").file(file).session(admin).with(csrf())
|
||||
.param("newId", "hostless").param("name", "Hostless").param("hosts", ""))
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, "hostless"));
|
||||
String page = mvc.perform(get("/__app/backups").session(admin))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||
assertTrue(page.contains("Review how site hostless is reached"));
|
||||
assertTrue(page.contains("none: no address reaches this site until you give it a host"), "not the default");
|
||||
assertFalse(page.contains("catch-all default site"), "it is not the default site");
|
||||
}
|
||||
|
||||
/** An archive from a newer Runway: the operator is told to upgrade, and nothing is replaced or created. */
|
||||
@Test
|
||||
void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception {
|
||||
|
||||
@@ -284,6 +284,31 @@ class TenantBackupsScreenTest {
|
||||
assertEquals("ORIGINAL_CONTENT", Files.readString(home, StandardCharsets.UTF_8), "the page was restored");
|
||||
}
|
||||
|
||||
/** After a restore the screen shows how the site is reached, read-only: a restore here keeps the hosts. */
|
||||
@Test
|
||||
void aRestoreIsFollowedByTheSitesHostsForReview() throws Exception {
|
||||
MockHttpSession admin = sessionFor("admin");
|
||||
mvc.perform(post("/__admin/backups/create").session(admin).with(csrf())).andExpect(status().is3xxRedirection());
|
||||
mvc.perform(get("/__admin/backups").session(admin)).andExpect(status().isOk()); // the create's redirect
|
||||
String name = backups.list("acme").get(0).name();
|
||||
mvc.perform(post("/__admin/backups/" + name + "/restore").session(admin).with(csrf()))
|
||||
.andExpect(status().is3xxRedirection())
|
||||
.andExpect(flash().attribute(AppBackupsController.REVIEW_HOSTS, Boolean.TRUE));
|
||||
|
||||
MvcResult shown = mvc.perform(get("/__admin/backups").session(admin)).andExpect(status().isOk()).andReturn();
|
||||
String page = shown.getResponse().getContentAsString();
|
||||
assertTrue(page.contains("id=\"bk-review\""), "the review card is shown");
|
||||
assertTrue(page.contains("How the site is reached"));
|
||||
assertTrue(page.contains("only a platform administrator can change them"));
|
||||
assertTrue(page.contains(">localhost<"), "the site's host");
|
||||
assertTrue(page.contains("not set, so https://localhost (https:// and the first host)"), "the derived base URL");
|
||||
assertTrue(!page.contains("/__app/sites/acme/hosts"), "no editor on the site console");
|
||||
|
||||
String plain = mvc.perform(get("/__admin/backups").session(admin))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsString();
|
||||
assertTrue(!plain.contains("id=\"bk-review\""), "no review card without a restore");
|
||||
}
|
||||
|
||||
/** An archive from a newer Runway is refused on both restore paths, with the upgrade message. */
|
||||
@Test
|
||||
void aNewerFormatBackupIsRefusedWithTheUpgradeMessage() throws Exception {
|
||||
|
||||
@@ -26,16 +26,18 @@ import org.springframework.boot.web.server.WebServer;
|
||||
|
||||
/**
|
||||
* The minimum request data rate, against a real Jetty: a body trickled in is cut with {@code 408} instead of holding a
|
||||
* request thread, and a server that is slow to start reading is not blamed for it. Guards the behaviour across Jetty
|
||||
* upgrades, since the rate check is Jetty's.
|
||||
* request thread, whether the servlet reads the stream, form parameters or multipart parts, and a server that is slow
|
||||
* to start reading is not blamed for it. The check is {@link RequestBodyRateHandler}'s; Jetty's own is turned off.
|
||||
*/
|
||||
class SlowClientConfigTest {
|
||||
|
||||
/** The bean, as Spring binds and applies it: the property, the clamp, and every connector of Boot's own Jetty. */
|
||||
@Test
|
||||
void theBoundPropertyReachesEveryConnectorOfTheServerBootBuilds() throws Exception {
|
||||
assertThat(rateOnBootsServer("1024")).containsOnly(1024L).isNotEmpty();
|
||||
assertThat(rateOnBootsServer("-5")).as("a negative value is clamped to off").containsOnly(0L);
|
||||
assertThat(rateOnBootsServer("1024")).as("Jetty's own check off on every connector; ours in Boot's chain")
|
||||
.containsOnly(0L, 1024L * 1_000_000).contains(0L, 1024L * 1_000_000);
|
||||
assertThat(rateOnBootsServer("-5")).as("a negative value is clamped to off, and no handler is installed")
|
||||
.containsOnly(0L).isNotEmpty();
|
||||
}
|
||||
|
||||
private java.util.List<Long> rateOnBootsServer(String configured) throws Exception {
|
||||
@@ -55,6 +57,13 @@ class SlowClientConfigTest {
|
||||
}
|
||||
}
|
||||
}
|
||||
// The handler chain, outermost first: a RequestBodyRateHandler is reported as its rate x 1_000_000.
|
||||
for (org.eclipse.jetty.server.Handler h = ((JettyWebServer) web).getServer().getHandler(); h != null;
|
||||
h = h instanceof org.eclipse.jetty.server.Handler.Wrapper w ? w.getHandler() : null) {
|
||||
if (h instanceof RequestBodyRateHandler rate) {
|
||||
rates.add(rate.bytesPerSecond() * 1_000_000);
|
||||
}
|
||||
}
|
||||
return rates;
|
||||
} finally {
|
||||
web.stop();
|
||||
@@ -70,27 +79,66 @@ class SlowClientConfigTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** How the servlet reads the body: the input stream (Jetty's own check), form parameters, or multipart parts. */
|
||||
private enum Body { STREAM, FORM, MULTIPART, SWALLOWED, ESCAPED }
|
||||
|
||||
/** A server whose servlet reads the whole body after {@code pauseMillis}, with the rate applied by the config. */
|
||||
private int start(long bytesPerSecond, long pauseMillis) throws Exception {
|
||||
return start(bytesPerSecond, pauseMillis, Body.STREAM);
|
||||
}
|
||||
|
||||
private int start(long bytesPerSecond, long pauseMillis, Body body) throws Exception {
|
||||
return start(bytesPerSecond, pauseMillis, body, RequestBodyRateHandler.CREDIT_SECONDS);
|
||||
}
|
||||
|
||||
private int start(long bytesPerSecond, long pauseMillis, Body body, long creditSeconds) throws Exception {
|
||||
server = new Server();
|
||||
ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory());
|
||||
connector.setPort(0);
|
||||
connector.setIdleTimeout(30_000);
|
||||
server.addConnector(connector);
|
||||
ServletContextHandler context = new ServletContextHandler();
|
||||
context.addServlet(new ServletHolder(new HttpServlet() {
|
||||
ServletHolder holder = new ServletHolder(new HttpServlet() {
|
||||
@Override
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
|
||||
protected void doPost(HttpServletRequest request, HttpServletResponse response)
|
||||
throws IOException, jakarta.servlet.ServletException {
|
||||
try {
|
||||
Thread.sleep(pauseMillis);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
response.getWriter().write("read " + request.getInputStream().readAllBytes().length);
|
||||
String read = switch (body) {
|
||||
case STREAM -> "read " + request.getInputStream().readAllBytes().length;
|
||||
case FORM -> "a=" + request.getParameter("a").length();
|
||||
case MULTIPART -> "parts " + request.getParts().size();
|
||||
case SWALLOWED -> { // the read fails and the code carries on as if nothing happened
|
||||
try {
|
||||
request.getInputStream().readAllBytes();
|
||||
} catch (IOException ignored) {
|
||||
// swallowed on purpose
|
||||
}
|
||||
yield "fine";
|
||||
}
|
||||
case ESCAPED -> { // the failure escapes, as from a filter that reads the stream itself
|
||||
request.getInputStream().readAllBytes();
|
||||
yield "unreachable";
|
||||
}
|
||||
};
|
||||
response.getWriter().write(read);
|
||||
}
|
||||
}), "/*");
|
||||
});
|
||||
if (body == Body.MULTIPART) {
|
||||
holder.getRegistration().setMultipartConfig(new jakarta.servlet.MultipartConfigElement(""));
|
||||
}
|
||||
context.addServlet(holder, "/*");
|
||||
server.setHandler(context);
|
||||
assertThat(SlowClientConfig.apply(server, bytesPerSecond)).isEqualTo(1);
|
||||
if (creditSeconds != RequestBodyRateHandler.CREDIT_SECONDS
|
||||
&& server.getHandler() instanceof RequestBodyRateHandler installed) {
|
||||
RequestBodyRateHandler shortCredit = new RequestBodyRateHandler(bytesPerSecond, creditSeconds);
|
||||
shortCredit.setHandler(installed.getHandler());
|
||||
server.setHandler(shortCredit);
|
||||
}
|
||||
server.start();
|
||||
return connector.getLocalPort();
|
||||
}
|
||||
@@ -136,6 +184,133 @@ class SlowClientConfigTest {
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends {@code head}, then {@code drip} one byte a second until the server answers or 20 bytes are sent. */
|
||||
private static String drip(int port, String head) throws Exception {
|
||||
long started = System.nanoTime();
|
||||
try (Socket socket = new Socket("127.0.0.1", port)) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(head.getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
try {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
Thread.sleep(1000);
|
||||
out.write('a');
|
||||
out.flush();
|
||||
}
|
||||
} catch (IOException closedByServer) {
|
||||
// expected: answered and closed while the client was still trickling
|
||||
}
|
||||
String status = statusLine(socket);
|
||||
assertThat(Duration.ofNanos(System.nanoTime() - started)).as("cut long before the idle timeout")
|
||||
.isLessThan(Duration.ofSeconds(15));
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrickledFormIsCutToo() throws Exception {
|
||||
// 1.1.0: form parameters were read past Jetty's own check, and this request was held for the idle timeout.
|
||||
int port = start(1024, 0, Body.FORM);
|
||||
assertThat(drip(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n"
|
||||
+ "Content-Length: 1000\r\nConnection: close\r\n\r\na=")).isEqualTo("HTTP/1.1 408 Request Timeout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrickledMultipartBodyIsCutToo() throws Exception {
|
||||
int port = start(1024, 0, Body.MULTIPART);
|
||||
assertThat(drip(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Type: multipart/form-data; boundary=XyZ\r\n"
|
||||
+ "Content-Length: 1000\r\nConnection: close\r\n\r\n--XyZ\r\n"
|
||||
+ "Content-Disposition: form-data; name=\"a\"\r\n\r\n")).isEqualTo("HTTP/1.1 408 Request Timeout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusedBodyIsAnswered408HoweverTheCodeHandledTheFailedRead() throws Exception {
|
||||
// Measured on 1.1.1-SNAPSHOT before this guard: a route reading the stream itself answered an empty 200.
|
||||
for (Body body : new Body[] {Body.SWALLOWED, Body.ESCAPED}) {
|
||||
int port = start(4096, 0, body);
|
||||
assertThat(drip(port, "POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/octet-stream\r\n"
|
||||
+ "Content-Length: 1000\r\nConnection: close\r\n\r\n")).as(body.name())
|
||||
.isEqualTo("HTTP/1.1 408 Request Timeout");
|
||||
server.stop();
|
||||
server = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBodySentFastAtFirstCannotBuyALongDripLater() throws Exception {
|
||||
// 32 KiB at line speed, then a byte a second: averaged over the whole body (1.1.0, and this fix's first form)
|
||||
// that bought 32 s of dripping at 1 KiB/s, and with 16 MiB over an hour. The credit is capped (2 s here).
|
||||
int port = start(1024, 0, Body.FORM, 2);
|
||||
long started = System.nanoTime();
|
||||
try (Socket socket = new Socket("127.0.0.1", port)) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n"
|
||||
+ "Content-Length: 65536\r\nConnection: close\r\n\r\na=" + "b".repeat(32 * 1024))
|
||||
.getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
try {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
Thread.sleep(1000);
|
||||
out.write('c');
|
||||
out.flush();
|
||||
}
|
||||
} catch (IOException closedByServer) {
|
||||
// expected
|
||||
}
|
||||
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 408 Request Timeout");
|
||||
}
|
||||
assertThat(Duration.ofNanos(System.nanoTime() - started)).isLessThan(Duration.ofSeconds(10));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aSmallFormWhoseOnlyPacketArrivesLateIsAccepted() throws Exception {
|
||||
// A network stall before the body: the body then arrives whole, so no thread is held by a slow client.
|
||||
int port = start(1024, 0, Body.FORM);
|
||||
try (Socket socket = new Socket("127.0.0.1", port)) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n"
|
||||
+ "Content-Length: 12\r\nConnection: close\r\n\r\n").getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
Thread.sleep(2500);
|
||||
out.write("a=1234567890".getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLargeFormAtAGoodRateIsAccepted() throws Exception {
|
||||
int port = start(4096, 0, Body.FORM);
|
||||
int size = 64 * 1024;
|
||||
try (Socket socket = new Socket("127.0.0.1", port)) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n"
|
||||
+ "Content-Length: " + (size + 2) + "\r\nConnection: close\r\n\r\na=")
|
||||
.getBytes(StandardCharsets.US_ASCII));
|
||||
for (int i = 0; i < size / 4096; i++) { // 4 KiB every 100 ms: 40 KiB/s, ten times the minimum
|
||||
out.write("b".repeat(4096).getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
Thread.sleep(100);
|
||||
}
|
||||
socket.setSoTimeout(10_000);
|
||||
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
|
||||
assertThat(response).startsWith("HTTP/1.1 200 OK").endsWith("a=" + size);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aFormServerSlowToReadIsNotBlamed() throws Exception {
|
||||
int port = start(1024, 3000, Body.FORM);
|
||||
try (Socket socket = new Socket("127.0.0.1", port)) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("POST / HTTP/1.1\r\nHost: x\r\nContent-Type: application/x-www-form-urlencoded\r\n"
|
||||
+ "Content-Length: 102\r\nConnection: close\r\n\r\na=" + "c".repeat(100))
|
||||
.getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
assertThat(statusLine(socket)).isEqualTo("HTTP/1.1 200 OK");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void theDefaultIsFourKilobytesPerSecond() {
|
||||
assertThat(new SlowClientConfig.HttpLimitProperties().getMinRequestDataRate()).isEqualTo(4096);
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
package mx.quest.runway.web;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.Socket;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import mx.quest.runway.security.PasswordEncoders;
|
||||
import mx.quest.runway.security.PasswordStrength;
|
||||
import mx.quest.runway.security.Roles;
|
||||
import mx.quest.runway.security.User;
|
||||
import mx.quest.runway.security.UserStore;
|
||||
import mx.quest.runway.site.Site;
|
||||
import mx.quest.runway.site.SiteStatus;
|
||||
import mx.quest.runway.site.SiteStore;
|
||||
import mx.quest.runway.spi.model.Realm;
|
||||
import mx.quest.runway.storage.StorageLayout;
|
||||
import mx.quest.runway.storage.StorageProperties;
|
||||
import mx.quest.runway.storage.YamlStore;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.boot.test.web.server.LocalServerPort;
|
||||
import org.springframework.test.context.DynamicPropertyRegistry;
|
||||
import org.springframework.test.context.DynamicPropertySource;
|
||||
|
||||
/**
|
||||
* The slow-body limit on the running application, where it was missing in 1.1.0: the login forms of both realms and a
|
||||
* multipart post, trickled in, are answered {@code 408} within seconds instead of holding a request thread until the
|
||||
* idle timeout. Through the whole chain (Spring Security reads the login form), which a bare Jetty cannot stand in
|
||||
* for: there, a refused read that the chain treats as a client gone away was answered an empty {@code 200}.
|
||||
*/
|
||||
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
|
||||
class SlowRequestBodyEndToEndTest {
|
||||
|
||||
private static final String HOST = "localhost";
|
||||
/** The console is never served on a site's host; this one is no site's. */
|
||||
private static final String CONSOLE_HOST = "127.0.0.1";
|
||||
|
||||
@DynamicPropertySource
|
||||
static void config(DynamicPropertyRegistry registry) throws IOException {
|
||||
Path external = Files.createTempDirectory("runway-slow-body");
|
||||
StorageProperties props = new StorageProperties();
|
||||
props.setExternal(external);
|
||||
YamlStore yaml = new YamlStore();
|
||||
new SiteStore(StorageLayout.from(props), yaml).save(new Site("acme", "Acme", List.of(HOST), Locale.ENGLISH,
|
||||
List.of(Locale.ENGLISH), null, SiteStatus.ACTIVE, false, null));
|
||||
String hash = PasswordEncoders.argon2id(PasswordStrength.STANDARD).encode("Slow-Body-7x");
|
||||
new UserStore(yaml).save(external.resolve("app-users.yml"),
|
||||
new User("app-master", "root", hash, "Root", "", true, true, Realm.APPLICATION,
|
||||
Set.of(Roles.SYSTEM_SUPERADMIN), List.of()));
|
||||
registry.add("runway.storage.external", () -> external.toString());
|
||||
registry.add("runway.security.app-master-id", () -> "app-master");
|
||||
registry.add("runway.health.content-check", () -> "false");
|
||||
registry.add("runway.http.min-request-data-rate", () -> "1024");
|
||||
}
|
||||
|
||||
@LocalServerPort
|
||||
private int port;
|
||||
|
||||
/** Sends the head of a 1000-byte body, then one byte a second; returns the status line and how long it took. */
|
||||
private String drip(String path, String contentType, String bodyStart) throws Exception {
|
||||
String host = path.startsWith("/app/") ? CONSOLE_HOST : HOST;
|
||||
long started = System.nanoTime();
|
||||
try (Socket socket = new Socket("127.0.0.1", port)) {
|
||||
OutputStream out = socket.getOutputStream();
|
||||
out.write(("POST " + path + " HTTP/1.1\r\nHost: " + host + "\r\nContent-Type: " + contentType
|
||||
+ "\r\nContent-Length: 1000\r\nConnection: close\r\n\r\n" + bodyStart)
|
||||
.getBytes(StandardCharsets.US_ASCII));
|
||||
out.flush();
|
||||
try {
|
||||
for (int i = 0; i < 20; i++) {
|
||||
Thread.sleep(1000);
|
||||
out.write('a');
|
||||
out.flush();
|
||||
}
|
||||
} catch (IOException closedByServer) {
|
||||
// expected: answered and closed while the client was still trickling
|
||||
}
|
||||
socket.setSoTimeout(40_000);
|
||||
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
|
||||
assertThat(Duration.ofNanos(System.nanoTime() - started)).as(path + ": cut long before the idle timeout")
|
||||
.isLessThan(Duration.ofSeconds(15));
|
||||
return response.isEmpty() ? "" : response.substring(0, response.indexOf("\r\n"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrickledSiteLoginIsAnswered408() throws Exception {
|
||||
assertThat(drip("/login", "application/x-www-form-urlencoded", "username="))
|
||||
.isEqualTo("HTTP/1.1 408 Request Timeout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrickledConsoleLoginIsAnswered408() throws Exception {
|
||||
assertThat(drip("/app/login", "application/x-www-form-urlencoded", "username="))
|
||||
.isEqualTo("HTTP/1.1 408 Request Timeout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTrickledMultipartPostIsAnswered408() throws Exception {
|
||||
assertThat(drip("/app/login", "multipart/form-data; boundary=XyZ",
|
||||
"--XyZ\r\nContent-Disposition: form-data; name=\"username\"\r\n\r\n"))
|
||||
.isEqualTo("HTTP/1.1 408 Request Timeout");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLoginSentAtOnceIsNotTouched() throws Exception {
|
||||
try (Socket socket = new Socket("127.0.0.1", port)) {
|
||||
String body = "username=root&password=wrong";
|
||||
socket.getOutputStream().write(("POST /app/login HTTP/1.1\r\nHost: " + CONSOLE_HOST
|
||||
+ "\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: " + body.length()
|
||||
+ "\r\nConnection: close\r\n\r\n" + body).getBytes(StandardCharsets.US_ASCII));
|
||||
socket.setSoTimeout(10_000);
|
||||
String response = new String(socket.getInputStream().readAllBytes(), StandardCharsets.US_ASCII);
|
||||
assertThat(response).as("refused for its missing CSRF token, as before: not a slow body")
|
||||
.startsWith("HTTP/1.1 403");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user