diff --git a/apis/com.dbeaver.datadam.dam.remote.api/README.md b/apis/com.dbeaver.datadam.dam.remote.api/README.md index 984e831..26fd290 100644 --- a/apis/com.dbeaver.datadam.dam.remote.api/README.md +++ b/apis/com.dbeaver.datadam.dam.remote.api/README.md @@ -9,7 +9,7 @@ See [Messaging](MESSAGING.md) for the neutral request/reply and typed RPC contra ## Session identity and handshake -The WebSocket handshake sends `DDRemoteDamHandshakeRequest` with `appDeploymentId`, `appInstanceId`, `workspaceId`, +`DDRemoteDamHandshakeRequest` holds `hello` metadata: `appDeploymentId`, `appInstanceId`, `workspaceId`, `clientDamId`, `product`, and `version`, in that constructor order. All six fields are mandatory. An optional seventh field, `suggestedName`, proposes an initial display name. The six-argument constructor and requests without this field remain supported; null means no suggestion and is omitted from encoded requests. @@ -17,18 +17,31 @@ When supplied, the name uses the same normalization and 256-Unicode-code-point l blank, non-string, and oversized values are rejected. `DDRemoteDamHandshakeResponse` returns the assigned `damSessionId` and `DDRemoteDamSettings`, containing immutable `account` and `dam` string maps. Its required `accountId` is verified by the server. +The optional `authenticationRefresh` flag advertises in-place token renewal. The desktop applies the settings snapshot before registering settings-dependent services and registers `service.desktop.DDRemoteDamSettingsService` (`dbeaver.dam.settings`) for subsequent complete snapshots. A missing settings field from an older broker produces empty maps; MCP remains disabled until explicitly enabled for the DAM. Setting keys are declared in `DDRemoteDamSettingKeys`. Settings reads and writes use Account GraphQL. -Wire control types remain -`hello` and `ready`, and the WebSocket path remains `/ws`. Control messages have `type` and an object `payload`; -application messages additionally have `topic`. Application messages may use any nonblank type, including the control -type names. +The WebSocket path is `/ws`. DBeaver sends `hello` to start a session, `resume` to reconnect to a session, +and `authenticate` to renew the access token on an open connection. The server replies to `hello` or `resume` with +`ready`. Control messages have `type` and an object `payload`; application messages additionally have `topic` and +may use any nonblank type, including the control type names. + +DBeaver includes the permanent `damSecret` in `hello` and reuses it for the same Dam in subsequent `hello` and `resume` +requests. `DDRemoteDamSecret` represents 32 random bytes encoded as canonical unpadded URL-safe Base64. +`encodeHandshakeRequest(metadata, damSecret)` adds the credential to `hello`, and `decodeRegistrationRequest` returns +`DDRemoteDamRegistrationRequest.Hello` for that frame. The original encoder and registration decoder still support the +legacy form without `damSecret`; `decodeHandshakeRequest` returns only metadata regardless of the credential field. +The server requires the credential and binds a new Dam to the authenticated account and user. For an existing Dam, +the server verifies both the owner and the permanent credential. `ready` never includes a secret. + +The server closes a rejected `hello` before `ready` with WebSocket code `4412` (`DAM_REGISTRATION_REJECTED`) when the +Dam credential is missing, a well-formed credential does not match, or the authenticated account or user does not +match the owner. The code does not distinguish these cases. If registration of a new Dam exceeds the account limit, the server closes the connection before `ready` with WebSocket code `4409` (`REGISTRATION_LIMIT_EXCEEDED`) and a displayable reason. Clients should not automatically -retry this rejection. Other close codes retain their existing behavior. +retry this rejection. `DDRemoteDamMessage` takes defensive payload snapshots. @@ -37,16 +50,37 @@ and oversized values are rejected. `clientDamId` is a required nonblank string of at most 2048 characters, using only the URL-safe Base64 alphabet `[A-Za-z0-9_-]+`, without padding. The shared bound is `DDRemoteDamHandshakeRequest.MAX_CLIENT_DAM_ID_LENGTH`. -Missing, null, blank, non-string, oversized, and non-alphabet values are rejected; there is no default or legacy hello -variant. Desktop generates this value as unpadded URL-safe Base64 of the UTF-8 bytes of +Missing, null, blank, non-string, oversized, and non-alphabet values are rejected; there is no fallback identifier. +Desktop generates this value as unpadded URL-safe Base64 of the UTF-8 bytes of `workspaceId + ':' + lowercase hexadecimal MAC address`. Generation belongs to Desktop; the API and server treat the encoded identifier as opaque and do not decode or interpret it. -Stable DAM identity is the authenticated `accountId` together with `clientDamId`. Desktop reconnects and process restarts +Stable Dam identity is the authenticated `accountId` together with `clientDamId`. Desktop reconnects and process restarts preserve that identity while the workspace and MAC address remain the same. `appInstanceId` identifies a process lifetime -and changes when Desktop restarts. `damSessionId` identifies one WebSocket transport session and changes on reconnect. -Reconnects supersede the previous connection for the same account, client DAM identity and application instance. -Different application instances can have independent connections to the same DAM. +and changes when Desktop restarts. `damSessionId` identifies a session, not an individual WebSocket connection. +Each accepted `hello` creates a new session ID and cannot replace an open session. Different application instances +can have independent sessions for the same Dam. + +### Reconnecting to a session + +After `hello`, `ready` contains a new `damSessionId`. After a connection loss, DBeaver opens a new authenticated +WebSocket and sends `resume` (`DDRemoteDamRegistrationRequest.Resume`) with two required payload fields: + +| Field | Meaning | +| --- | --- | +| `damSessionId` | The ID returned in the initial `ready`. | +| `damSecret` | The permanent credential sent in `hello`. | + +Remote Dam verifies the session owner's account and user and the permanent Dam credential before replacing the WebSocket. +Its `ready` response keeps the same `damSessionId`. The credential does not rotate, so a retry uses the same ID and secret. +The settled connection generation is nonsecret server-side state that tracks which connection owns the session. +It is never sent on the wire. A disconnected session can be resumed for five minutes. + +Missing or malformed `resume` fields use close code `1007` (`BAD_DATA`). Owner or credential mismatches in a well-formed +request use `4410` (`RESUME_REJECTED`); DBeaver stops rather than automatically falling back to `hello`. +A temporary server failure (`1011`) allows retrying `resume` with backoff. On `4411` (`RESUME_EXPIRED`), the server +has verified the owner and credential, but the session has expired; DBeaver starts a new session with `hello` using +the same permanent credential. Reconnecting does not replay pending RPC calls. `DDRemoteDamSessionInfo` contains the verified `accountId`, `appDeploymentId`, `appInstanceId`, `damSessionId`, and the handshake settings snapshot. Transport identity includes the account and the three session identifiers; @@ -76,7 +110,7 @@ Names are normalized, limited to 256 Unicode code points, and do not need to be cannot be renamed. A lookup can return null until the DAM appears in the Account snapshot. Registration persistence may apply `suggestedName` only when the stored name is unset or equals the stored -deployment ID. Other saved names are preserved. Persistence is asynchronous and does not gate the `ready` response. +deployment ID. Other saved names are preserved. Initial naming is part of registration and does not send a separate notification or require a follow-up request. Later manual renames still use Account GraphQL. Servers without registration naming support may ignore the suggestion. diff --git a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocol.java b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocol.java index d7187f7..5ea4996 100644 --- a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocol.java +++ b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocol.java @@ -16,8 +16,22 @@ */ package com.dbeaver.datadam.dam.remote.api; -import com.dbeaver.datadam.dam.remote.api.model.*; -import com.google.gson.*; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamAuthenticationRequest; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamHandshakeRequest; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamHandshakeResponse; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamMessage; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamPayload; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamRegistrationRequest; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamSecret; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamSessionRequest; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamSettings; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.JsonParser; +import com.google.gson.ToNumberPolicy; import com.google.gson.reflect.TypeToken; import org.jkiss.code.NotNull; import org.jkiss.code.Nullable; @@ -33,7 +47,11 @@ public final class DDRemoteDamProtocol { public static final String TYPE_HANDSHAKE_REQUEST = "hello"; public static final String TYPE_HANDSHAKE_RESPONSE = "ready"; public static final String TYPE_AUTHENTICATION_REQUEST = "authenticate"; + private static final String TYPE_RECONNECT_REQUEST = "resume"; public static final int REGISTRATION_LIMIT_EXCEEDED = 4409; + public static final int RESUME_REJECTED = 4410; + public static final int RESUME_EXPIRED = 4411; + public static final int DAM_REGISTRATION_REJECTED = 4412; private static final String FIELD_TOPIC = "topic"; private static final String FIELD_TYPE = "type"; @@ -46,6 +64,7 @@ public final class DDRemoteDamProtocol { private static final String FIELD_VERSION = "version"; private static final String FIELD_SUGGESTED_NAME = "suggestedName"; private static final String FIELD_DAM_SESSION_ID = "damSessionId"; + private static final String FIELD_DAM_SECRET = "damSecret"; private static final String FIELD_ACCOUNT_ID = "accountId"; private DDRemoteDamProtocol() { @@ -110,6 +129,18 @@ public static String decodeAuthenticationRequest(@NotNull String message) { @NotNull public static String encodeHandshakeRequest(@NotNull DDRemoteDamHandshakeRequest hello) { + return envelope(TYPE_HANDSHAKE_REQUEST, writeHandshakePayload(hello)).toString(); + } + + @NotNull + public static String encodeHandshakeRequest(@NotNull DDRemoteDamHandshakeRequest hello, @NotNull DDRemoteDamSecret damSecret) { + JsonObject payload = writeHandshakePayload(hello); + payload.addProperty(FIELD_DAM_SECRET, damSecret.value()); + return envelope(TYPE_HANDSHAKE_REQUEST, payload).toString(); + } + + @NotNull + private static JsonObject writeHandshakePayload(@NotNull DDRemoteDamHandshakeRequest hello) { JsonObject payload = new JsonObject(); payload.addProperty(FIELD_APP_DEPLOYMENT_ID, hello.appDeploymentId()); payload.addProperty(FIELD_APP_INSTANCE_ID, hello.appInstanceId()); @@ -120,12 +151,54 @@ public static String encodeHandshakeRequest(@NotNull DDRemoteDamHandshakeRequest if (hello.suggestedName() != null) { payload.addProperty(FIELD_SUGGESTED_NAME, hello.suggestedName()); } - return envelope(TYPE_HANDSHAKE_REQUEST, payload).toString(); + return payload; + } + + @NotNull + public static String encodeReconnectRequest(@NotNull DDRemoteDamRegistrationRequest.Resume request) { + JsonObject payload = new JsonObject(); + payload.addProperty(FIELD_DAM_SESSION_ID, request.damSessionId()); + payload.addProperty(FIELD_DAM_SECRET, request.damSecret().value()); + return envelope(TYPE_RECONNECT_REQUEST, payload).toString(); } @NotNull public static DDRemoteDamHandshakeRequest decodeHandshakeRequest(@NotNull String message) { - JsonObject payload = readControlPayload(message, TYPE_HANDSHAKE_REQUEST); + return readHandshakeRequest(readControlPayload(message, TYPE_HANDSHAKE_REQUEST)); + } + + @NotNull + public static DDRemoteDamRegistrationRequest decodeRegistrationRequest(@NotNull String message) { + JsonObject envelope = parseEnvelope(message); + if (envelope.has(FIELD_TOPIC)) { + throw new IllegalArgumentException("Expected a registration request"); + } + JsonObject payload = readPayload(envelope); + return switch (readString(envelope, FIELD_TYPE)) { + case TYPE_HANDSHAKE_REQUEST -> { + DDRemoteDamHandshakeRequest hello = readHandshakeRequest(payload); + yield payload.has(FIELD_DAM_SECRET) + ? new DDRemoteDamRegistrationRequest.Hello(hello, readDamSecret(payload)) + : hello; + } + case TYPE_RECONNECT_REQUEST -> new DDRemoteDamRegistrationRequest.Resume( + readString(payload, FIELD_DAM_SESSION_ID), + readDamSecret(payload) + ); + default -> throw new IllegalArgumentException("Expected a registration request"); + }; + } + + @NotNull + private static DDRemoteDamSecret readDamSecret(@NotNull JsonObject payload) { + return new DDRemoteDamSecret(readString(payload, FIELD_DAM_SECRET)); + } + + @NotNull + private static DDRemoteDamHandshakeRequest readHandshakeRequest(@NotNull JsonObject payload) { + if (payload.has(FIELD_DAM_SESSION_ID)) { + throw new IllegalArgumentException("Dam session ID requires a resume request"); + } return new DDRemoteDamHandshakeRequest( readString(payload, FIELD_APP_DEPLOYMENT_ID), readString(payload, FIELD_APP_INSTANCE_ID), diff --git a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeRequest.java b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeRequest.java index e3be22f..f13bf67 100644 --- a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeRequest.java +++ b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeRequest.java @@ -27,7 +27,7 @@ public record DDRemoteDamHandshakeRequest( @NotNull String product, @NotNull String version, @Nullable String suggestedName -) { +) implements DDRemoteDamRegistrationRequest { public static final int MAX_WORKSPACE_ID_LENGTH = 256; public static final int MAX_CLIENT_DAM_ID_LENGTH = 2048; diff --git a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeResponse.java b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeResponse.java index 10f7bc5..c955dec 100644 --- a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeResponse.java +++ b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamHandshakeResponse.java @@ -31,5 +31,8 @@ public record DDRemoteDamHandshakeResponse( Objects.requireNonNull(settings); Objects.requireNonNull(accountId); DDRemoteDamMessage.requireText(damSessionId, "damSessionId"); + if (damSessionId.length() > DDRemoteDamRegistrationRequest.Resume.MAX_SESSION_ID_LENGTH) { + throw new IllegalArgumentException("Dam session ID is too long"); + } } } diff --git a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamRegistrationRequest.java b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamRegistrationRequest.java new file mode 100644 index 0000000..fd4e7dc --- /dev/null +++ b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamRegistrationRequest.java @@ -0,0 +1,50 @@ +/* + * DBeaver - Universal Database Manager + * Copyright (C) 2010-2026 DBeaver Corp + * + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of DBeaver Corp and its suppliers, if any. + * The intellectual and technical concepts contained + * herein are proprietary to DBeaver Corp and its suppliers + * and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from DBeaver Corp. + */ +package com.dbeaver.datadam.dam.remote.api.model; + +import org.jkiss.code.NotNull; + +import java.util.Objects; + +public sealed interface DDRemoteDamRegistrationRequest + permits DDRemoteDamHandshakeRequest, DDRemoteDamRegistrationRequest.Hello, DDRemoteDamRegistrationRequest.Resume { + + record Hello( + @NotNull DDRemoteDamHandshakeRequest request, + @NotNull DDRemoteDamSecret damSecret + ) implements DDRemoteDamRegistrationRequest { + public Hello { + Objects.requireNonNull(request); + Objects.requireNonNull(damSecret); + } + } + + record Resume( + @NotNull String damSessionId, + @NotNull DDRemoteDamSecret damSecret + ) implements DDRemoteDamRegistrationRequest { + static final int MAX_SESSION_ID_LENGTH = 256; + + public Resume { + Objects.requireNonNull(damSecret); + DDRemoteDamMessage.requireText(damSessionId, "damSessionId"); + if (damSessionId.length() > MAX_SESSION_ID_LENGTH) { + throw new IllegalArgumentException("Dam session ID is too long"); + } + } + } +} diff --git a/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamSecret.java b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamSecret.java new file mode 100644 index 0000000..f85a2c9 --- /dev/null +++ b/apis/com.dbeaver.datadam.dam.remote.api/src/main/java/com/dbeaver/datadam/dam/remote/api/model/DDRemoteDamSecret.java @@ -0,0 +1,45 @@ +/* + * DBeaver - Universal Database Manager + * Copyright (C) 2010-2026 DBeaver Corp + * + * All Rights Reserved. + * + * NOTICE: All information contained herein is, and remains + * the property of DBeaver Corp and its suppliers, if any. + * The intellectual and technical concepts contained + * herein are proprietary to DBeaver Corp and its suppliers + * and may be covered by U.S. and Foreign Patents, + * patents in process, and are protected by trade secret or copyright law. + * Dissemination of this information or reproduction of this material + * is strictly forbidden unless prior written permission is obtained + * from DBeaver Corp. + */ +package com.dbeaver.datadam.dam.remote.api.model; + +import org.jkiss.code.NotNull; +import org.jkiss.code.Nullable; + +import java.util.Base64; +import java.util.regex.Pattern; + +public record DDRemoteDamSecret(@NotNull String value) { + private static final Pattern ENCODED = Pattern.compile("[A-Za-z0-9_-]{43}"); + private static final Base64.Encoder ENCODER = Base64.getUrlEncoder().withoutPadding(); + + public DDRemoteDamSecret { + if (!isCanonicalEncoding(value)) { + throw new IllegalArgumentException("Invalid Dam secret"); + } + } + + private static boolean isCanonicalEncoding(@Nullable String value) { + return value != null && ENCODED.matcher(value).matches() + && ENCODER.encodeToString(Base64.getUrlDecoder().decode(value)).equals(value); + } + + @Override + @NotNull + public String toString() { + return "DDRemoteDamSecret[]"; + } +} diff --git a/apis/com.dbeaver.datadam.dam.remote.api/src/test/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocolTest.java b/apis/com.dbeaver.datadam.dam.remote.api/src/test/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocolTest.java index 59ba414..01e8c09 100644 --- a/apis/com.dbeaver.datadam.dam.remote.api/src/test/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocolTest.java +++ b/apis/com.dbeaver.datadam.dam.remote.api/src/test/java/com/dbeaver/datadam/dam/remote/api/DDRemoteDamProtocolTest.java @@ -19,7 +19,13 @@ import com.dbeaver.datadam.api.base.DDExceptionRemote; import com.dbeaver.datadam.api.base.DDRemoteService; import com.dbeaver.datadam.dam.remote.api.exception.DDRemoteDamException; -import com.dbeaver.datadam.dam.remote.api.model.*; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamAuthenticationRequest; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamHandshakeRequest; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamHandshakeResponse; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamMessage; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamRegistrationRequest; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamSecret; +import com.dbeaver.datadam.dam.remote.api.model.DDRemoteDamSettings; import com.dbeaver.datadam.dam.remote.api.service.desktop.DDRemoteDamSettingsService; import com.dbeaver.datadam.dam.remote.api.service.desktop.DDSharedProjectEventsService; import com.dbeaver.datadam.dam.remote.api.service.web.DDGatewayKeyService; @@ -30,6 +36,7 @@ import java.math.BigDecimal; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.UUID; import static org.junit.jupiter.api.Assertions.*; @@ -156,6 +163,68 @@ void roundTripsHandshakeRequestWithoutAccountCredentialsOrProtocolVersion() { assertFalse(encoded.contains("protocolVersion")); } + @Test + void carriesThePermanentDamSecretOnlyOnRegistrationRequests() { + var metadata = new DDRemoteDamHandshakeRequest("deployment", "run", "workspace", "desktop", "DBeaver", "1", "Work Dam"); + var damSecret = new DDRemoteDamSecret("C" + "A".repeat(42)); + var hello = new DDRemoteDamRegistrationRequest.Hello(metadata, damSecret); + var ready = new DDRemoteDamHandshakeResponse("session-1", DDRemoteDamSettings.EMPTY, true, ACCOUNT_ID); + var resume = new DDRemoteDamRegistrationRequest.Resume(ready.damSessionId(), damSecret); + String encodedHello = DDRemoteDamProtocol.encodeHandshakeRequest(metadata, damSecret); + String encodedResume = DDRemoteDamProtocol.encodeReconnectRequest(resume); + String encodedReady = DDRemoteDamProtocol.encodeHandshakeResponse(ready); + + var helloPayload = JsonParser.parseString(encodedHello).getAsJsonObject().getAsJsonObject("payload"); + assertEquals(damSecret.value(), helloPayload.get("damSecret").getAsString()); + assertEquals(JsonParser.parseString(""" + {"type":"resume","payload":{"damSessionId":"session-1","damSecret":"%s"}} + """.formatted(damSecret.value())), JsonParser.parseString(encodedResume)); + var readyPayload = JsonParser.parseString(encodedReady).getAsJsonObject().getAsJsonObject("payload"); + assertEquals(Set.of("damSessionId", "settings", "authenticationRefresh", "accountId"), readyPayload.keySet()); + assertEquals(metadata, DDRemoteDamProtocol.decodeRegistrationRequest(DDRemoteDamProtocol.encodeHandshakeRequest(metadata))); + assertEquals(hello, DDRemoteDamProtocol.decodeRegistrationRequest(encodedHello)); + assertEquals(resume, DDRemoteDamProtocol.decodeRegistrationRequest(encodedResume)); + assertEquals(ready, DDRemoteDamProtocol.decodeHandshakeResponse(encodedReady)); + assertEquals(metadata, DDRemoteDamProtocol.decodeHandshakeRequest(encodedHello)); + assertThrows(IllegalArgumentException.class, () -> DDRemoteDamProtocol.decodeHandshakeRequest(encodedResume)); + assertFalse(damSecret.toString().contains(damSecret.value())); + assertFalse(hello.toString().contains(damSecret.value())); + assertFalse(resume.toString().contains(damSecret.value())); + } + + @Test + void rejectsMalformedDamSecretsWhenDecodingRegistrationRequests() { + var metadata = new DDRemoteDamHandshakeRequest("deployment", "run", "workspace", "desktop", "DBeaver", "1"); + var resume = new DDRemoteDamRegistrationRequest.Resume("session-1", new DDRemoteDamSecret("A".repeat(43))); + var helloFrame = JsonParser.parseString(DDRemoteDamProtocol.encodeHandshakeRequest(metadata)).getAsJsonObject(); + var resumeFrame = JsonParser.parseString(DDRemoteDamProtocol.encodeReconnectRequest(resume)).getAsJsonObject(); + + for (String value : List.of("null", "42", "\" \"", "\"too-short\"", + "\"" + "A".repeat(43) + "=\"", "\"" + "!".repeat(43) + "\"", "\"" + "A".repeat(42) + "B\"")) { + for (JsonObject frame : List.of(helloFrame, resumeFrame)) { + frame.getAsJsonObject("payload").add("damSecret", JsonParser.parseString(value)); + assertThrows(IllegalArgumentException.class, () -> DDRemoteDamProtocol.decodeRegistrationRequest(frame.toString())); + } + assertEquals(metadata, DDRemoteDamProtocol.decodeHandshakeRequest(helloFrame.toString())); + } + } + + @Test + void rejectsIncompleteResumeRequestsAndInvalidSessionIds() { + var resume = new DDRemoteDamRegistrationRequest.Resume("session-1", new DDRemoteDamSecret("A".repeat(43))); + var frame = JsonParser.parseString(DDRemoteDamProtocol.encodeReconnectRequest(resume)).getAsJsonObject(); + for (String field : List.of("damSessionId", "damSecret")) { + JsonObject missing = frame.deepCopy(); + missing.getAsJsonObject("payload").remove(field); + assertThrows(IllegalArgumentException.class, () -> DDRemoteDamProtocol.decodeRegistrationRequest(missing.toString())); + } + for (String value : List.of("null", "42", "\" \"", "\"" + "s".repeat(257) + "\"")) { + frame.getAsJsonObject("payload").add("damSessionId", JsonParser.parseString(value)); + assertThrows(IllegalArgumentException.class, () -> DDRemoteDamProtocol.decodeRegistrationRequest(frame.toString())); + } + assertThrows(NullPointerException.class, () -> new DDRemoteDamRegistrationRequest.Resume("session-1", null)); + } + @Test void acceptsWorkspaceIdLengthBoundariesAndRejectsNullBlankAndOversizedIds() { for (String workspaceId : List.of("w", "w".repeat(256))) { @@ -368,11 +437,14 @@ void rejectsMissingAndMalformedHandshakeRequestFields() { } @Test - void rejectsHandshakeResponseWithoutAStringSessionId() { - for (String payload : List.of("{}", "{\"damSessionId\":null}", "{\"damSessionId\":42}", "{\"damSessionId\":\" \"}")) { - String message = "{\"type\":\"ready\",\"payload\":" + payload + "}"; + void rejectsHandshakeResponseWithoutAValidSessionId() { + for (String sessionId : List.of("null", "42", "\" \"", "\"" + "x".repeat(257) + "\"")) { + String message = "{\"type\":\"ready\",\"payload\":{\"accountId\":\"" + ACCOUNT_ID + + "\",\"damSessionId\":" + sessionId + "}}"; assertThrows(IllegalArgumentException.class, () -> DDRemoteDamProtocol.decodeHandshakeResponse(message)); } + assertThrows(IllegalArgumentException.class, () -> DDRemoteDamProtocol.decodeHandshakeResponse( + "{\"type\":\"ready\",\"payload\":{\"accountId\":\"" + ACCOUNT_ID + "\"}}")); } }