Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(sdk): refuse empty and dot path ids in the Go and Java SDKs

Yudhi Armyndharis4e04010e0615
diff --git a/sdk/go/README.md b/sdk/go/README.md
index 9a2afd094..7440440a5 100644
--- a/sdk/go/README.md
+++ b/sdk/go/README.md
@@ -182,6 +182,10 @@ err := client.Do(ctx, "GET", "/api/some/new/path", nil, nil, &out)
than re-sending the API key to the redirect target.
- Path segments (chat/message ids) are percent-encoded; a base-URL path prefix
(e.g. behind a proxy at `/v1`) is preserved.
+- **Empty and dot ids are refused.** An empty, `.` or `..` id returns an error
+ and nothing is sent, so a proxy that resolves dot segments cannot turn the
+ call into one on the parent resource. `Client.Do` refuses a `.` or `..`
+ segment the same way but sends an empty one (a trailing slash) as written.
## Development
diff --git a/sdk/go/client.go b/sdk/go/client.go
index d41d8feac..6cb7284bc 100644
--- a/sdk/go/client.go
+++ b/sdk/go/client.go
@@ -197,12 +197,19 @@ func warnIfInsecure(cfg *config) {
// body falls back to the raw text when out is a *string — mirroring the
// JS/Python/PHP transports, which return the raw text instead of failing.
// Any other out type still requires a JSON body.
+//
+// A "." or ".." segment (also written %2e) returns an error and nothing is
+// sent; empty segments, such as a trailing slash, are sent as written.
func (c *Client) Do(ctx context.Context, method, path string, query url.Values, body, out any) error {
- return c.do(ctx, method, path, query, body, out)
+ return c.call(ctx, method, path, query, body, out, true)
}
func (c *Client) do(ctx context.Context, method, path string, query url.Values, body, out any) error {
- data, _, err := c.doRaw(ctx, method, path, query, body)
+ return c.call(ctx, method, path, query, body, out, false)
+}
+
+func (c *Client) call(ctx context.Context, method, path string, query url.Values, body, out any, rawPath bool) error {
+ data, _, err := c.doRaw(ctx, method, path, query, body, rawPath)
if err != nil {
return err
}
@@ -228,7 +235,15 @@ func (c *Client) do(ctx context.Context, method, path string, query url.Values,
// doRaw performs the request and returns the response body and Content-Type.
// Any non-2xx status (including an unfollowed 3xx) is an error.
-func (c *Client) doRaw(ctx context.Context, method, path string, query url.Values, body any) ([]byte, string, error) {
+//
+// A path segment that is "." or ".." is refused before sending: a proxy that
+// resolves dot segments would route the request to the parent resource. A
+// typed service path (rawPath false) also refuses an empty segment, which
+// means a required id was blank; a hand-written Do path may keep one.
+func (c *Client) doRaw(ctx context.Context, method, path string, query url.Values, body any, rawPath bool) ([]byte, string, error) {
+ if err := checkPathSegments(path, rawPath); err != nil {
+ return nil, "", err
+ }
var bodyBytes []byte
var reader io.Reader
if body != nil {
@@ -292,7 +307,8 @@ func isTimeout(err error) bool {
// pathEscape percent-encodes a single path segment so a value containing "/",
// "#", or "?" can't break out of its path position. WhatsApp-JID characters
-// that are already path-safe ("@", ":", "+") are kept readable.
+// that are already path-safe ("@", ":", "+") are kept readable. An empty, "."
+// or ".." id is left as is and refused by doRaw before anything is sent.
func pathEscape(segment string) string {
escaped := url.PathEscape(segment)
return jidRestorer.Replace(escaped)
@@ -300,6 +316,28 @@ func pathEscape(segment string) string {
var jidRestorer = strings.NewReplacer("%40", "@", "%3A", ":", "%2B", "+")
+var dotFolder = strings.NewReplacer("%2e", ".", "%2E", ".")
+
+// checkPathSegments refuses a "." or ".." segment (also written %2e), and an
+// empty one unless allowEmpty. The query and fragment are not path segments.
+func checkPathSegments(path string, allowEmpty bool) error {
+ p := path
+ if i := strings.IndexAny(p, "?#"); i >= 0 {
+ p = p[:i]
+ }
+ for _, seg := range strings.Split(p, "/")[1:] {
+ switch dotFolder.Replace(seg) {
+ case ".", "..":
+ return fmt.Errorf("openwa: dot path segment in %q", path)
+ case "":
+ if !allowEmpty {
+ return fmt.Errorf("openwa: empty path segment in %q", path)
+ }
+ }
+ }
+ return nil
+}
+
// query helpers used by the typed *Query structs.
func setStr(v url.Values, key string, p *string) {
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index 8da716f06..51fab3efd 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -111,6 +111,54 @@ func TestJIDPathIsReadable(t *testing.T) {
}
}
+func TestEmptyAndDotSegmentsRefused(t *testing.T) {
+ var hits int32
+ rt := RoundTripperFunc(func(req *http.Request) (*http.Response, error) {
+ atomic.AddInt32(&hits, 1)
+ return &http.Response{StatusCode: 204, Body: io.NopCloser(strings.NewReader("")), Header: http.Header{}, Request: req}, nil
+ })
+ c := newTestClient(t, rt)
+ ctx := context.Background()
+
+ refused := map[string]error{
+ `Webhooks.Delete ".."`: c.Webhooks.Delete(ctx, "s1", ".."),
+ `Webhooks.Delete "."`: c.Webhooks.Delete(ctx, "s1", "."),
+ `Webhooks.Delete ""`: c.Webhooks.Delete(ctx, "s1", ""),
+ `Do %2E%2e`: c.Do(ctx, "DELETE", "/api/sessions/s1/labels/%2E%2e", nil, nil, nil),
+ `Do ..`: c.Do(ctx, "GET", "/api/sessions/s1/..?x=1", nil, nil, nil),
+ }
+ _, err := c.Sessions.Get(ctx, "")
+ refused[`Sessions.Get ""`] = err
+ _, err = c.Messages.Media(ctx, "s1", "..", "m1")
+ refused[`Messages.Media ".."`] = err
+ _, err = c.Status.Media(ctx, "s1", ".")
+ refused[`Status.Media "."`] = err
+ for name, err := range refused {
+ if err == nil || !strings.Contains(err.Error(), "path segment") {
+ t.Errorf("%s: err = %v, want a path segment error", name, err)
+ }
+ }
+ if n := atomic.LoadInt32(&hits); n != 0 {
+ t.Fatalf("%d requests sent, want 0", n)
+ }
+
+ // Dots inside an id, a dot-only query value, and a hand-written trailing or
+ // double slash are not refused.
+ for _, id := range []string{"a.b", "...", "[email protected]"} {
+ if err := c.Webhooks.Delete(ctx, "s1", id); err != nil {
+ t.Errorf("Webhooks.Delete %q: %v", id, err)
+ }
+ }
+ for _, path := range []string{"/api/sessions/", "/api/sessions//x", "/", "/api/labels/a.b?x=/.."} {
+ if err := c.Do(ctx, "GET", path, nil, nil, nil); err != nil {
+ t.Errorf("Do %q: %v", path, err)
+ }
+ }
+ if n := atomic.LoadInt32(&hits); n != 7 {
+ t.Fatalf("%d requests sent, want 7", n)
+ }
+}
+
func TestListSessionsQueryName(t *testing.T) {
rt := &recordTransport{status: 200, body: `[]`}
c := newTestClient(t, rt)
diff --git a/sdk/go/messages.go b/sdk/go/messages.go
index 739d14cd9..3751555fd 100644
--- a/sdk/go/messages.go
+++ b/sdk/go/messages.go
@@ -184,7 +184,7 @@ func (s *MessagesService) Unpin(ctx context.Context, sessionID string, body Unpi
// size-only marker, or a URL-based send whose bytes were never stored).
func (s *MessagesService) Media(ctx context.Context, sessionID, chatID, messageID string) (*MessageMedia, error) {
path := s.base(sessionID) + "/" + pathEscape(chatID) + "/" + pathEscape(messageID) + "/media"
- data, contentType, err := s.client.doRaw(ctx, "GET", path, nil, nil)
+ data, contentType, err := s.client.doRaw(ctx, "GET", path, nil, nil, false)
if err != nil {
return nil, err
}
diff --git a/sdk/go/status.go b/sdk/go/status.go
index 2bf5c45e5..e4c835835 100644
--- a/sdk/go/status.go
+++ b/sdk/go/status.go
@@ -30,7 +30,7 @@ func (s *StatusService) FromContact(ctx context.Context, sessionID, contactID st
// Media fetches the stored media bytes for a status update. The server
// answers 404 when no media is stored (text status, omitted, or expired).
func (s *StatusService) Media(ctx context.Context, sessionID, statusID string) (*StatusMedia, error) {
- data, contentType, err := s.client.doRaw(ctx, "GET", s.base(sessionID)+"/"+pathEscape(statusID)+"/media", nil, nil)
+ data, contentType, err := s.client.doRaw(ctx, "GET", s.base(sessionID)+"/"+pathEscape(statusID)+"/media", nil, nil, false)
if err != nil {
return nil, err
}
diff --git a/sdk/java/README.md b/sdk/java/README.md
index 08bceeb60..9bceffe51 100644
--- a/sdk/java/README.md
+++ b/sdk/java/README.md
@@ -128,6 +128,11 @@ All extend `OpenWAError` (a `RuntimeException`). 503 is transient, but a catalog
- **Default per-request timeout** is 30 s (configurable). Path segments (chat /
message ids) are percent-encoded; a base-URL path prefix (e.g. behind a proxy
at `/v1`) is preserved.
+- **Empty and dot ids are refused.** An empty, `.` or `..` id throws
+ `IllegalArgumentException` and nothing is sent, so a proxy that resolves dot
+ segments cannot turn the call into one on the parent resource. The raw
+ `request*` methods refuse a `.` or `..` segment the same way but send an
+ empty one (a trailing slash) as written.
## Development
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/http/Http.java b/sdk/java/src/main/java/com/rmyndharis/openwa/http/Http.java
index 129adc616..23c720302 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/http/Http.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/http/Http.java
@@ -12,16 +12,37 @@ import java.util.StringJoiner;
public final class Http {
private Http() {}
- /** Percent-encode a path segment, keeping WhatsApp-id chars {@code @ : +} readable. */
+ /**
+ * Percent-encode a path segment, keeping WhatsApp-id chars {@code @ : +} readable.
+ *
+ * @throws IllegalArgumentException for an empty, {@code .} or {@code ..} segment: a proxy that
+ * resolves dot segments would send the request to the parent resource, and an empty one
+ * means a required id was blank.
+ */
public static String encodeSegment(String segment) {
+ if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) {
+ throw new IllegalArgumentException("OpenWA: empty or dot path segment \"" + segment + "\"");
+ }
// URLEncoder is form-encoding: it encodes space as '+'. Restore true
// percent-encoding first, then keep already-path-safe WhatsApp-id chars readable.
String enc = URLEncoder.encode(segment, StandardCharsets.UTF_8).replace("+", "%20");
return enc.replace("%40", "@").replace("%3A", ":").replace("%2B", "+");
}
- /** Build an absolute URL, preserving a base path prefix and omitting null query values. */
+ /**
+ * Build an absolute URL, preserving a base path prefix and omitting null query values.
+ *
+ * @throws IllegalArgumentException if the path has a {@code .} or {@code ..} segment (also
+ * written {@code %2e}); empty segments, such as a trailing slash, are kept as written.
+ */
public static String buildUrl(String baseUrl, String path, Object query, Gson gson) {
+ String pathOnly = path.split("[?#]", 2)[0];
+ for (String segment : pathOnly.split("/", -1)) {
+ String dots = segment.replaceAll("(?i)%2e", ".");
+ if (dots.equals(".") || dots.equals("..")) {
+ throw new IllegalArgumentException("OpenWA: dot path segment in \"" + path + "\"");
+ }
+ }
String base = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
String url = base + path;
if (query == null) {
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
index b27afa282..4a6e89821 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/ClientTest.java
@@ -30,6 +30,15 @@ class ClientTest {
() -> new OpenWAClient(ClientConfig.builder().baseUrl("http://h").build()));
}
+ @Test
+ void emptyOrDotIdIsRefusedBeforeSending() {
+ assertThrows(IllegalArgumentException.class, () -> client.webhooks.delete("s1", ".."));
+ assertThrows(IllegalArgumentException.class, () -> client.webhooks.delete("s1", ""));
+ assertThrows(IllegalArgumentException.class,
+ () -> client.requestVoid(HttpMethod.DELETE, "/api/sessions/s1/labels/%2e%2E", null, null));
+ assertNull(tx.lastRequest());
+ }
+
@Test
void requestSendsAuthHeaderAndParsesBody() {
tx.respond(200, "{\"success\":true}");
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/http/HttpTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/http/HttpTest.java
index ac489a391..eb0860c6d 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/http/HttpTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/http/HttpTest.java
@@ -2,6 +2,7 @@ package com.rmyndharis.openwa.http;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.gson.Gson;
@@ -21,6 +22,26 @@ class HttpTest {
assertEquals("1:2+3", Http.encodeSegment("1:2+3"));
}
+ @Test
+ void encodeSegmentRefusesEmptyAndDotSegments() {
+ for (String id : new String[] {"", ".", ".."}) {
+ assertThrows(IllegalArgumentException.class, () -> Http.encodeSegment(id), id);
+ }
+ // Dots inside an id are not a dot segment.
+ assertEquals("a.b", Http.encodeSegment("a.b"));
+ assertEquals("...", Http.encodeSegment("..."));
+ }
+
+ @Test
+ void buildUrlRefusesDotSegmentsButKeepsEmptyOnes() {
+ for (String path : new String[] {"/api/sessions/s1/..", "/api/./x", "/api/sessions/s1/labels/%2E%2e"}) {
+ assertThrows(IllegalArgumentException.class, () -> Http.buildUrl("http://h", path, null, gson), path);
+ }
+ assertEquals("http://h/api/sessions/", Http.buildUrl("http://h", "/api/sessions/", null, gson));
+ assertEquals("http://h/a//b", Http.buildUrl("http://h", "/a//b", null, gson));
+ assertEquals("http://h/api/labels/a.b?x=/..", Http.buildUrl("http://h", "/api/labels/a.b?x=/..", null, gson));
+ }
+
@Test
void buildUrlStripsTrailingSlashAndPreservesPrefix() {
assertEquals("http://h:2785/api/sessions", Http.buildUrl("http://h:2785/", "/api/sessions", null, gson));