Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rename websocket notification channel URL path #537

Merged
merged 18 commits into from
Jul 2, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions HTTP_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
| What you want to do | Which handler you should use |
| ------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| **Miscellaneous** | |
| Get a URL you can use to access Cryostat's WebSocket command channel | [`ClientUrlGetHandler`](#ClientUrlGetHandler) |
| Get a URL you can use to access Cryostat's WebSocket notification channel | [`NotificationsUrlGetHandler`](#NotificationsUrlGetHandler) |
| Scan for and get a list of target JVMs visible to Cryostat | [`TargetsGetHandler`](#TargetsGetHandler) |
| Get a static asset from the web client | [`StaticAssetsGetHandler`](#StaticAssetsGetHandler) |
| Send a `GET` request to a path not supported by this API | [`WebClientAssetsGetHandler`](#WebClientAssetsGetHandler) |
Expand Down Expand Up @@ -82,25 +82,25 @@
```


* #### `ClientUrlGetHandler`
* #### `NotificationsUrlGetHandler`

###### synopsis
Returns a URL that a client can connect to, to access Cryostat's
WebSocket command channel (see [COMMANDS.md](COMMANDS.md)).
WebSocket notification channel.

###### request
`GET /api/v1/clienturl`
`GET /api/v1/notifications_url`

###### response
`200` - The body is `{"clientUrl":"$URL"}`.
`200` - The body is `{"notificationsUrl":"$URL"}`.

`500` - The URL could not be constructed due to an error with the socket
or the host. Or there was an unexpected error. The body is an error message.

###### example
```
$ curl localhost:8181/api/v1/clienturl
{"clientUrl":"ws://0.0.0.0:8181/api/v1/command"}
$ curl localhost:8181/api/v1/notifications_url
{"notificationsUrl":"ws://0.0.0.0:8181/api/v1/notifications"}
```


Expand Down
5 changes: 4 additions & 1 deletion src/main/java/io/cryostat/messaging/MessagingServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,10 @@ public void start() throws SocketException, UnknownHostException {

server.websocketHandler(
(sws) -> {
if (!"/api/v1/command".equals(sws.path())) {
if ("/api/v1/command".equals(sws.path())) {
sws.reject(410);
return;
} else if (!"/api/v1/notifications".equals(sws.path())) {
andrewazores marked this conversation as resolved.
Show resolved Hide resolved
sws.reject(404);
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public abstract class HttpApiV1Module {

@Binds
@IntoSet
abstract RequestHandler bindClientUrlGetHandler(ClientUrlGetHandler handler);
abstract RequestHandler bindNotificationsUrlGetHandler(NotificationsUrlGetHandler handler);

@Binds
@IntoSet
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,14 +55,14 @@
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.impl.HttpStatusException;

class ClientUrlGetHandler implements RequestHandler {
class NotificationsUrlGetHandler implements RequestHandler {

private final Gson gson;
private final boolean isSsl;
private final NetworkConfiguration netConf;

@Inject
ClientUrlGetHandler(Gson gson, HttpServer server, NetworkConfiguration netConf) {
NotificationsUrlGetHandler(Gson gson, HttpServer server, NetworkConfiguration netConf) {
this.gson = gson;
this.isSsl = server.isSsl();
this.netConf = netConf;
Expand All @@ -80,7 +80,7 @@ public HttpMethod httpMethod() {

@Override
public String path() {
return basePath() + "clienturl";
return basePath() + "notifications_url";
}

@Override
Expand All @@ -94,13 +94,13 @@ public void handle(RoutingContext ctx) {
try {
// TODO replace String.format with URIBuilder or something else than manual string
// construction
String clientUrl =
String notificationsUrl =
String.format(
"%s://%s:%d/api/v1/command",
"%s://%s:%d/api/v1/notifications",
isSsl ? "wss" : "ws",
netConf.getWebServerHost(),
netConf.getExternalWebServerPort());
ctx.response().end(gson.toJson(Map.of("clientUrl", clientUrl)));
ctx.response().end(gson.toJson(Map.of("notificationsUrl", notificationsUrl)));
} catch (SocketException | UnknownHostException e) {
throw new HttpStatusException(500, e);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ void webSocketCloseHandlerShouldRemoveConnection()
SocketAddress addr = Mockito.mock(SocketAddress.class);
when(addr.toString()).thenReturn("mockaddr");
when(sws.remoteAddress()).thenReturn(addr);
when(sws.path()).thenReturn("/api/v1/command");
when(sws.path()).thenReturn("/api/v1/notifications");
server.start();

ArgumentCaptor<Handler> websocketHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,20 +68,20 @@
import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith(MockitoExtension.class)
class ClientUrlGetHandlerTest {
class NotificationsUrlGetHandlerTest {

@Nested
class WithoutSsl {

ClientUrlGetHandler handler;
NotificationsUrlGetHandler handler;
@Mock HttpServer httpServer;
@Mock NetworkConfiguration netConf;
@Mock Logger logger;
Gson gson = MainModule.provideGson(logger);

@BeforeEach
void setup() {
this.handler = new ClientUrlGetHandler(gson, httpServer, netConf);
this.handler = new NotificationsUrlGetHandler(gson, httpServer, netConf);
}

@Test
Expand All @@ -91,7 +91,7 @@ void shouldBeGETRequest() {

@Test
void shouldHaveCorrectPath() {
MatcherAssert.assertThat(handler.path(), Matchers.equalTo("/api/v1/clienturl"));
MatcherAssert.assertThat(handler.path(), Matchers.equalTo("/api/v1/notifications_url"));
}

@Test
Expand All @@ -100,7 +100,7 @@ void shouldBeAsync() {
}

@Test
void shouldHandleClientUrlRequest() throws SocketException, UnknownHostException {
void shouldHandleNotificationsUrlRequest() throws SocketException, UnknownHostException {
RoutingContext ctx = mock(RoutingContext.class);
HttpServerResponse rep = mock(HttpServerResponse.class);
when(ctx.response()).thenReturn(rep);
Expand All @@ -111,7 +111,8 @@ void shouldHandleClientUrlRequest() throws SocketException, UnknownHostException

InOrder inOrder = inOrder(rep);
inOrder.verify(rep).putHeader(HttpHeaders.CONTENT_TYPE, HttpMimeType.JSON.mime());
inOrder.verify(rep).end("{\"clientUrl\":\"ws://hostname:1/api/v1/command\"}");
inOrder.verify(rep)
.end("{\"notificationsUrl\":\"ws://hostname:1/api/v1/notifications\"}");
}

@Test
Expand All @@ -128,7 +129,7 @@ void shouldBubbleInternalServerErrorIfHandlerThrows()
@Nested
class WithSsl {

ClientUrlGetHandler handler;
NotificationsUrlGetHandler handler;
@Mock Logger logger;
@Mock HttpServer httpServer;
@Mock NetworkConfiguration netConf;
Expand All @@ -137,11 +138,12 @@ class WithSsl {
@BeforeEach
void setup() {
when(httpServer.isSsl()).thenReturn(true);
this.handler = new ClientUrlGetHandler(gson, httpServer, netConf);
this.handler = new NotificationsUrlGetHandler(gson, httpServer, netConf);
}

@Test
void shouldHandleClientUrlRequestWithWss() throws SocketException, UnknownHostException {
void shouldHandleNotificationsUrlRequestWithWss()
throws SocketException, UnknownHostException {
RoutingContext ctx = mock(RoutingContext.class);
HttpServerResponse rep = mock(HttpServerResponse.class);
when(ctx.response()).thenReturn(rep);
Expand All @@ -152,7 +154,8 @@ void shouldHandleClientUrlRequestWithWss() throws SocketException, UnknownHostEx

InOrder inOrder = inOrder(rep);
inOrder.verify(rep).putHeader(HttpHeaders.CONTENT_TYPE, HttpMimeType.JSON.mime());
inOrder.verify(rep).end("{\"clientUrl\":\"wss://hostname:1/api/v1/command\"}");
inOrder.verify(rep)
.end("{\"notificationsUrl\":\"wss://hostname:1/api/v1/notifications\"}");
}
}
}
83 changes: 83 additions & 0 deletions src/test/java/itest/MessagingServerIT.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright The Cryostat Authors
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or data
* (collectively the "Software"), free of charge and under any and all copyright
* rights in the Software, and any and all patent rights owned or freely
* licensable by each licensor hereunder covering either (i) the unmodified
* Software as contributed to or provided by such licensor, or (ii) the Larger
* Works (as defined below), to deal in both
*
* (a) the Software, and
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software (each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
* The above copyright notice and either this complete permission notice or at
* a minimum a reference to the UPL must be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package itest;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import io.vertx.core.json.JsonObject;
import itest.bases.StandardSelfTest;
import itest.util.Utils;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class MessagingServerIT extends StandardSelfTest {

public static final String DEPRECATED_COMMAND_PATH = "/api/v1/command";

public static CompletableFuture<JsonObject> sendMessage(String command, String... args)
throws InterruptedException, ExecutionException, TimeoutException {
CompletableFuture<JsonObject> future = new CompletableFuture<>();

Utils.HTTP_CLIENT.webSocket(
DEPRECATED_COMMAND_PATH,
ar -> {
if (ar.failed()) {
future.completeExceptionally(ar.cause());
} else {
future.complete(null);
}
andrewazores marked this conversation as resolved.
Show resolved Hide resolved
});

return future;
}

@Test
public void shouldRejectDeprecatedCommandPathWith410StatusCode() throws Exception {
ExecutionException ex =
Assertions.assertThrows(
ExecutionException.class,
() -> sendMessage("ping").get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS));
String errorMessage = "Websocket connection attempt returned HTTP status code 410";
MatcherAssert.assertThat(ex.getCause().getMessage(), Matchers.equalTo(errorMessage));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ClientUrlIT extends StandardSelfTest {
public class NotificationsUrlIT extends StandardSelfTest {

HttpRequest<Buffer> req;

@BeforeEach
void createRequest() {
req = webClient.get("/api/v1/clienturl");
req = webClient.get("/api/v1/notifications_url");
}

@Test
Expand Down Expand Up @@ -119,7 +119,7 @@ public void shouldReturnJsonMessage() throws Exception {
future.get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS),
Matchers.equalTo(
String.format(
"{\"clientUrl\":\"ws://0.0.0.0:%d/api/v1/command\"}",
"{\"notificationsUrl\":\"ws://0.0.0.0:%d/api/v1/notifications\"}",
Utils.WEB_PORT)));
}
}
10 changes: 6 additions & 4 deletions src/test/java/itest/bases/StandardSelfTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public static CompletableFuture<JsonObject> sendMessage(String command, String..
CompletableFuture<JsonObject> future = new CompletableFuture<>();

Utils.HTTP_CLIENT.webSocket(
getClientUrl().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS),
getNotificationsUrl().get(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS),
ar -> {
if (ar.failed()) {
future.completeExceptionally(ar.cause());
Expand Down Expand Up @@ -141,15 +141,17 @@ public static boolean assertRequestStatus(
return true;
}

private static Future<String> getClientUrl() {
private static Future<String> getNotificationsUrl() {
CompletableFuture<String> future = new CompletableFuture<>();
webClient
.get("/api/v1/clienturl")
.get("/api/v1/notifications_url")
.send(
ar -> {
if (ar.succeeded()) {
future.complete(
ar.result().bodyAsJsonObject().getString("clientUrl"));
ar.result()
.bodyAsJsonObject()
.getString("notificationsUrl"));
} else {
future.completeExceptionally(ar.cause());
}
Expand Down
2 changes: 1 addition & 1 deletion web-client