GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
fix!: lock down session file permissions and webhook tls verification (#925)
Aldino Kemala60a5a06ecce
diff --git a/readme.md b/readme.mdindex 4abd4c52..ad7aadb8 100644--- a/readme.md+++ b/readme.md@@ -261,8 +261,8 @@ To use environment variables:| `MCP_OAUTH_ISSUER_URL` | Public HTTPS OAuth issuer URL | - | `MCP_OAUTH_ISSUER_URL=https://gowa.example.com` || `MCP_OAUTH_RESOURCE_URL` | Optional canonical public MCP URL | Derived from issuer and base path | `MCP_OAUTH_RESOURCE_URL=https://gowa.example.com/mcp` || `MCP_OAUTH_DB_URI` | SQLite URI for OAuth clients, codes, and token hashes | `file:storages/oauth.db` | `MCP_OAUTH_DB_URI=file:storages/oauth.db` |-| `DB_URI` | Database connection URI | `file:storages/whatsapp.db` | `DB_URI=postgres://user:pass@host/db` |-| `DB_KEYS_URI` | Optional database URI for encryption/session key cache. Leave blank to use `DB_URI`; avoid in-memory storage in production because restarts can lose WhatsApp session state. | - | `DB_KEYS_URI=file:storages/whatsapp-keys.db?_foreign_keys=on` |+| `DB_URI` | Database connection URI. A Postgres URI without `sslmode` (or `PGSSLMODE`) uses `verify-full` for remote hosts and `disable` for loopback targets (`localhost`, `127.0.0.1`, `::1`) or unix sockets; set `sslmode=require` to keep unverified TLS. | `file:storages/whatsapp.db` | `DB_URI=postgres://user:pass@host/db` |+| `DB_KEYS_URI` | Optional database URI for encryption/session key cache. Leave blank to use `DB_URI`; avoid in-memory storage in production because restarts can lose WhatsApp session state. A Postgres URI gets the same `sslmode` default as `DB_URI`. | - | `DB_KEYS_URI=file:storages/whatsapp-keys.db?_foreign_keys=on` || `CHAT_STORAGE_MAX_OPEN_CONNS` | Maximum concurrent SQLite connections for chat storage | `5` | `CHAT_STORAGE_MAX_OPEN_CONNS=10` || `WHATSAPP_AUTO_REPLY` | Auto-reply message | - | `WHATSAPP_AUTO_REPLY="Auto reply message"` || `WHATSAPP_AUTO_MARK_READ` | Auto-mark incoming messages as read | `false` | `WHATSAPP_AUTO_MARK_READ=true` |diff --git a/src/.env.example b/src/.env.exampleindex d457f231..8d4299e2 100644--- a/src/.env.example+++ b/src/.env.example@@ -39,6 +39,13 @@ MCP_OAUTH_RESOURCE_URL=MCP_OAUTH_DB_URI=file:storages/oauth.db# Database Settings+# SQLite session files are created with owner-only permissions.+# A PostgreSQL DB_URI or DB_KEYS_URI that omits sslmode uses sslmode=verify-full+# for the host lib/pq will dial (URL host, host, hostaddr, PGHOST, PGHOSTADDR).+# localhost, 127.0.0.1, ::1, and unix sockets use sslmode=disable. A blank+# sslmode is ignored. Set a non-empty sslmode in the URI to override.+# An sslmode from PGSSLMODE or a PGSERVICE entry (PGSERVICEFILE selects the+# file) is kept as is; a service entry's host and sslmode override the URI.DB_URI=file:storages/whatsapp.db?_foreign_keys=onDB_KEYS_URI=# Max concurrent SQLite connections for chat storage (default: 5, min: 1).diff --git a/src/cmd/root.go b/src/cmd/root.goindex 27f3e2f9..40e6a557 100644--- a/src/cmd/root.go+++ b/src/cmd/root.go@@ -668,6 +668,9 @@ func initFlags() {}func initChatStorage() (*sql.DB, error) {+ if err := whatsapp.SecureSQLiteFile(config.ChatStorageURI); err != nil {+ return nil, fmt.Errorf("prepare chat storage file: %w", err)+ }connStr := sqlite.FormatChatStorageURI(config.ChatStorageURI, config.ChatStorageEnableWAL, config.ChatStorageEnableForeignKeys)db, err := sql.Open(sqlite.DriverName, connStr)diff --git a/src/infrastructure/whatsapp/database.go b/src/infrastructure/whatsapp/database.goindex cacf583c..5119d564 100644--- a/src/infrastructure/whatsapp/database.go+++ b/src/infrastructure/whatsapp/database.go@@ -2,12 +2,24 @@ package whatsappimport ("context"+ "errors""fmt"+ "io/fs"+ "net"+ "net/netip"+ "net/url"+ "os"+ "path/filepath"+ "runtime"+ "slices""strings"+ "syscall""github.com/aldinokemal/go-whatsapp-web-multidevice/config"pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"+ "github.com/lib/pq"+ "github.com/sirupsen/logrus""go.mau.fi/whatsmeow/store/sqlstore"waLog "go.mau.fi/whatsmeow/util/log")@@ -32,11 +44,340 @@ func initDatabase(ctx context.Context, dbLog waLog.Logger, DBURI string) (*sqlstDBURI = strings.Trim(DBURI, `"'`)if strings.HasPrefix(DBURI, "file:") {+ // Restrict the session file before the driver creates it. Both the CGO+ // sqlite3 driver and modernc.org/sqlite (-tags purego) honor an+ // existing file's mode and give sidecars created during open the+ // database file's mode. FormatChatStorageURI still applies WAL, the 30s+ // busy timeout, and foreign keys.+ if err := SecureSQLiteFile(DBURI); err != nil {+ return nil, fmt.Errorf("prepare sqlite session file: %w", err)+ }DBURI = sqlite.FormatChatStorageURI(DBURI, true, true)- return sqlstore.New(ctx, sqlite.DriverName, DBURI, dbLog)+ container, err := sqlstore.New(ctx, sqlite.DriverName, DBURI, dbLog)+ if err != nil {+ return nil, err+ }+ if err := SecureSQLiteFile(DBURI); err != nil {+ _ = container.Close()+ return nil, fmt.Errorf("restrict sqlite session file: %w", err)+ }+ return container, nil} else if strings.HasPrefix(DBURI, "postgres:") {- return sqlstore.New(ctx, "postgres", DBURI, dbLog)+ // applyPostgresTLSDefault preserves a non-empty sslmode. Otherwise the+ // host lib/pq will dial selects sslmode=disable or sslmode=verify-full.+ // Set sslmode in DB_URI or DB_KEYS_URI to override.+ secured, err := applyPostgresTLSDefault(DBURI)+ if err != nil {+ return nil, err+ }+ return sqlstore.New(ctx, "postgres", secured, dbLog)}return nil, fmt.Errorf("unknown database type: %s. Currently only sqlite3(file:) and postgres are supported", DBURI)}++// SecureSQLiteFile makes the database file of a SQLite file: URI owner-read/write+// (0600) before it is opened. A directory it has to create is owner-only (0700);+// an existing directory is left as is. Memory and other non-file URIs are left+// untouched. Existing files are tightened in place; they are not truncated.+func SecureSQLiteFile(uri string) error {+ target, err := sqliteSessionTarget(uri)+ if err != nil {+ return err+ }+ if target.skip {+ return nil+ }++ dir := filepath.Dir(target.path)+ if target.create {+ if err := secureSQLiteSessionDir(dir); err != nil {+ return err+ }+ }+ if err := secureSQLiteSessionDB(target.path, target.create); err != nil {+ return err+ }+ for _, suffix := range []string{"-wal", "-shm", "-journal"} {+ if err := chmodExistingFile(target.path+suffix, 0600); err != nil {+ return err+ }+ }+ return nil+}++type sqliteTarget struct {+ path string+ create bool+ skip bool+}++func sqliteSessionTarget(uri string) (sqliteTarget, error) {+ raw, ok := strings.CutPrefix(uri, "file:")+ if !ok {+ return sqliteTarget{skip: true}, nil+ }+ // SQLite stops reading the URI at '#', even when a query follows it.+ raw, _, _ = strings.Cut(raw, "#")+ base, query, _ := strings.Cut(raw, "?")+ create := true+ if query != "" {+ q, err := url.ParseQuery(query)+ if err != nil {+ return sqliteTarget{}, fmt.Errorf("parse sqlite uri: %w", err)+ }+ if strings.EqualFold(q.Get("mode"), "memory") {+ return sqliteTarget{skip: true}, nil+ }+ // SQLite creates a missing file only for mode=rwc, its default, and+ // never for an immutable database.+ mode := strings.ToLower(q.Get("mode"))+ immutable := strings.ToLower(q.Get("immutable"))+ if (mode != "" && mode != "rwc") || slices.Contains([]string{"1", "true", "yes", "on"}, immutable) {+ create = false+ }+ }+ if base == "" || base == ":memory:" || strings.HasPrefix(base, ":memory:") {+ return sqliteTarget{skip: true}, nil+ }++ path, err := sqliteURIPath(base)+ if err != nil {+ return sqliteTarget{}, err+ }+ if path == "" || path == "." || path == string(filepath.Separator) {+ return sqliteTarget{skip: true}, nil+ }+ return sqliteTarget{path: path, create: create}, nil+}++func sqliteURIPath(base string) (string, error) {+ var path string+ if strings.HasPrefix(base, "//") {+ u, err := url.Parse("file:" + base)+ if err != nil {+ return "", fmt.Errorf("parse sqlite uri: %w", err)+ }+ path = u.Path+ } else {+ decoded, err := url.PathUnescape(base)+ if err != nil {+ return "", fmt.Errorf("parse sqlite uri: %w", err)+ }+ path = decoded+ }+ if path == "" {+ return "", nil+ }+ // SQLite drops the slash before a Windows drive letter (file:///C:/x.db).+ if runtime.GOOS == "windows" && len(path) >= 3 && (path[0] == '/' || path[0] == '\\') && path[2] == ':' {+ path = path[1:]+ }+ return filepath.Clean(path), nil+}++func secureSQLiteSessionDir(dir string) error {+ if dir == "" || dir == "." || filepath.Clean(dir) == string(filepath.Separator) {+ return nil+ }+ // Only a directory created here is made owner-only. An existing one may be+ // shared (/tmp) or owned by another user (NFS root_squash, volume mounts).+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ return err+ }+ if err := os.MkdirAll(dir, 0700); err != nil {+ return err+ }+ return os.Chmod(dir, 0700)+}++func secureSQLiteSessionDB(path string, create bool) error {+ if _, err := os.Stat(path); err != nil {+ if !os.IsNotExist(err) {+ return err+ }+ if !create {+ return nil+ }+ // OpenFile applies the process umask, so a follow-up Chmod is required+ // to land on 0600 even when umask is 0.+ f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)+ if err != nil {+ return err+ }+ if err := f.Close(); err != nil {+ return err+ }+ }+ return chmodExistingFile(path, 0600)+}++func chmodExistingFile(path string, mode os.FileMode) error {+ info, err := os.Stat(path)+ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return err+ }+ if info.IsDir() {+ return fmt.Errorf("sqlite session path %s is a directory", path)+ }+ // A file owned by another user or on a read-only mount keeps its mode.+ // SQLite can still open it, so warn instead of failing startup.+ err = os.Chmod(path, mode)+ if errors.Is(err, fs.ErrPermission) || errors.Is(err, syscall.EROFS) {+ logrus.Warnf("could not restrict SQLite file to owner-only access: %v", err)+ return nil+ }+ return err+}++// applyPostgresTLSDefault sets a TLS mode when the DSN does not already+// contain a non-empty sslmode query parameter.+//+// lib/pq reads only the first sslmode value (url.Values.Get) and drops it+// when that value is blank, which leaves SSLMode empty and skips certificate+// checks. A non-empty first value is preserved, including disable, require,+// verify-ca, and verify-full. A missing or blank first value is not a choice.+// Later blank entries are dropped; if a later value is non-empty, that single+// value is written so pq.NewConfig reports it. Otherwise the dial-target+// default applies. Override the defaults with a non-empty first sslmode in+// DB_URI or DB_KEYS_URI.+//+// The mode follows the address lib/pq will dial, from pq.NewConfig: URL+// authority, query host and hostaddr, PGHOST, and PGHOSTADDR. If any dial+// target is not loopback (localhost, 127.0.0.1, ::1) and not a unix-socket+// path, the default is sslmode=verify-full. Loopback and unix-socket targets+// use sslmode=disable so a local Postgres without TLS still connects.+// A mode lib/pq already resolved (PGSSLMODE, a service file, or the+// verify-full implied by sslrootcert=system) is left in place, and so is a+// local DSN with sslnegotiation=direct, which lib/pq rejects with disable. A+// remote hostaddr with a loopback or empty host is an error: verify-full+// checks the certificate against host. The query is written on the parsed+// URL so a fragment stays a fragment.+func applyPostgresTLSDefault(dsn string) (string, error) {+ u, err := url.Parse(dsn)+ if err != nil {+ // url.Parse errors quote the whole DSN, password included.+ return "", errors.New("parse postgres dsn: invalid URI")+ }+ if u.Scheme != "postgres" && u.Scheme != "postgresql" {+ return "", fmt.Errorf("unsupported postgres scheme %q", u.Scheme)+ }+ if _, ok := leadingPostgresSSLMode(u); ok {+ return dsn, nil+ }+ if promoted := promotedPostgresSSLMode(u); promoted != "" {+ return setPostgresSSLMode(u, promoted), nil+ }++ cfg, err := pq.NewConfig(dsn)+ if err != nil {+ // lib/pq errors can quote DSN text, such as an opaque postgres:user:pass@host+ // URI or a password cut short by an unescaped '#'.+ return "", errors.New("parse postgres dial target: invalid connection settings")+ }+ // Keep a mode lib/pq already took from PGSSLMODE, a service file, or+ // sslrootcert=system (verify-full); a DSN sslmode would replace it.+ if cfg.SSLMode != "" {+ return dsn, nil+ }+ remote, err := postgresDialTargetIsRemote(cfg)+ if err != nil {+ return "", err+ }+ // lib/pq rejects sslmode=disable together with sslnegotiation=direct.+ if !remote && cfg.SSLNegotiation == pq.SSLNegotiationDirect {+ return dsn, nil+ }+ mode := "disable"+ if remote {+ mode = "verify-full"+ }+ return setPostgresSSLMode(u, mode), nil+}++// leadingPostgresSSLMode reports the first sslmode query value when it is+// non-empty. That is the only value lib/pq will read.+func leadingPostgresSSLMode(u *url.URL) (string, bool) {+ values, ok := u.Query()["sslmode"]+ if !ok || len(values) == 0 {+ return "", false+ }+ trimmed := strings.TrimSpace(values[0])+ if trimmed == "" {+ return "", false+ }+ return trimmed, true+}++// promotedPostgresSSLMode returns the first non-blank sslmode after a missing+// or blank first entry. lib/pq never sees those later entries.+func promotedPostgresSSLMode(u *url.URL) string {+ for _, value := range u.Query()["sslmode"] {+ if trimmed := strings.TrimSpace(value); trimmed != "" {+ return trimmed+ }+ }+ return ""+}++// postgresDialTargetIsRemote reports whether lib/pq will dial any TCP address+// that is not the loopback names this package treats as local.+func postgresDialTargetIsRemote(cfg pq.Config) (bool, error) {+ remote := false+ for _, target := range append([]pq.ConfigMultihost{{Host: cfg.Host, Hostaddr: cfg.Hostaddr}}, cfg.Multi...) {+ if !postgresTargetIsRemote(target.Host, target.Hostaddr) {+ continue+ }+ // verify-full checks the server certificate against host, not hostaddr.+ if target.Hostaddr.IsValid() && isLocalPostgresHost(target.Host) {+ return false, fmt.Errorf("hostaddr %s is remote but host is %q; set host to the server certificate name or set sslmode explicitly", target.Hostaddr, target.Host)+ }+ remote = true+ }+ return remote, nil+}++func postgresTargetIsRemote(host string, addr netip.Addr) bool {+ if addr.IsValid() {+ return !isPostgresLoopbackIP(addr)+ }+ host = strings.TrimSpace(host)+ if host == "" || filepath.IsAbs(host) || strings.HasPrefix(host, "@") {+ return false+ }+ return !isLocalPostgresHost(host)+}++func isPostgresLoopbackIP(addr netip.Addr) bool {+ if !addr.IsValid() {+ return false+ }+ if addr.Is4() {+ return addr == netip.MustParseAddr("127.0.0.1")+ }+ return addr == netip.MustParseAddr("::1")+}++func isLocalPostgresHost(host string) bool {+ host = strings.TrimSpace(host)+ host = strings.Trim(host, "[]")+ if host == "" || strings.EqualFold(host, "localhost") {+ return true+ }+ ip := net.ParseIP(host)+ if ip == nil {+ return false+ }+ return ip.Equal(net.ParseIP("127.0.0.1")) || ip.Equal(net.IPv6loopback)+}++func setPostgresSSLMode(u *url.URL, mode string) string {+ cloned := *u+ query := cloned.Query()+ query.Set("sslmode", mode)+ cloned.RawQuery = query.Encode()+ return cloned.String()+}diff --git a/src/infrastructure/whatsapp/database_test.go b/src/infrastructure/whatsapp/database_test.gonew file mode 100644index 00000000..ecbf25db--- /dev/null+++ b/src/infrastructure/whatsapp/database_test.go@@ -0,0 +1,502 @@+package whatsapp++import (+ "net/url"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "testing"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite"+ "github.com/lib/pq"+)++func TestApplyPostgresTLSDefault(t *testing.T) {+ isolatePostgresDialEnv(t)++ tests := []struct {+ name string+ dsn string+ pgsslmode string+ wantMode string+ same bool+ }{+ {+ name: "public host gains verify-full",+ dsn: "postgres://user:[email protected]:5432/whatsapp",+ wantMode: "verify-full",+ },+ {+ name: "public host keeps existing query and encoded password",+ dsn: "postgres://user:p%[email protected]/whatsapp?connect_timeout=5",+ wantMode: "verify-full",+ },+ {+ name: "localhost is not forced to verify-full",+ dsn: "postgres://user:secret@localhost:5432/whatsapp",+ wantMode: "disable",+ },+ {+ name: "localhost hostname is case-insensitive",+ dsn: "postgresql://user:secret@LocalHost/whatsapp",+ wantMode: "disable",+ },+ {+ name: "ipv4 loopback is not forced to verify-full",+ dsn: "postgres://user:[email protected]:5432/whatsapp",+ wantMode: "disable",+ },+ {+ name: "ipv6 loopback is not forced to verify-full",+ dsn: "postgres://user:secret@[::1]:5432/whatsapp",+ wantMode: "disable",+ },+ {+ name: "empty host follows lib/pq localhost default",+ dsn: "postgres://user:secret@/whatsapp",+ wantMode: "disable",+ },+ {+ name: "explicit sslmode on a public host is preserved",+ dsn: "postgres://user:[email protected]/whatsapp?sslmode=require",+ same: true,+ },+ {+ name: "explicit disable on a public host is preserved",+ dsn: "postgres://user:[email protected]/whatsapp?application_name=gowa&sslmode=disable",+ same: true,+ },+ {+ name: "explicit verify-full on localhost is preserved",+ dsn: "postgres://user:secret@localhost/whatsapp?sslmode=verify-full",+ same: true,+ },+ {+ name: "localhost suffix is not treated as loopback",+ dsn: "postgres://user:[email protected]/whatsapp",+ wantMode: "verify-full",+ },+ {+ name: "localhost.evil.com stays verify-full",+ dsn: "postgres://user:[email protected]/whatsapp",+ wantMode: "verify-full",+ },+ {+ name: "userinfo is not the host",+ dsn: "postgres://localhost:[email protected]/whatsapp",+ wantMode: "verify-full",+ },+ {+ name: "PGSSLMODE=require on localhost is not replaced with disable",+ dsn: "postgres://user:secret@localhost/whatsapp",+ pgsslmode: "require",+ same: true,+ },+ {+ name: "PGSSLMODE=disable on a public host is not replaced with verify-full",+ dsn: "postgres://user:[email protected]/whatsapp",+ pgsslmode: "disable",+ same: true,+ },+ {+ name: "PGSSLMODE=verify-full on localhost is not replaced with disable",+ dsn: "postgres://user:secret@localhost/whatsapp",+ pgsslmode: "verify-full",+ same: true,+ },+ {+ name: "sslrootcert=system on localhost keeps its implied verify-full",+ dsn: "postgres://user:secret@localhost/whatsapp?sslrootcert=system",+ same: true,+ },+ {+ name: "sslnegotiation=direct on localhost is not given disable",+ dsn: "postgres://user:secret@localhost/whatsapp?sslnegotiation=direct",+ same: true,+ },+ }++ for _, tc := range tests {+ t.Run(tc.name, func(t *testing.T) {+ if tc.pgsslmode != "" {+ t.Setenv("PGSSLMODE", tc.pgsslmode)+ }+ got, err := applyPostgresTLSDefault(tc.dsn)+ if err != nil {+ t.Fatalf("applyPostgresTLSDefault: %v", err)+ }+ if tc.same {+ if got != tc.dsn {+ t.Fatalf("explicit sslmode changed\n got %s\nwant %s", got, tc.dsn)+ }+ mustPostgresConfig(t, got)+ return+ }+ sep := "?"+ if strings.Contains(tc.dsn, "?") {+ sep = "&"+ }+ want := tc.dsn + sep + "sslmode=" + tc.wantMode+ if got != want {+ t.Fatalf("dsn = %s, want %s", got, want)+ }+ u, err := url.Parse(got)+ if err != nil {+ t.Fatalf("parse result: %v", err)+ }+ if u.Query().Get("sslmode") != tc.wantMode {+ t.Fatalf("sslmode = %q, want %q", u.Query().Get("sslmode"), tc.wantMode)+ }+ if strings.Contains(tc.dsn, "p%40ss") && !strings.Contains(got, "p%40ss") {+ t.Fatalf("encoded password was rewritten: %s", got)+ }+ })+ }+}++func TestApplyPostgresTLSDefaultUsesDialTarget(t *testing.T) {+ isolatePostgresDialEnv(t)++ t.Run("remote hostaddr without a certificate host name is rejected", func(t *testing.T) {+ // verify-full would check the certificate against localhost or "".+ for _, in := range []string{+ "postgres://user:secret@localhost/whatsapp?hostaddr=203.0.113.10",+ "postgres://user:secret@/whatsapp?hostaddr=203.0.113.10",+ } {+ assertRemoteHostaddrRejected(t, in)+ }+ // An explicit sslmode is the documented way out.+ in := "postgres://user:secret@localhost/whatsapp?hostaddr=203.0.113.10&sslmode=require"+ if got := mustApplyPostgresTLSDefault(t, in); got != in {+ t.Fatalf("explicit sslmode changed\n got %s\nwant %s", got, in)+ }+ })++ t.Run("query host overrides localhost", func(t *testing.T) {+ in := "postgres://user:secret@localhost/whatsapp?host=prod.example.com"+ got := mustApplyPostgresTLSDefault(t, in)+ assertPostgresSSLMode(t, got, "verify-full")+ cfg := mustPostgresConfig(t, got)+ if cfg.Host != "prod.example.com" {+ t.Fatalf("dial host = %q, want prod.example.com", cfg.Host)+ }+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("PGHOST on empty authority", func(t *testing.T) {+ t.Setenv("PGHOST", "db.example.com")+ in := "postgres://user:secret@/whatsapp"+ got := mustApplyPostgresTLSDefault(t, in)+ if strings.Contains(got, "sslmode=disable") {+ t.Fatalf("remote PGHOST was given sslmode=disable: %s", got)+ }+ assertPostgresSSLMode(t, got, "verify-full")+ cfg := mustPostgresConfig(t, got)+ if cfg.Host != "db.example.com" {+ t.Fatalf("dial host = %q, want db.example.com", cfg.Host)+ }+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("PGSSLMODE verify-full is not replaced with disable", func(t *testing.T) {+ t.Setenv("PGHOST", "db.example.com")+ t.Setenv("PGSSLMODE", "verify-full")+ in := "postgres://user:secret@/whatsapp"+ got := mustApplyPostgresTLSDefault(t, in)+ if strings.Contains(got, "sslmode=disable") {+ t.Fatalf("PGSSLMODE=verify-full was rewritten to disable: %s", got)+ }+ if got != in {+ t.Fatalf("DSN was rewritten even though PGSSLMODE=verify-full\n got %s\nwant %s", got, in)+ }+ cfg := mustPostgresConfig(t, got)+ if cfg.Host != "db.example.com" {+ t.Fatalf("dial host = %q, want db.example.com", cfg.Host)+ }+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("remote PGHOSTADDR with localhost host is rejected", func(t *testing.T) {+ t.Setenv("PGHOSTADDR", "203.0.113.10")+ assertRemoteHostaddrRejected(t, "postgres://user:secret@localhost/whatsapp")+ })++ t.Run("blank first sslmode yields to a later verify-full", func(t *testing.T) {+ in := "postgres://user:[email protected]/whatsapp?sslmode=&sslmode=verify-full"+ got := mustApplyPostgresTLSDefault(t, in)+ assertPostgresSSLMode(t, got, "verify-full")+ cfg := mustPostgresConfig(t, got)+ if cfg.Host != "db.example.com" {+ t.Fatalf("dial host = %q, want db.example.com", cfg.Host)+ }+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("blank first sslmode yields to a later require", func(t *testing.T) {+ in := "postgres://user:[email protected]/whatsapp?sslmode=&sslmode=require"+ got := mustApplyPostgresTLSDefault(t, in)+ assertPostgresSSLMode(t, got, "require")+ cfg := mustPostgresConfig(t, got)+ if cfg.SSLMode != pq.SSLModeRequire {+ t.Fatalf("SSLMode = %q, want require", cfg.SSLMode)+ }+ })++ t.Run("non-empty first sslmode stays ahead of a blank repeat", func(t *testing.T) {+ in := "postgres://user:[email protected]/whatsapp?sslmode=verify-full&sslmode="+ got := mustApplyPostgresTLSDefault(t, in)+ if got != in {+ t.Fatalf("DSN with a non-empty first sslmode changed\n got %s\nwant %s", got, in)+ }+ cfg := mustPostgresConfig(t, got)+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("repeated blank sslmode uses the remote default", func(t *testing.T) {+ in := "postgres://user:[email protected]/whatsapp?sslmode=&sslmode="+ got := mustApplyPostgresTLSDefault(t, in)+ assertPostgresSSLMode(t, got, "verify-full")+ cfg := mustPostgresConfig(t, got)+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("blank sslmode is not explicit", func(t *testing.T) {+ in := "postgres://user:[email protected]/whatsapp?sslmode="+ got := mustApplyPostgresTLSDefault(t, in)+ assertPostgresSSLMode(t, got, "verify-full")+ cfg := mustPostgresConfig(t, got)+ if cfg.Host != "db.example.com" {+ t.Fatalf("dial host = %q, want db.example.com", cfg.Host)+ }+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("fragment stays a fragment", func(t *testing.T) {+ in := "postgres://user:[email protected]/whatsapp#frag"+ got := mustApplyPostgresTLSDefault(t, in)+ u, err := url.Parse(got)+ if err != nil {+ t.Fatalf("parse result: %v", err)+ }+ if u.Fragment != "frag" {+ t.Fatalf("fragment = %q, want frag in %s", u.Fragment, got)+ }+ if u.Query().Get("sslmode") != "verify-full" {+ t.Fatalf("sslmode = %q, want verify-full in %s", u.Query().Get("sslmode"), got)+ }+ if strings.Contains(u.Fragment, "sslmode") {+ t.Fatalf("sslmode was appended to the fragment: %s", got)+ }+ cfg := mustPostgresConfig(t, got)+ if cfg.SSLMode != pq.SSLModeVerifyFull {+ t.Fatalf("SSLMode = %q, want verify-full", cfg.SSLMode)+ }+ })++ t.Run("localhost without override stays disable", func(t *testing.T) {+ in := "postgres://user:secret@localhost/whatsapp"+ got := mustApplyPostgresTLSDefault(t, in)+ assertPostgresSSLMode(t, got, "disable")+ cfg := mustPostgresConfig(t, got)+ if cfg.Host != "localhost" {+ t.Fatalf("dial host = %q, want localhost", cfg.Host)+ }+ if cfg.Hostaddr.IsValid() {+ t.Fatalf("dial hostaddr = %s, want none", cfg.Hostaddr.String())+ }+ if cfg.SSLMode != pq.SSLModeDisable {+ t.Fatalf("SSLMode = %q, want disable", cfg.SSLMode)+ }+ })++ t.Run("explicit require stays require", func(t *testing.T) {+ in := "postgres://user:[email protected]/whatsapp?sslmode=require"+ got := mustApplyPostgresTLSDefault(t, in)+ if got != in {+ t.Fatalf("explicit sslmode changed\n got %s\nwant %s", got, in)+ }+ cfg := mustPostgresConfig(t, got)+ if cfg.Host != "db.example.com" {+ t.Fatalf("dial host = %q, want db.example.com", cfg.Host)+ }+ if cfg.SSLMode != pq.SSLModeRequire {+ t.Fatalf("SSLMode = %q, want require", cfg.SSLMode)+ }+ })+}++func TestApplyPostgresTLSDefaultErrorsOmitPassword(t *testing.T) {+ isolatePostgresDialEnv(t)++ for _, dsn := range []string{+ "postgres://user:secret@host:abc/db", // url.Parse quotes the input+ "postgres:user:secret@host/db", // lib/pq quotes an opaque URI as a key+ "postgres://user:99999#secret@host/db", // '#' leaves "99999" as an invalid port+ } {+ _, err := applyPostgresTLSDefault(dsn)+ if err == nil {+ t.Fatalf("applyPostgresTLSDefault(%q) succeeded, want an error", dsn)+ }+ if strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "99999") {+ t.Fatalf("error for %q contains password text: %v", dsn, err)+ }+ }+}++func isolatePostgresDialEnv(t *testing.T) {+ t.Helper()+ for _, key := range []string{"PGHOST", "PGHOSTADDR", "PGSSLMODE", "PGSERVICE"} {+ value, ok := os.LookupEnv(key)+ t.Cleanup(func() {+ if ok {+ os.Setenv(key, value)+ } else {+ os.Unsetenv(key)+ }+ })+ if err := os.Unsetenv(key); err != nil {+ t.Fatal(err)+ }+ }+}++func mustApplyPostgresTLSDefault(t *testing.T, dsn string) string {+ t.Helper()+ got, err := applyPostgresTLSDefault(dsn)+ if err != nil {+ t.Fatalf("applyPostgresTLSDefault(%q): %v", dsn, err)+ }+ return got+}++func assertRemoteHostaddrRejected(t *testing.T, dsn string) {+ t.Helper()+ got, err := applyPostgresTLSDefault(dsn)+ if err == nil || !strings.Contains(err.Error(), "hostaddr 203.0.113.10 is remote") {+ t.Fatalf("applyPostgresTLSDefault(%q) = %q, %v; want remote hostaddr error", dsn, got, err)+ }+}++func assertPostgresSSLMode(t *testing.T, dsn, want string) {+ t.Helper()+ u, err := url.Parse(dsn)+ if err != nil {+ t.Fatalf("parse %q: %v", dsn, err)+ }+ if got := u.Query().Get("sslmode"); got != want {+ t.Fatalf("sslmode = %q, want %q in %s", got, want, dsn)+ }+}++func mustPostgresConfig(t *testing.T, dsn string) pq.Config {+ t.Helper()+ cfg, err := pq.NewConfig(dsn)+ if err != nil {+ t.Fatalf("pq.NewConfig(%q): %v", dsn, err)+ }+ return cfg+}++func TestSQLiteDatabasePathSurvivesPragmas(t *testing.T) {+ original := "file:storages/whatsapp.db"+ formatted := sqlite.FormatChatStorageURI(original, true, true)+ if !strings.Contains(formatted, "busy_timeout") {+ t.Fatalf("formatted uri dropped busy timeout: %s", formatted)+ }++ before, err := sqliteSessionTarget(original)+ if err != nil {+ t.Fatal(err)+ }+ after, err := sqliteSessionTarget(formatted)+ if err != nil {+ t.Fatal(err)+ }+ if before.skip || after.skip || before.path != after.path {+ t.Fatalf("path changed from %q (skip %v) to %q (skip %v) via %s", before.path, before.skip, after.path, after.skip, formatted)+ }+ if !before.create || !after.create {+ t.Fatal("session file should be created when missing")+ }+}++func TestSQLiteMemoryURIDoesNotCreateFile(t *testing.T) {+ target, err := sqliteSessionTarget("file:storages/should-not-exist.db?mode=memory&cache=shared")+ if err != nil {+ t.Fatal(err)+ }+ if !target.skip {+ t.Fatalf("memory uri was treated as a file path %q", target.path)+ }++ memory, err := sqliteSessionTarget("file::memory:")+ if err != nil {+ t.Fatal(err)+ }+ if !memory.skip {+ t.Fatalf(":memory: uri was treated as a file path %q", memory.path)+ }+}++func TestSQLiteNoCreateURIDoesNotCreateFileOrDirectory(t *testing.T) {+ for _, query := range []string{"mode=rw", "mode=ro", "immutable=1", "immutable=true", "immutable=YES", "immutable=on"} {+ dbPath := filepath.Join(t.TempDir(), "missing", "whatsapp.db")+ if err := SecureSQLiteFile("file:" + filepath.ToSlash(dbPath) + "?" + query); err != nil {+ t.Fatalf("%s: %v", query, err)+ }+ if _, err := os.Stat(filepath.Dir(dbPath)); !os.IsNotExist(err) {+ t.Fatalf("%s created %s (stat error %v); SQLite would not create it", query, filepath.Dir(dbPath), err)+ }+ }++ target, err := sqliteSessionTarget("file:storages/whatsapp.db?mode=rwc")+ if err != nil {+ t.Fatal(err)+ }+ if !target.create {+ t.Fatal("mode=rwc session file should be created when missing")+ }+}++func TestSQLiteURIFragmentIsIgnored(t *testing.T) {+ // SQLite ignores everything from '#', so mode=memory in the fragment does not apply.+ for _, uri := range []string{"file:storages/whatsapp.db#backup", "file:storages/whatsapp.db#backup?mode=memory"} {+ target, err := sqliteSessionTarget(uri)+ if err != nil {+ t.Fatal(err)+ }+ if target.skip || !target.create || target.path != filepath.Clean("storages/whatsapp.db") {+ t.Fatalf("%s: target = %+v, want storages/whatsapp.db created when missing", uri, target)+ }+ }+}++func TestSQLiteWindowsDriveLetterURI(t *testing.T) {+ if runtime.GOOS != "windows" {+ t.Skip("drive-letter URIs only apply on Windows")+ }+ for _, uri := range []string{"file:///C:/gowa/whatsapp.db", "file:/C:/gowa/whatsapp.db"} {+ target, err := sqliteSessionTarget(uri)+ if err != nil {+ t.Fatal(err)+ }+ if target.path != `C:\gowa\whatsapp.db` {+ t.Fatalf("%s path = %q, want C:\\gowa\\whatsapp.db", uri, target.path)+ }+ }+}diff --git a/src/infrastructure/whatsapp/database_unix_test.go b/src/infrastructure/whatsapp/database_unix_test.gonew file mode 100644index 00000000..ca983a35--- /dev/null+++ b/src/infrastructure/whatsapp/database_unix_test.go@@ -0,0 +1,118 @@+//go:build unix++package whatsapp++import (+ "context"+ "os"+ "path/filepath"+ "syscall"+ "testing"++ waLog "go.mau.fi/whatsmeow/util/log"+)++func TestSQLiteOpenCreatesOwnerOnlySessionFile(t *testing.T) {+ // Umask is process-wide. This package's tests do not call t.Parallel, and+ // this test restores the previous mask before returning.+ old := syscall.Umask(0)+ t.Cleanup(func() { syscall.Umask(old) })++ t.Run("new file", func(t *testing.T) {+ dbPath := filepath.Join(t.TempDir(), "sessions", "whatsapp.db")+ openSQLiteSession(t, "file:"+dbPath)+ assertSQLiteWrote(t, dbPath)+ assertOwnerOnly(t, dbPath, 0600)+ assertOwnerOnly(t, filepath.Dir(dbPath), 0700)+ assertSidecarsOwnerOnly(t, dbPath)+ })++ t.Run("existing loose file and directory", func(t *testing.T) {+ dir := filepath.Join(t.TempDir(), "sessions")+ if err := os.MkdirAll(dir, 0777); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(dir, 0777); err != nil {+ t.Fatal(err)+ }+ dbPath := filepath.Join(dir, "whatsapp.db")+ if err := os.WriteFile(dbPath, nil, 0666); err != nil {+ t.Fatal(err)+ }+ if err := os.Chmod(dbPath, 0666); err != nil {+ t.Fatal(err)+ }+ if perm := filePerm(t, dbPath); perm&0077 == 0 {+ t.Fatalf("fixture mode %o has no group or other bits; umask hid a loose create", perm)+ }+ if perm := filePerm(t, dir); perm&0077 == 0 {+ t.Fatalf("fixture directory mode %o has no group or other bits", perm)+ }+ openSQLiteSession(t, "file:"+dbPath)+ assertSQLiteWrote(t, dbPath)+ assertOwnerOnly(t, dbPath, 0600)+ // An existing directory may be shared or owned by someone else.+ if perm := filePerm(t, dir); perm != 0777 {+ t.Fatalf("existing directory mode changed to %o, want 0777", perm)+ }+ assertSidecarsOwnerOnly(t, dbPath)+ })+}++func openSQLiteSession(t *testing.T, uri string) {+ t.Helper()+ container, err := initDatabase(context.Background(), waLog.Noop, uri)+ if err != nil {+ t.Fatalf("initDatabase: %v", err)+ }+ t.Cleanup(func() {+ if err := container.Close(); err != nil {+ t.Errorf("close session database: %v", err)+ }+ })+}++func filePerm(t *testing.T, path string) os.FileMode {+ t.Helper()+ info, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ return info.Mode().Perm()+}++func assertSQLiteWrote(t *testing.T, path string) {+ t.Helper()+ info, err := os.Stat(path)+ if err != nil {+ t.Fatal(err)+ }+ if info.Size() == 0 {+ t.Fatalf("%s was not written by sqlite", path)+ }+}++func assertOwnerOnly(t *testing.T, path string, wantOwner os.FileMode) {+ t.Helper()+ perm := filePerm(t, path)+ if perm&0077 != 0 {+ t.Fatalf("%s mode %o includes group or other permissions", path, perm)+ }+ if perm&wantOwner != wantOwner {+ t.Fatalf("%s mode %o is missing owner bits %o", path, perm, wantOwner)+ }+}++func assertSidecarsOwnerOnly(t *testing.T, dbPath string) {+ t.Helper()+ for _, suffix := range []string{"-wal", "-shm", "-journal"} {+ path := dbPath + suffix+ if _, err := os.Stat(path); err != nil {+ if os.IsNotExist(err) {+ continue+ }+ t.Fatal(err)+ }+ assertOwnerOnly(t, path, 0600)+ }+}diff --git a/src/infrastructure/whatsapp/webhook.go b/src/infrastructure/whatsapp/webhook.goindex de23dadf..f7e3c4a1 100644--- a/src/infrastructure/whatsapp/webhook.go+++ b/src/infrastructure/whatsapp/webhook.go@@ -17,29 +17,19 @@ import ()func submitWebhook(ctx context.Context, payload map[string]any, url string, webhookConfig *chatstorage.DeviceWebhookConfig) error {- // Determine effective config - use device-specific if set, otherwise fall back to global- insecureSkipVerify := config.WhatsappWebhookInsecureSkipVerify+ // Device TLS is resolved separately from the signing secret. A nil device+ // config keeps the global bypass; an explicit device flag, including false,+ // replaces it. Secret selection is unchanged.webhookSecret := config.WhatsappWebhookSecretif webhookConfig != nil {- if webhookConfig.WebhookInsecureSkipVerify {- insecureSkipVerify = true- }if webhookConfig.WebhookSecret != "" {webhookSecret = webhookConfig.WebhookSecret}}- // Configure HTTP client with optional TLS skip verification- transport := &http.Transport{- TLSClientConfig: &tls.Config{- InsecureSkipVerify: insecureSkipVerify,- },- }- client := &http.Client{- Timeout: 10 * time.Second,- Transport: transport,- }+ client := newWebhookHTTPClient(webhookConfig)+ defer client.CloseIdleConnections()postBody, err := json.Marshal(payload)if err != nil {@@ -103,3 +93,33 @@ func submitWebhook(ctx context.Context, payload map[string]any, url string, webhreturn pkgError.WebhookError(fmt.Sprintf("error when submit webhook after %d attempts: %v", attempt, err))}++// effectiveWebhookInsecureSkipVerify chooses the TLS bypass for one delivery.+//+// DeviceWebhookConfig.WebhookInsecureSkipVerify is a bool, so it cannot+// represent "unset". Callers pass a nil config when the device did not+// override webhook delivery (global URLs, or no stored device webhook). The+// process-wide WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY value applies only in+// that case. A non-nil config carries the stored device flag: false means+// verify certificates and wins over a global bypass.+func effectiveWebhookInsecureSkipVerify(webhookConfig *chatstorage.DeviceWebhookConfig) bool {+ if webhookConfig != nil {+ return webhookConfig.WebhookInsecureSkipVerify+ }+ return config.WhatsappWebhookInsecureSkipVerify+}++func webhookTLSConfig(webhookConfig *chatstorage.DeviceWebhookConfig) *tls.Config {+ return &tls.Config{+ InsecureSkipVerify: effectiveWebhookInsecureSkipVerify(webhookConfig),+ }+}++func newWebhookHTTPClient(webhookConfig *chatstorage.DeviceWebhookConfig) *http.Client {+ return &http.Client{+ Timeout: 10 * time.Second,+ Transport: &http.Transport{+ TLSClientConfig: webhookTLSConfig(webhookConfig),+ },+ }+}diff --git a/src/infrastructure/whatsapp/webhook_test.go b/src/infrastructure/whatsapp/webhook_test.goindex 5eeda013..ef332ed3 100644--- a/src/infrastructure/whatsapp/webhook_test.go+++ b/src/infrastructure/whatsapp/webhook_test.go@@ -7,6 +7,10 @@ import ("net/http/httptest""sync""testing"+ "time"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage")type capturedRequest struct {@@ -96,3 +100,67 @@ func TestSubmitWebhookRetryKeepsFullBody(t *testing.T) {t.Errorf("retry Content-Length = %d, want %d", reqs[1].contentLength, len(reqs[1].body))}}++func TestWebhookTLSDeviceVerifyOverridesGlobalBypass(t *testing.T) {+ // Mutates the process-wide webhook TLS default. This package does not run+ // tests in parallel; restore the previous value before returning.+ prev := config.WhatsappWebhookInsecureSkipVerify+ t.Cleanup(func() { config.WhatsappWebhookInsecureSkipVerify = prev })++ config.WhatsappWebhookInsecureSkipVerify = true+ // WebhookInsecureSkipVerify is a bool and cannot encode "unset". false is+ // the stored "verify certificates" value and must win over the global bypass.+ deviceVerify := &chatstorage.DeviceWebhookConfig{WebhookInsecureSkipVerify: false}+ if webhookInsecureSkipVerify(t, newWebhookHTTPClient(deviceVerify)) {+ t.Fatal("device verify=true yielded InsecureSkipVerify true while the global bypass was enabled")+ }++ config.WhatsappWebhookInsecureSkipVerify = true+ if !webhookInsecureSkipVerify(t, newWebhookHTTPClient(nil)) {+ t.Fatal("unset device config did not keep the global bypass")+ }+ config.WhatsappWebhookInsecureSkipVerify = false+ if webhookInsecureSkipVerify(t, newWebhookHTTPClient(nil)) {+ t.Fatal("unset device config did not keep global certificate verification")+ }++ deviceSkip := &chatstorage.DeviceWebhookConfig{WebhookInsecureSkipVerify: true}+ config.WhatsappWebhookInsecureSkipVerify = false+ if !webhookInsecureSkipVerify(t, newWebhookHTTPClient(deviceSkip)) {+ t.Fatal("explicit device skip=true was replaced by the global verify setting")+ }+}++func TestWebhookTLSDeviceVerifyRejectsUntrustedServer(t *testing.T) {+ prev := config.WhatsappWebhookInsecureSkipVerify+ t.Cleanup(func() { config.WhatsappWebhookInsecureSkipVerify = prev })+ config.WhatsappWebhookInsecureSkipVerify = true++ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ payload := map[string]any{"event": "message", "body": "tls"}+ deviceVerify := &chatstorage.DeviceWebhookConfig{WebhookInsecureSkipVerify: false}+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ if err := submitWebhook(ctx, payload, srv.URL, deviceVerify); err == nil {+ t.Fatal("device verify=true accepted an untrusted certificate while the global bypass was enabled")+ }++ ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)+ defer cancel()+ if err := submitWebhook(ctx, payload, srv.URL, nil); err != nil {+ t.Fatalf("unset device config did not keep the global bypass: %v", err)+ }+}++func webhookInsecureSkipVerify(t *testing.T, client *http.Client) bool {+ t.Helper()+ transport, ok := client.Transport.(*http.Transport)+ if !ok || transport.TLSClientConfig == nil {+ t.Fatal("webhook client is missing a TLS config")+ }+ return transport.TLSClientConfig.InsecureSkipVerify+}diff --git a/src/ui/mcp/oauth/store.go b/src/ui/mcp/oauth/store.goindex d2687e7c..9f0759a8 100644--- a/src/ui/mcp/oauth/store.go+++ b/src/ui/mcp/oauth/store.go@@ -13,6 +13,7 @@ import ("fmt""time"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp""github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/sqlite")@@ -76,6 +77,9 @@ CREATE INDEX IF NOT EXISTS idx_oauth_tokens_client_id ON oauth_tokens(client_id)`func openStore(uri string) (*store, error) {+ if err := whatsapp.SecureSQLiteFile(uri); err != nil {+ return nil, fmt.Errorf("prepare oauth storage: %w", err)+ }db, err := sql.Open(sqlite.DriverName, sqlite.FormatChatStorageURI(uri, true, true))if err != nil {return nil, fmt.Errorf("open oauth storage: %w", err)