Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix(rest): keep the device group last, and harden the status-media guard

Aldino Kemald6b404e8a0f6
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index ec0391d2..deb5ba90 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -2664,10 +2664,10 @@ paths:
count:
type: integer
default: 50
- minimum: 1
+ minimum: 0
maximum: 500
example: 50
- description: Number of older messages to request from the phone
+ description: Number of older messages to request from the phone. Omit it, or send 0, to use the default of 50.
responses:
'200':
description: OK
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index b6fbd910..4974d4a5 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -182,10 +182,6 @@ func restServer(_ *cobra.Command, _ []string) {
apiGroup.Delete("/devices/:device_id/chatwoot/config", chatwootHandler.DeleteChatwootConfig)
}
- // Device-scoped operations (header-based)
- headerDeviceGroup := apiGroup.Group("", middleware.DeviceMiddleware(dm))
- registerDeviceScopedRoutes(headerDeviceGroup)
-
// Dashboard: gowa-ui is a separate project released as one HTML file;
// serve the runtime-downloaded copy at "/" (behind basic auth like the
// rest of the API surface).
@@ -193,6 +189,13 @@ func restServer(_ *cobra.Command, _ []string) {
defer uiCancel()
registerUIRoute(apiGroup, uiCtx)
+ // Device-scoped operations (header-based). This must stay the LAST
+ // registration on apiGroup: Group("") registers a root "use" route that
+ // matches every path, so DeviceMiddleware would also run for anything
+ // mounted after it. TestDeviceGroupIsRegisteredLast pins the order.
+ headerDeviceGroup := apiGroup.Group("", middleware.DeviceMiddleware(dm))
+ registerDeviceScopedRoutes(headerDeviceGroup)
+
go websocket.RunHub()
// Set auto reconnect to whatsapp server after booting
diff --git a/src/cmd/rest_route_order_test.go b/src/cmd/rest_route_order_test.go
new file mode 100644
index 00000000..34675ed4
--- /dev/null
+++ b/src/cmd/rest_route_order_test.go
@@ -0,0 +1,96 @@
+package cmd
+
+import (
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+// TestDeviceGroupIsRegisteredLast pins the ordering invariant in restServer.
+//
+// apiGroup.Group("", DeviceMiddleware(dm)) does not scope the middleware to
+// the returned group: fiber registers it as a root "use" route that matches
+// every path, and the route stack is walked in registration order. So every
+// route mounted on apiGroup *after* that call silently inherits
+// DeviceMiddleware — which is what broke the chatwoot config endpoints in
+// multi-device setups (#837).
+//
+// restServer builds a live listener, so there is no runtime seam to assert
+// this on. The invariant is therefore checked against the source: the device
+// group must be the last thing registered on apiGroup.
+func TestDeviceGroupIsRegisteredLast(t *testing.T) {
+ fset := token.NewFileSet()
+ file, err := parser.ParseFile(fset, "rest.go", nil, 0)
+ require.NoError(t, err)
+
+ var body *ast.BlockStmt
+ for _, decl := range file.Decls {
+ if fn, ok := decl.(*ast.FuncDecl); ok && fn.Name.Name == "restServer" {
+ body = fn.Body
+ break
+ }
+ }
+ require.NotNil(t, body, "restServer not found in rest.go")
+
+ isAPIGroup := func(e ast.Expr) bool {
+ id, ok := e.(*ast.Ident)
+ return ok && id.Name == "apiGroup"
+ }
+
+ var groupPos token.Pos
+ type mount struct {
+ pos token.Pos
+ desc string
+ }
+ var mounts []mount
+
+ ast.Inspect(body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ // apiGroup.<Method>(...)
+ if sel, ok := call.Fun.(*ast.SelectorExpr); ok && isAPIGroup(sel.X) {
+ if sel.Sel.Name == "Group" {
+ groupPos = call.Pos()
+ } else {
+ mounts = append(mounts, mount{call.Pos(), "apiGroup." + sel.Sel.Name + "(...)"})
+ }
+ return true
+ }
+ // f(apiGroup, ...) — InitRest*, uimcp.Register, registerUIRoute
+ for _, arg := range call.Args {
+ if isAPIGroup(arg) {
+ mounts = append(mounts, mount{call.Pos(), callName(call) + "(apiGroup, ...)"})
+ break
+ }
+ }
+ return true
+ })
+
+ require.NotZero(t, groupPos, `apiGroup.Group("", DeviceMiddleware(dm)) not found in restServer`)
+ require.NotEmpty(t, mounts, "no apiGroup registrations found — test is not checking anything")
+
+ for _, m := range mounts {
+ require.Less(t, int(m.pos), int(groupPos),
+ "%s is registered at %s, after the device group at %s — it will inherit DeviceMiddleware. "+
+ "Move it above the apiGroup.Group(\"\", ...) call.",
+ m.desc, fset.Position(m.pos), fset.Position(groupPos))
+ }
+}
+
+func callName(call *ast.CallExpr) string {
+ switch fn := call.Fun.(type) {
+ case *ast.Ident:
+ return fn.Name
+ case *ast.SelectorExpr:
+ if x, ok := fn.X.(*ast.Ident); ok {
+ return x.Name + "." + fn.Sel.Name
+ }
+ return fn.Sel.Name
+ }
+ return "call"
+}
diff --git a/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go b/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go
index 6de3ecc3..3bf7577b 100644
--- a/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go
+++ b/src/infrastructure/chatstorage/sqlite_repository_message_lookup.go
@@ -44,7 +44,7 @@ func (r *SQLiteRepository) GetOldestMessageByDevice(deviceID, chatJID string) (*
file_enc_sha256, file_length, referral_metadata, created_at, updated_at
FROM messages
WHERE chat_jid = ? AND device_id = ? AND (media_type IS NULL OR media_type != 'call')
- ORDER BY timestamp ASC
+ ORDER BY timestamp ASC, id ASC
LIMIT 1
`
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index a1aada38..4679bfda 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -82,7 +82,12 @@ func shouldIgnoreImageDownload(autoDownloadMedia, ignoreStatusMedia bool, chatJI
if !autoDownloadMedia {
return true
}
- if ignoreStatusMedia && chatJID == types.StatusBroadcastJID {
+ // Match on the JID's shape rather than struct equality: whatsmeow's
+ // broadcast branch assigns source.Chat without ToNonAD(), so a
+ // device-qualified status JID would not compare equal to
+ // types.StatusBroadcastJID. IsBroadcastList() is defined as "broadcast
+ // server and user != status", so negating it selects exactly status.
+ if ignoreStatusMedia && chatJID.Server == types.BroadcastServer && !chatJID.IsBroadcastList() {
return true
}
return false
diff --git a/src/infrastructure/whatsapp/event_message_handler_test.go b/src/infrastructure/whatsapp/event_message_handler_test.go
index cabe47f4..9c18dbe4 100644
--- a/src/infrastructure/whatsapp/event_message_handler_test.go
+++ b/src/infrastructure/whatsapp/event_message_handler_test.go
@@ -333,6 +333,15 @@ func TestShouldIgnoreImageDownload(t *testing.T) {
chatJID: types.NewJID("123456789", types.DefaultUserServer),
expected: false,
},
+ {
+ // whatsmeow's broadcast branch does not ToNonAD() source.Chat, so
+ // the status JID can arrive device-qualified and must still match.
+ name: "device-qualified status jid ignored",
+ autoDownloadMedia: true,
+ ignoreStatusMedia: true,
+ chatJID: types.JID{User: "status", Server: types.BroadcastServer, Device: 1},
+ expected: true,
+ },
}
for _, tt := range tests {
diff --git a/src/ui/rest/chatwoot_config_test.go b/src/ui/rest/chatwoot_config_test.go
index b1521783..5f70af8c 100644
--- a/src/ui/rest/chatwoot_config_test.go
+++ b/src/ui/rest/chatwoot_config_test.go
@@ -396,4 +396,3 @@ func TestChatwootConfigMultiDeviceNoDeviceMiddlewareLeak(t *testing.T) {
}
})
}
-