mirror of
https://github.com/floci-io/floci-cli.git
synced 2026-11-22 21:50:47 -05:00
fix(http): keep snapshot names in one path segment and report odd server responses clearly
Snapshot names are URL-encoded and names that would change the path are refused; every trailing slash is stripped from the endpoint; a non-JSON body or a redirect gets a message that says so instead of a parser error; requests use HTTP/1.1. snapshot delete reports a missing snapshot API like save and load, save warns that --message is not sent yet, and export/import no longer cite a server version that does not exist. Signed-off-by: Hector Ventura <hectorvent@gmail.com>
This commit is contained in:
7 files changed
+234
-18
No files matched your search
@@ -47,7 +47,12 @@ public class SnapshotDeleteCommand implements Callable<Integer> {
|
||||
printer.println(Ansi.green("Snapshot deleted:") + " " + name);
|
||||
return 0;
|
||||
} catch (FlociException e) {
|
||||
printer.error("Failed to delete snapshot: " + e.getMessage());
|
||||
if (e.getMessage().contains("404") || e.getMessage().contains("501")) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public class SnapshotExportCommand implements Callable<Integer> {
|
||||
public Integer call() {
|
||||
Printer printer = global.printer();
|
||||
// TODO: implement GET /_floci/snapshots/<name>/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;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public class SnapshotImportCommand implements Callable<Integer> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,10 @@ public class SnapshotSaveCommand implements Callable<Integer> {
|
||||
// so a container started with --port <n> 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);
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -172,11 +177,11 @@ public class FlociHttpClient {
|
||||
}
|
||||
|
||||
public Map<String, Object> postSnapshot(String name) throws FlociException {
|
||||
return postJson(controlPrefix + "/snapshots/" + name, "{}");
|
||||
return postJson(controlPrefix + "/snapshots/" + snapshotSegment(name), "{}");
|
||||
}
|
||||
|
||||
public Map<String, Object> 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<String> 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<Void> 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);
|
||||
}
|
||||
}
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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<String> lastPath = new AtomicReference<>();
|
||||
private final AtomicInteger status = new AtomicInteger(200);
|
||||
private final AtomicReference<String> body = new AtomicReference<>("{\"version\":\"1.0\",\"services\":[]}");
|
||||
private final AtomicReference<String> 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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
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 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;
|
||||
|
||||
@BeforeEach
|
||||
void start() throws Exception {
|
||||
server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
server.createContext("/", exchange -> {
|
||||
exchange.sendResponseHeaders(404, -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]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user