Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk-java): harden trust-boundary handling in the client

Yudhi Armyndhariscffbe67334d0
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java b/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java
index e7ab5525b..4b0a2ae28 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/ClientConfig.java
@@ -1,6 +1,8 @@
package com.rmyndharis.openwa;
import com.rmyndharis.openwa.http.HttpTransport;
+import java.net.URI;
+import java.net.URISyntaxException;
import java.time.Duration;
import java.util.Map;
@@ -13,13 +15,44 @@ public final class ClientConfig {
final HttpTransport transport; // nullable → OpenWAClient supplies DefaultHttpTransport
private ClientConfig(Builder b) {
- this.baseUrl = b.baseUrl;
- this.apiKey = b.apiKey;
+ String url = b.baseUrl == null ? null : b.baseUrl.strip();
+ if (url == null || url.isEmpty()) {
+ throw new IllegalArgumentException("OpenWAClient: baseUrl is required");
+ }
+ try {
+ new URI(url);
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("OpenWAClient: baseUrl is not a valid URL: " + url);
+ }
+ String key = b.apiKey == null ? null : b.apiKey.strip();
+ if (key == null || key.isEmpty()) {
+ throw new IllegalArgumentException("OpenWAClient: apiKey is required");
+ }
+ if (hasControlChar(key)) {
+ throw new IllegalArgumentException(
+ "OpenWAClient: apiKey contains illegal characters (whitespace or control) — check for a stray newline");
+ }
+ if (b.timeout != null && (b.timeout.isZero() || b.timeout.isNegative())) {
+ throw new IllegalArgumentException("OpenWAClient: timeout must be positive");
+ }
+ // baseUrl/apiKey are stripped so a trailing newline from a file/env var can't break the request.
+ this.baseUrl = url;
+ this.apiKey = key;
this.timeout = b.timeout != null ? b.timeout : Duration.ofSeconds(30);
this.defaultHeaders = b.defaultHeaders != null ? b.defaultHeaders : Map.of();
this.transport = b.transport;
}
+ private static boolean hasControlChar(String s) {
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (c < 0x20 || c == 0x7f) {
+ return true;
+ }
+ }
+ return false;
+ }
+
public static Builder builder() {
return new Builder();
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
index 6d0331aec..52018c220 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
@@ -58,12 +58,7 @@ public final class OpenWAClient {
public final HealthResource health = new HealthResource(this);
public OpenWAClient(ClientConfig config) {
- if (config.baseUrl == null || config.baseUrl.isBlank()) {
- throw new IllegalArgumentException("OpenWAClient: baseUrl is required");
- }
- if (config.apiKey == null || config.apiKey.isBlank()) {
- throw new IllegalArgumentException("OpenWAClient: apiKey is required");
- }
+ // ClientConfig's constructor validates baseUrl/apiKey/timeout, so config is already sound here.
this.config = config;
this.transport = config.transport != null ? config.transport : new DefaultHttpTransport();
}
@@ -119,6 +114,10 @@ public final class OpenWAClient {
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new OpenWAError("Transport interrupted — " + method + " " + path);
+ } catch (IllegalArgumentException e) {
+ // e.g. a JDK-restricted header name in defaultHeaders, or a URI-illegal char — keep it
+ // inside the OpenWAError contract instead of leaking a raw JDK exception to the caller.
+ throw new OpenWAError("Invalid request — " + method + " " + path + ": " + e.getMessage());
}
if (res.status() < 200 || res.status() >= 300) {
throw OpenWAApiError.fromResponse(res.status(), "", res.body(), method + " " + path);
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java
index f23013b1f..d66f00987 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/errors/OpenWAApiError.java
@@ -55,25 +55,32 @@ public class OpenWAApiError extends OpenWAError {
"Unexpected redirect (not followed; the API key is never re-sent to a redirect target) — " + context,
status, null, null);
}
- JsonObject env = null;
+ JsonObject obj = null;
Object parsedBody = rawBody;
if (rawBody != null && !rawBody.isEmpty()) {
try {
JsonElement el = GSON.fromJson(rawBody, JsonElement.class);
if (el != null && el.isJsonObject()) {
- JsonObject o = el.getAsJsonObject();
- parsedBody = o;
- if (o.has("statusCode") && o.has("message") && o.has("error")) {
- env = o;
- }
+ obj = el.getAsJsonObject();
+ parsedBody = obj;
}
} catch (RuntimeException ignore) {
// leave parsedBody as the raw text
}
}
- String errorKind = env != null && env.has("error") ? env.get("error").getAsString() : null;
- String messageText = describe(env != null ? env.get("message") : null, statusText);
- String message = "OpenWA API " + status + " " + statusText + " — " + context + ": " + messageText;
+ // Pull `message`/`error` from any JSON object body, not only a full NestJS envelope, so a partial
+ // body (e.g. a 500 with {statusCode, message} but no `error`) still yields a useful message.
+ String errorKind = obj != null && obj.has("error") && obj.get("error").isJsonPrimitive()
+ ? obj.get("error").getAsString()
+ : null;
+ JsonElement messageEl = obj != null && obj.has("message") ? obj.get("message") : null;
+ String fallback = rawBody != null && !rawBody.isBlank() ? rawBody : (statusText == null ? "" : statusText);
+ String messageText = describe(messageEl, fallback);
+ // java.net.http exposes no HTTP reason phrase, so statusText is often blank — omit it rather than
+ // emitting a double space, and omit the trailing ": " when there is no message text at all.
+ String reason = statusText == null || statusText.isBlank() ? "" : " " + statusText;
+ String tail = messageText.isEmpty() ? "" : ": " + messageText;
+ String message = "OpenWA API " + status + reason + " — " + context + tail;
return classify(status, message, parsedBody, errorKind);
}
@@ -83,10 +90,12 @@ public class OpenWAApiError extends OpenWAError {
}
if (message.isJsonArray()) {
return StreamSupport.stream(message.getAsJsonArray().spliterator(), false)
- .map(JsonElement::getAsString)
+ .map(el -> el.isJsonPrimitive() ? el.getAsString() : el.toString())
.collect(Collectors.joining(", "));
}
- return message.getAsString();
+ // Guard against a non-primitive `message` (e.g. a nested object in a non-NestJS body): getAsString()
+ // would throw, and throwing while constructing an error is worse than a slightly-verbose message.
+ return message.isJsonPrimitive() ? message.getAsString() : message.toString();
}
/** Construct the most specific subclass for a status code. */
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/ConfigTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/ConfigTest.java
new file mode 100644
index 000000000..f9e4ad178
--- /dev/null
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/ConfigTest.java
@@ -0,0 +1,59 @@
+package com.rmyndharis.openwa;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.rmyndharis.openwa.errors.OpenWAError;
+import com.rmyndharis.openwa.http.HttpMethod;
+import com.rmyndharis.openwa.http.HttpTransport;
+import com.rmyndharis.openwa.model.SuccessResult;
+import com.rmyndharis.openwa.support.MockTransport;
+import java.time.Duration;
+import org.junit.jupiter.api.Test;
+
+class ConfigTest {
+ private static ClientConfig.Builder base() {
+ return ClientConfig.builder().baseUrl("http://h").apiKey("owa_k1_x");
+ }
+
+ @Test
+ void rejectsZeroAndNegativeTimeout() {
+ assertThrows(IllegalArgumentException.class, () -> base().timeout(Duration.ZERO).build());
+ assertThrows(IllegalArgumentException.class, () -> base().timeout(Duration.ofSeconds(-1)).build());
+ }
+
+ @Test
+ void rejectsMalformedBaseUrl() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ClientConfig.builder().baseUrl("http://my host:2785").apiKey("owa_k1_x").build());
+ }
+
+ @Test
+ void rejectsApiKeyWithInteriorControlChar() {
+ assertThrows(IllegalArgumentException.class,
+ () -> ClientConfig.builder().baseUrl("http://h").apiKey("owa\nk1").build());
+ }
+
+ @Test
+ void trimsWhitespaceFromBaseUrlAndApiKey() {
+ // A trailing newline (e.g. key read from a file/env) must be tolerated, not fatal.
+ MockTransport tx = new MockTransport().respond(200, "{\"valid\":true}");
+ OpenWAClient c = new OpenWAClient(
+ ClientConfig.builder().baseUrl("http://h ").apiKey(" owa_k1_x\n").transport(tx).build());
+ c.auth();
+ assertEquals("owa_k1_x", tx.lastRequest().headers().get("X-API-Key"));
+ assertTrue(tx.lastRequest().url().startsWith("http://h/"));
+ }
+
+ @Test
+ void transportIllegalArgumentIsWrappedAsOpenWAError() {
+ HttpTransport bad = req -> {
+ throw new IllegalArgumentException("restricted header name: \"Host\"");
+ };
+ OpenWAClient c = new OpenWAClient(base().transport(bad).build());
+ OpenWAError e = assertThrows(OpenWAError.class,
+ () -> c.request(HttpMethod.GET, "/x", null, null, SuccessResult.class));
+ assertTrue(e.getMessage().contains("Invalid request"));
+ }
+}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.java
index 56451591b..bcc97cabe 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/errors/ErrorsTest.java
@@ -44,4 +44,29 @@ class ErrorsTest {
assertTrue(t.getMessage().contains("30000"));
assertTrue(t instanceof OpenWAError);
}
+
+ @Test
+ void blankStatusTextProducesNoDoubleSpace() {
+ // The default transport exposes no HTTP reason phrase, so the client passes "" as statusText.
+ String body = "{\"statusCode\":404,\"message\":\"Session x not found\",\"error\":\"Not Found\"}";
+ OpenWAApiError e = OpenWAApiError.fromResponse(404, "", body, "GET /api/sessions/x");
+ assertTrue(e.getMessage().contains("Session x not found"));
+ assertFalse(e.getMessage().contains("404 "), "must not emit a double space when statusText is blank");
+ assertTrue(e.getMessage().startsWith("OpenWA API 404 — GET /api/sessions/x"));
+ }
+
+ @Test
+ void partialEnvelopeWithoutErrorFieldStillKeepsMessage() {
+ // NestJS default 500 carries {statusCode, message} but no `error` field — the message must survive.
+ String body = "{\"statusCode\":500,\"message\":\"Internal server error\"}";
+ OpenWAApiError e = OpenWAApiError.fromResponse(500, "", body, "GET /api/x");
+ assertEquals(OpenWAApiError.class, e.getClass());
+ assertTrue(e.getMessage().contains("Internal server error"), "message text must not be dropped");
+ }
+
+ @Test
+ void bodylessErrorHasCleanMessage() {
+ OpenWAApiError e = OpenWAApiError.fromResponse(502, "", "", "GET /api/x");
+ assertEquals("OpenWA API 502 — GET /api/x", e.getMessage());
+ }
}