diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java index 43bd612..484581c 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotDeleteCommand.java @@ -47,7 +47,12 @@ public class SnapshotDeleteCommand implements Callable { printer.println(Ansi.green("Snapshot deleted:") + " " + name); return 0; } catch (FlociException e) { - printer.error("Failed to delete snapshot: " + e.getMessage()); + if (e.endpointMissing()) { + printer.error("Snapshot API not available on this server version.\n" + + "Track progress: " + profile.serverRepo() + "/issues"); + } else { + printer.error("Failed to delete snapshot: " + e.getMessage()); + } return 1; } } diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java index 5e9dfdc..9a234a0 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotExportCommand.java @@ -38,7 +38,7 @@ public class SnapshotExportCommand implements Callable { public Integer call() { Printer printer = global.printer(); // TODO: implement GET /_floci/snapshots//export streaming to file - printer.error("snapshot export requires floci-server >= 1.6.0\n" + + printer.error("snapshot export is not available yet: the emulator has no snapshot export API.\n" + "Track progress: " + profile.serverRepo() + "/issues"); return 1; } diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java index a19c1e6..b87b4b4 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotImportCommand.java @@ -38,7 +38,7 @@ public class SnapshotImportCommand implements Callable { public Integer call() { Printer printer = global.printer(); // TODO: implement POST /_floci/snapshots/import with multipart upload - printer.error("snapshot import requires floci-server >= 1.6.0\n" + + printer.error("snapshot import is not available yet: the emulator has no snapshot import API.\n" + "Track progress: " + profile.serverRepo() + "/issues"); return 1; } diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java index 226aaf4..4ae84af 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotListCommand.java @@ -54,7 +54,7 @@ public class SnapshotListCommand implements Callable { node.forEach(s -> printer.println(" " + s.asText())); return 0; } catch (FlociException e) { - if (e.getMessage().contains("404") || e.getMessage().contains("501")) { + if (e.endpointMissing()) { printer.error("Snapshot API not available on this server version.\n" + "Track progress: " + profile.serverRepo() + "/issues"); } else { diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java index 9a94732..5436c78 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotLoadCommand.java @@ -47,7 +47,7 @@ public class SnapshotLoadCommand implements Callable { printer.println(Ansi.green("Snapshot loaded:") + " " + name); return 0; } catch (FlociException e) { - if (e.getMessage().contains("404") || e.getMessage().contains("501")) { + if (e.endpointMissing()) { printer.error("Snapshot API not available on this server version.\n" + "Track progress: " + profile.serverRepo() + "/issues"); } else { diff --git a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java index f8d83ad..1badd36 100644 --- a/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java +++ b/src/main/java/io/floci/cli/commands/snapshot/SnapshotSaveCommand.java @@ -45,12 +45,16 @@ public class SnapshotSaveCommand implements Callable { // so a container started with --port is still found without --endpoint. String effectiveEndpoint = global.resolvedEndpoint(new DockerClient()); FlociHttpClient client = new FlociHttpClient(effectiveEndpoint, profile); + if (message != null && !message.isBlank()) { + // The snapshot API contract has no description field yet; say so rather than drop it. + printer.warn("--message is not sent: the snapshot API does not take a description yet."); + } try { client.postSnapshot(name); printer.println(Ansi.green("Snapshot saved:") + " " + name); return 0; } catch (FlociException e) { - if (e.getMessage().contains("404") || e.getMessage().contains("501")) { + if (e.endpointMissing()) { printer.error("Snapshot API not available on this server version.\n" + "Track progress: " + profile.serverRepo() + "/issues"); } else { diff --git a/src/main/java/io/floci/cli/http/FlociException.java b/src/main/java/io/floci/cli/http/FlociException.java index 222d7b9..e632093 100644 --- a/src/main/java/io/floci/cli/http/FlociException.java +++ b/src/main/java/io/floci/cli/http/FlociException.java @@ -1,7 +1,29 @@ package io.floci.cli.http; public class FlociException extends Exception { + + private final int status; + public FlociException(String message) { + this(message, 0); + } + + /** An error the server answered with HTTP {@code status}. */ + public FlociException(String message, int status) { super(message); + this.status = status; + } + + /** The HTTP status the server answered with, or 0 when the failure was not an HTTP response. */ + public int status() { + return status; + } + + /** + * The server has no such endpoint (404) or does not implement it (501). Asked of the status, + * never of the message: the message carries the request path, and a path can contain "404". + */ + public boolean endpointMissing() { + return status == 404 || status == 501; } } diff --git a/src/main/java/io/floci/cli/http/FlociHttpClient.java b/src/main/java/io/floci/cli/http/FlociHttpClient.java index 73ea7f1..def58c9 100644 --- a/src/main/java/io/floci/cli/http/FlociHttpClient.java +++ b/src/main/java/io/floci/cli/http/FlociHttpClient.java @@ -6,10 +6,12 @@ import io.floci.cli.ProductProfile; import java.net.ConnectException; import java.net.URI; +import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.net.http.HttpTimeoutException; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ArrayList; import java.util.List; @@ -59,11 +61,14 @@ public class FlociHttpClient { int query = base.indexOf('?'); this.query = query >= 0 ? base.substring(query) : ""; base = query >= 0 ? base.substring(0, query) : base; - this.endpoint = base.endsWith("/") ? base.substring(0, base.length() - 1) : base; + this.endpoint = base.replaceAll("/+$", ""); this.controlPrefix = controlPrefix.endsWith("/") ? controlPrefix.substring(0, controlPrefix.length() - 1) : controlPrefix; + // HTTP/1.1: the emulators speak it, and the default (HTTP/2) first tries an h2c upgrade on + // every plain-http request. Redirects are not followed; see checkStatus. this.http = HttpClient.newBuilder() + .version(HttpClient.Version.HTTP_1_1) .connectTimeout(Duration.ofSeconds(5)) .build(); } @@ -159,7 +164,7 @@ public class FlociHttpClient { message.contains("not available yet")); } if (resp.statusCode() >= 400) { - throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); + throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path, resp.statusCode()); } return resp.body(); } catch (FlociException e) { @@ -172,11 +177,11 @@ public class FlociHttpClient { } public Map postSnapshot(String name) throws FlociException { - return postJson(controlPrefix + "/snapshots/" + name, "{}"); + return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name), "{}"); } public Map loadSnapshot(String name) throws FlociException { - return postJson(controlPrefix + "/snapshots/" + name + "/load", "{}"); + return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name) + "/load", "{}"); } public JsonNode listSnapshots() throws FlociException { @@ -184,7 +189,7 @@ public class FlociHttpClient { } public void deleteSnapshot(String name) throws FlociException { - deleteRequest(controlPrefix + "/snapshots/" + name); + deleteRequest(controlPrefix + "/snapshots/" + snapshotSegment(name)); } private JsonNode getJson(String path) throws FlociException { @@ -215,10 +220,8 @@ public class FlociHttpClient { if (e.getCause() instanceof HttpTimeoutException) throw timedOut(path, timeout); throw new FlociException("Request failed: " + e.getCause().getMessage()); } - if (resp.statusCode() >= 400) { - throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); - } - return MAPPER.readTree(resp.body()); + checkStatus(resp, path); + return readJson(resp.body(), path); } catch (FlociException e) { throw e; } catch (InterruptedException e) { @@ -246,11 +249,9 @@ public class FlociHttpClient { .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.ofString()); - if (resp.statusCode() >= 400) { - throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); - } + checkStatus(resp, path); if (resp.body() == null || resp.body().isBlank()) return Map.of(); - return MAPPER.readValue(resp.body(), Map.class); + return MAPPER.convertValue(readJson(resp.body(), path), Map.class); } catch (FlociException e) { throw e; } catch (ConnectException e) { @@ -268,9 +269,7 @@ public class FlociHttpClient { .DELETE() .build(); HttpResponse resp = http.send(req, HttpResponse.BodyHandlers.discarding()); - if (resp.statusCode() >= 400) { - throw new FlociException("Server returned HTTP " + resp.statusCode() + " for " + path); - } + checkStatus(resp, path); } catch (FlociException e) { throw e; } catch (Exception e) { @@ -285,4 +284,36 @@ public class FlociHttpClient { private URI url(String path) { return URI.create(endpoint + path + query); } + + // A redirect usually means --endpoint names a proxy or the wrong address; following it + // silently could send requests elsewhere, so it is reported instead. + private void checkStatus(HttpResponse resp, String path) throws FlociException { + int status = resp.statusCode(); + if (status >= 300 && status < 400) { + String location = resp.headers().firstValue("Location").orElse("another address"); + throw new FlociException("Server redirected " + path + " to " + location + ".\n" + + "Point --endpoint at the address Floci listens on."); + } + if (status >= 400) { + throw new FlociException("Server returned HTTP " + status + " for " + path, status); + } + } + + private JsonNode readJson(String body, String path) throws FlociException { + try { + return MAPPER.readTree(body); + } catch (Exception e) { + throw new FlociException("The response from " + endpoint + path + " is not JSON, so this may not be a Floci server.\n" + + "Run '" + commandPrefix + " status' to see the endpoint the emulator answers on."); + } + } + + /** A snapshot name as one URL path segment; names that could change the path are refused. */ + static String snapshotSegment(String name) throws FlociException { + if (name == null || name.isBlank() || name.equals(".") || name.equals("..") || name.contains("/")) { + throw new FlociException("Invalid snapshot name '" + name + "'.\n" + + "Use a name that is not '.' or '..' and has no '/'."); + } + return URLEncoder.encode(name, StandardCharsets.UTF_8).replace("+", "%20"); + } } diff --git a/src/test/java/io/floci/cli/unit/FlociHttpClientRobustnessTest.java b/src/test/java/io/floci/cli/unit/FlociHttpClientRobustnessTest.java new file mode 100644 index 0000000..d4ee096 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/FlociHttpClientRobustnessTest.java @@ -0,0 +1,99 @@ +package io.floci.cli.unit; + +import com.sun.net.httpserver.HttpServer; +import io.floci.cli.http.FlociException; +import io.floci.cli.http.FlociHttpClient; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-047: what FlociHttpClient sends, and how it reports responses that are not what it expects. */ +class FlociHttpClientRobustnessTest { + + private HttpServer server; + private final AtomicReference lastPath = new AtomicReference<>(); + private final AtomicInteger status = new AtomicInteger(200); + private final AtomicReference body = new AtomicReference<>("{\"version\":\"1.0\",\"services\":[]}"); + private final AtomicReference location = new AtomicReference<>(); + + @BeforeEach + void start() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + lastPath.set(exchange.getRequestURI().getRawPath()); + if (location.get() != null) exchange.getResponseHeaders().add("Location", location.get()); + byte[] bytes = body.get().getBytes(StandardCharsets.UTF_8); + exchange.sendResponseHeaders(status.get(), bytes.length == 0 ? -1 : bytes.length); + if (bytes.length > 0) { + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + exchange.close(); + }); + server.start(); + } + + @AfterEach + void stop() { + server.stop(0); + } + + private String endpoint() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @Test + void everyTrailingSlashIsStripped() throws Exception { + new FlociHttpClient(endpoint() + "///", "/_floci").health(); + + assertEquals("/_floci/health", lastPath.get()); + } + + @Test + void aBodyThatIsNotJsonIsReportedAsSuch() { + body.set("OK"); + + FlociException e = assertThrows(FlociException.class, () -> new FlociHttpClient(endpoint(), "/_floci").health()); + assertTrue(e.getMessage().contains("is not JSON"), e.getMessage()); + } + + @Test + void aRedirectIsReportedNotFollowed() { + status.set(302); + body.set(""); + location.set("http://elsewhere.example/_floci/health"); + + FlociException e = assertThrows(FlociException.class, () -> new FlociHttpClient(endpoint(), "/_floci").health()); + assertTrue(e.getMessage().contains("redirected"), e.getMessage()); + assertTrue(e.getMessage().contains("elsewhere.example"), e.getMessage()); + } + + @Test + void snapshotNamesAreOnePathSegment() throws Exception { + status.set(204); + body.set(""); + + new FlociHttpClient(endpoint(), "/_floci").deleteSnapshot("my snap?x"); + + assertEquals("/_floci/snapshots/my%20snap%3Fx", lastPath.get()); + } + + @Test + void snapshotNamesThatWouldChangeThePathAreRefused() { + FlociHttpClient client = new FlociHttpClient(endpoint(), "/_floci"); + for (String bad : new String[]{"..", ".", "a/b", "../escape"}) { + FlociException e = assertThrows(FlociException.class, () -> client.deleteSnapshot(bad), bad); + assertTrue(e.getMessage().contains("Invalid snapshot name"), e.getMessage()); + } + assertNull(lastPath.get(), "nothing reached the server"); + } +} diff --git a/src/test/java/io/floci/cli/unit/SnapshotCommandsTest.java b/src/test/java/io/floci/cli/unit/SnapshotCommandsTest.java new file mode 100644 index 0000000..1bd3f05 --- /dev/null +++ b/src/test/java/io/floci/cli/unit/SnapshotCommandsTest.java @@ -0,0 +1,106 @@ +package io.floci.cli.unit; + +import com.sun.net.httpserver.HttpServer; +import io.floci.cli.FlociCli; +import io.floci.cli.config.ProfileStore; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.net.InetSocketAddress; +import java.nio.file.Path; + +import static org.junit.jupiter.api.Assertions.*; + +/** BL-048: the snapshot commands against a server that has no snapshot API (404). */ +class SnapshotCommandsTest { + + @TempDir + Path tempDir; + + private HttpServer server; + private volatile int status = 404; + + @BeforeEach + void start() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/", exchange -> { + exchange.sendResponseHeaders(status, -1); + exchange.close(); + }); + server.start(); + } + + @AfterEach + void stop() { + server.stop(0); + } + + private String[] run(String... args) { + String[] all = new String[args.length + 4]; + System.arraycopy(args, 0, all, 0, args.length); + all[args.length] = "--endpoint"; + all[args.length + 1] = "http://127.0.0.1:" + server.getAddress().getPort(); + all[args.length + 2] = "--container"; + all[args.length + 3] = "floci-snapshot-test-none"; + PrintStream out = System.out; + PrintStream err = System.err; + ByteArrayOutputStream outBuf = new ByteArrayOutputStream(); + ByteArrayOutputStream errBuf = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outBuf)); + System.setErr(new PrintStream(errBuf)); + try { + int exit = FlociCli.buildCommandLine(new ProfileStore(tempDir)).execute(all); + return new String[]{String.valueOf(exit), outBuf.toString(), errBuf.toString()}; + } finally { + System.setOut(out); + System.setErr(err); + } + } + + @Test + void deleteSaysTheApiIsMissingLikeSaveAndLoad() { + String[] r = run("snapshot", "delete", "nightly"); + + assertEquals("1", r[0]); + assertTrue(r[2].contains("Snapshot API not available"), r[2]); + } + + @Test + void aMessageIsNotDroppedSilently() { + String[] r = run("snapshot", "save", "nightly", "-m", "before upgrade"); + + assertTrue(r[2].contains("--message is not sent"), r[2]); + } + + /** + * Only the status says the API is missing. A name that happens to contain "404" or "501" must + * not turn a real server error into "not available". + */ + @ParameterizedTest + @CsvSource({"delete, nightly404", "save, build-501", "load, 404"}) + void aStatusLookingNameDoesNotHideARealError(String command, String name) { + status = 500; + + String[] r = run("snapshot", command, name); + + assertEquals("1", r[0]); + assertFalse(r[2].contains("Snapshot API not available"), r[2]); + assertTrue(r[2].contains("HTTP 500"), r[2]); + } + + @ParameterizedTest + @CsvSource({"404", "501"}) + void bothMissingEndpointStatusesReadAsNotAvailable(int missing) { + status = missing; + + String[] r = run("snapshot", "delete", "nightly"); + + assertTrue(r[2].contains("Snapshot API not available"), r[2]); + } +}