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: redact secrets and control characters in logs (#926)

Aldino Kemal670be26b563c
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 4275ea65..27f3e2f9 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -86,7 +86,8 @@ func init() {
// initEnvConfig loads configuration from environment variables
func initEnvConfig() {
- fmt.Println(viper.AllSettings())
+ // Key names stay visible; secret values and URL userinfo are masked.
+ fmt.Println(utils.RedactSettings(viper.AllSettings()))
// Application settings
if envPort := viper.GetString("app_port"); envPort != "" {
config.AppPort = envPort
diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.go
index 99a8d5e9..29b0c27b 100644
--- a/src/infrastructure/whatsapp/device_manager.go
+++ b/src/infrastructure/whatsapp/device_manager.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "net/url"
"slices"
"strings"
"sync"
@@ -13,6 +14,7 @@ import (
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
fiberUtils "github.com/gofiber/utils/v2"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
@@ -836,7 +838,12 @@ func (m *DeviceManager) EnsureClient(ctx context.Context, deviceID string) (*Dev
client := whatsmeow.NewClient(storeDevice, newFilteredLogger(baseLogger))
if proxyURL := config.WhatsappProxy; proxyURL != "" {
if err := client.SetProxyAddress(proxyURL); err != nil {
- baseLogger.Errorf("failed to apply WHATSAPP_PROXY=%q for device %s: %v", redactProxyURL(proxyURL), deviceID, err)
+ // url.Parse errors include the raw URL, so log only its scheme and host.
+ reason := err.Error()
+ if errors.As(err, new(*url.Error)) {
+ reason = utils.FormatProxyParseFailure(proxyURL)
+ }
+ baseLogger.Errorf("failed to apply WHATSAPP_PROXY for device %s: %s", deviceID, reason)
} else {
baseLogger.Infof("applied outbound proxy from WHATSAPP_PROXY for device %s", deviceID)
}
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index 4679bfda..8bc0dbec 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -5,6 +5,7 @@ import (
"fmt"
"strings"
"time"
+ "unicode"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
@@ -17,13 +18,14 @@ import (
)
func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo domainChatStorage.IChatStorageRepository, client *whatsmeow.Client) {
- // Log message metadata
+ // Log message metadata. Message ID, sender name, JID and body are escaped so
+ // a newline in sender-controlled fields cannot forge a second log line.
metaParts := buildMessageMetaParts(evt)
- log.Infof("Received message %s from %s (%s): %+v",
- evt.Info.ID,
- evt.Info.SourceString(),
- strings.Join(metaParts, ", "),
- evt.Message,
+ log.Infof("Received message %s from %s (%s): %s",
+ sanitizeLogText(evt.Info.ID),
+ sanitizeLogText(evt.Info.SourceString()),
+ sanitizeLogText(strings.Join(metaParts, ", ")),
+ logMessageBody{evt.Message},
)
// Materialize SecretEncryptedMessage{MESSAGE_EDIT} envelope (sent by recent
@@ -36,7 +38,7 @@ func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo dom
if isReactionMessage(evt) {
if err := chatStorageRepo.CreateReaction(ctx, evt); err != nil {
- log.Errorf("Failed to store incoming reaction %s: %v", evt.Info.ID, err)
+ log.Errorf("Failed to store incoming reaction %s: %v", sanitizeLogText(evt.Info.ID), err)
}
handleWebhookForward(ctx, evt, client, pollPayload)
@@ -45,7 +47,7 @@ func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo dom
if err := chatStorageRepo.CreateMessage(ctx, evt); err != nil {
// Log storage errors to avoid silent failures that could lead to data loss
- log.Errorf("Failed to store incoming message %s: %v", evt.Info.ID, err)
+ log.Errorf("Failed to store incoming message %s: %v", sanitizeLogText(evt.Info.ID), err)
}
// Handle image message if present
@@ -63,7 +65,7 @@ func handleMessage(ctx context.Context, evt *events.Message, chatStorageRepo dom
func buildMessageMetaParts(evt *events.Message) []string {
metaParts := []string{
- fmt.Sprintf("pushname: %s", evt.Info.PushName),
+ fmt.Sprintf("pushname: %s", sanitizeLogText(evt.Info.PushName)),
fmt.Sprintf("timestamp: %s", evt.Info.Timestamp),
}
if evt.Info.Type != "" {
@@ -78,6 +80,47 @@ func buildMessageMetaParts(evt *events.Message) []string {
return metaParts
}
+// sanitizeLogText escapes control characters (C0, DEL, C1) and the Unicode
+// line and paragraph separators so one log record stays one line.
+func sanitizeLogText(s string) string {
+ if !strings.ContainsFunc(s, isLogControl) {
+ return s
+ }
+ var b strings.Builder
+ b.Grow(len(s) + 8)
+ for _, r := range s {
+ switch r {
+ case '\n':
+ b.WriteString(`\n`)
+ case '\r':
+ b.WriteString(`\r`)
+ case '\t':
+ b.WriteString(`\t`)
+ default:
+ if r < 0x20 || r == 0x7f {
+ fmt.Fprintf(&b, `\x%02x`, r)
+ } else if isLogControl(r) {
+ fmt.Fprintf(&b, `\u%04x`, r)
+ } else {
+ b.WriteRune(r)
+ }
+ }
+ }
+ return b.String()
+}
+
+func isLogControl(r rune) bool {
+ return unicode.IsControl(r) || r == '\u2028' || r == '\u2029'
+}
+
+// logMessageBody formats a message only when the log level prints it. The
+// protobuf text format escapes control characters but keeps U+2028/U+2029.
+type logMessageBody struct{ msg *waE2E.Message }
+
+func (b logMessageBody) String() string {
+ return sanitizeLogText(fmt.Sprintf("%+v", b.msg))
+}
+
func shouldIgnoreImageDownload(autoDownloadMedia, ignoreStatusMedia bool, chatJID types.JID) bool {
if !autoDownloadMedia {
return true
@@ -126,9 +169,9 @@ func handleAutoMarkRead(ctx context.Context, evt *events.Message, client *whatsm
sender := evt.Info.Sender
if err := client.MarkRead(ctx, messageIDs, timestamp, chat, sender); err != nil {
- log.Warnf("Failed to mark message %s as read: %v", evt.Info.ID, err)
+ log.Warnf("Failed to mark message %s as read: %v", sanitizeLogText(evt.Info.ID), err)
} else {
- log.Debugf("Marked message %s as read", evt.Info.ID)
+ log.Debugf("Marked message %s as read", sanitizeLogText(evt.Info.ID))
}
}
@@ -153,7 +196,7 @@ func materializeSecretEditMessage(ctx context.Context, evt *events.Message, clie
if k := sem.GetTargetMessageKey(); k != nil {
targetID = k.GetID()
}
- log.Warnf("Failed to decrypt SecretEncryptedMessage(MESSAGE_EDIT) for %s (target=%s): %v", evt.Info.ID, targetID, err)
+ log.Warnf("Failed to decrypt SecretEncryptedMessage(MESSAGE_EDIT) for %s (target=%s): %v", sanitizeLogText(evt.Info.ID), sanitizeLogText(targetID), err)
return evt
}
if decrypted == nil {
diff --git a/src/infrastructure/whatsapp/event_message_handler_test.go b/src/infrastructure/whatsapp/event_message_handler_test.go
index 9c18dbe4..2ef0d461 100644
--- a/src/infrastructure/whatsapp/event_message_handler_test.go
+++ b/src/infrastructure/whatsapp/event_message_handler_test.go
@@ -2,6 +2,8 @@ package whatsapp
import (
"context"
+ "fmt"
+ "strings"
"sync"
"testing"
"time"
@@ -290,6 +292,96 @@ func reactionEventForTest(eventID, targetID, emoji string) *events.Message {
}
}
+type captureLogger struct {
+ mu sync.Mutex
+ lines []string
+}
+
+func (l *captureLogger) Infof(msg string, args ...any) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ l.lines = append(l.lines, fmt.Sprintf(msg, args...))
+}
+
+func (l *captureLogger) Errorf(msg string, args ...any) { l.Infof(msg, args...) }
+func (l *captureLogger) Warnf(msg string, args ...any) { l.Infof(msg, args...) }
+func (l *captureLogger) Debugf(string, ...any) {}
+func (l *captureLogger) Sub(string) waLog.Logger { return l }
+
+func TestHandleMessageLogDoesNotSplitOnSenderNewline(t *testing.T) {
+ originalLog := log
+ originalAutoReply := config.WhatsappAutoReplyMessage
+ originalAutoMarkRead := config.WhatsappAutoMarkRead
+ originalWebhook := append([]string(nil), config.WhatsappWebhook...)
+ originalChatwoot := config.ChatwootEnabled
+ t.Cleanup(func() {
+ log = originalLog
+ config.WhatsappAutoReplyMessage = originalAutoReply
+ config.WhatsappAutoMarkRead = originalAutoMarkRead
+ config.WhatsappWebhook = originalWebhook
+ config.ChatwootEnabled = originalChatwoot
+ })
+
+ capture := &captureLogger{}
+ log = capture
+ config.WhatsappAutoReplyMessage = ""
+ config.WhatsappAutoMarkRead = false
+ config.WhatsappWebhook = nil
+ config.ChatwootEnabled = false
+
+ const forged = "INFO forged-entry"
+ pushName := "Alice\r\n" + forged + "\x1b[31m\u0085\u009b\u2028\u2029 …"
+ // A status broadcast chat returns from handleWebhookForward before it
+ // spawns the forwarding goroutine, which would race with t.Cleanup.
+ evt := textEventForTest("log-newline-1\nINFO forged-id", types.StatusBroadcastJID)
+ evt.Info.PushName = pushName
+ evt.Info.Sender = types.NewJID("62811\n999", types.DefaultUserServer)
+ // The protobuf text format keeps U+2028 and U+2029 in the body unescaped.
+ evt.Message.Conversation = protoString("body\u2028INFO forged-body\u2029")
+
+ handleMessage(context.Background(), evt, &messageHandlerRepoSpy{}, nil)
+
+ capture.mu.Lock()
+ lines := append([]string(nil), capture.lines...)
+ capture.mu.Unlock()
+
+ var received []string
+ for _, line := range lines {
+ if strings.Contains(line, "Received message") {
+ received = append(received, line)
+ }
+ }
+ if len(received) != 1 {
+ t.Fatalf("expected one received-message record, got %d: %#v", len(received), lines)
+ }
+ record := received[0]
+ // A stdout logger writes the formatted record plus one trailing newline.
+ // A CR/LF inside the sender name would show up as an extra line here.
+ written := record + "\n"
+ writtenLines := strings.Split(strings.TrimSuffix(written, "\n"), "\n")
+ if len(writtenLines) != 1 {
+ t.Fatalf("sender name forged an extra log line: %#v", writtenLines)
+ }
+ if strings.ContainsAny(record, "\r\n\u0085\u009b\u2028\u2029") || strings.Contains(record, "\x1b") {
+ t.Fatalf("log record still contains control characters: %q", record)
+ }
+ if !strings.Contains(record, "Alice") || !strings.Contains(record, forged) || !strings.Contains(record, `\x1b[31m\u0085\u009b\u2028\u2029 …`) {
+ t.Fatalf("sender name missing from the same log line: %q", record)
+ }
+ if !strings.Contains(record, `log-newline-1\nINFO forged-id`) {
+ t.Fatalf("message id was not escaped onto the same line: %q", record)
+ }
+ if !strings.Contains(record, `62811\n999`) {
+ t.Fatalf("sender jid was not escaped onto the same line: %q", record)
+ }
+ if !strings.Contains(record, `body\u2028INFO forged-body\u2029`) {
+ t.Fatalf("message body was not escaped onto the same line: %q", record)
+ }
+ if evt.Info.PushName != pushName {
+ t.Fatalf("push name was mutated: %q", evt.Info.PushName)
+ }
+}
+
func TestShouldIgnoreImageDownload(t *testing.T) {
tests := []struct {
name string
diff --git a/src/infrastructure/whatsapp/init.go b/src/infrastructure/whatsapp/init.go
index e1a1b5dc..7ee710fd 100644
--- a/src/infrastructure/whatsapp/init.go
+++ b/src/infrastructure/whatsapp/init.go
@@ -2,12 +2,15 @@ package whatsapp
import (
"context"
+ "errors"
"fmt"
+ "net/url"
"sync"
"time"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/store"
@@ -107,7 +110,12 @@ func InitWaCLI(ctx context.Context, storeContainer, keysStoreContainer *sqlstore
client := whatsmeow.NewClient(device, newFilteredLogger(baseLogger))
if proxyURL := config.WhatsappProxy; proxyURL != "" {
if err := client.SetProxyAddress(proxyURL); err != nil {
- baseLogger.Errorf("failed to apply WHATSAPP_PROXY=%q: %v", redactProxyURL(proxyURL), err)
+ // url.Parse errors include the raw URL, so log only its scheme and host.
+ reason := err.Error()
+ if errors.As(err, new(*url.Error)) {
+ reason = utils.FormatProxyParseFailure(proxyURL)
+ }
+ baseLogger.Errorf("failed to apply WHATSAPP_PROXY=%q: %s", redactProxyURL(proxyURL), reason)
} else {
baseLogger.Infof("applied outbound proxy from WHATSAPP_PROXY")
}
diff --git a/src/infrastructure/whatsapp/proxy.go b/src/infrastructure/whatsapp/proxy.go
index 40a46d78..ea631dbf 100644
--- a/src/infrastructure/whatsapp/proxy.go
+++ b/src/infrastructure/whatsapp/proxy.go
@@ -1,14 +1,25 @@
package whatsapp
-import "net/url"
+import (
+ "net/url"
+ "strings"
+)
// redactProxyURL returns a form of the proxy URL safe for logging: the
-// password (and any unparseable URL entirely) is masked so credentials from
-// WHATSAPP_PROXY never reach the logs.
+// userinfo (and any unparseable URL entirely) is masked so credentials from
+// WHATSAPP_PROXY never reach the logs. A parse without a host counts as
+// unparseable: "user:pass@host:1080" reads as scheme "user" with the
+// credentials left in Opaque, which Redacted would print unchanged.
func redactProxyURL(raw string) string {
u, err := url.Parse(raw)
- if err != nil {
+ if err != nil || u.Host == "" {
return "<unparseable-proxy-url>"
}
+ if u.User != nil {
+ // Redacted keeps the username, which can be an access token, and
+ // url.User("***") would print escaped, so write the mask as text.
+ u.User = nil
+ return strings.Replace(u.String(), "//", "//***@", 1)
+ }
return u.Redacted()
}
diff --git a/src/infrastructure/whatsapp/proxy_test.go b/src/infrastructure/whatsapp/proxy_test.go
new file mode 100644
index 00000000..e5d61680
--- /dev/null
+++ b/src/infrastructure/whatsapp/proxy_test.go
@@ -0,0 +1,15 @@
+package whatsapp
+
+import "testing"
+
+func TestRedactProxyURLMasksUserinfo(t *testing.T) {
+ for raw, want := range map[string]string{
+ "ftp://[email protected]:1080": "ftp://***@proxy.internal:1080",
+ "socks5://user:[email protected]:1080": "socks5://***@proxy.internal:1080",
+ "http://proxy.internal:8080": "http://proxy.internal:8080",
+ } {
+ if got := redactProxyURL(raw); got != want {
+ t.Fatalf("redactProxyURL(%q) = %q, want %q", raw, got, want)
+ }
+ }
+}
diff --git a/src/pkg/utils/logredact.go b/src/pkg/utils/logredact.go
new file mode 100644
index 00000000..6eb97e68
--- /dev/null
+++ b/src/pkg/utils/logredact.go
@@ -0,0 +1,368 @@
+package utils
+
+import (
+ "fmt"
+ "net/url"
+ "regexp"
+ "strings"
+ "unicode"
+)
+
+const redactedSecret = "***"
+
+// sensitiveKeySubstrings mark a setting as secret from its name alone.
+// "webhook" is intentionally absent: destination URLs are useful at startup,
+// and only webhook signing secrets (keys that also match "secret" or "token")
+// are fully redacted. "proxy" is handled separately because a proxy without
+// userinfo is safe to print. "basic_auth" stands in for a bare "auth", which
+// would also hide the non-secret mcp_oauth_* flags and URLs.
+var sensitiveKeySubstrings = []string{
+ "password",
+ "passwd",
+ "secret",
+ "token",
+ "api_key",
+ "apikey",
+ "authorization",
+ "basic_auth",
+ "credential",
+ "private",
+}
+
+// urlScheme finds where each URL in a flat env value such as a comma-separated
+// webhook list starts.
+var urlScheme = regexp.MustCompile(`(?i)[a-z][a-z0-9+.-]*://`)
+
+// queryParamName matches a query separator and parameter name up to its '='.
+var queryParamName = regexp.MustCompile(`[?&]([^?&=#\s]*)=`)
+
+// secretQueryName matches a query parameter name that looks secret.
+var secretQueryName = regexp.MustCompile(`(?i)secret|token|password|passwd|key|sig|auth|credential`)
+
+// RedactSettings returns a deep copy of a Viper AllSettings map safe to print
+// at startup. Key names are preserved. Secret values become "***". Other
+// URL-like values keep their host and path, with userinfo and secret query
+// values replaced by "***".
+func RedactSettings(settings map[string]any) map[string]any {
+ if settings == nil {
+ return nil
+ }
+ return redactMap("", settings)
+}
+
+func redactMap(prefix string, settings map[string]any) map[string]any {
+ out := make(map[string]any, len(settings))
+ for key, value := range settings {
+ path := key
+ if prefix != "" {
+ path = prefix + "." + key
+ }
+ out[key] = redactSettingValue(path, value)
+ }
+ return out
+}
+
+func redactSettingValue(key string, value any) any {
+ // An empty secret stays empty so a missing setting is still visible.
+ if value != "" && isFullySensitiveKey(key) {
+ return redactedSecret
+ }
+ switch typed := value.(type) {
+ case map[string]any:
+ return redactMap(key, typed)
+ case string:
+ return redactStringSetting(key, typed)
+ case []string:
+ out := make([]string, len(typed))
+ for i, item := range typed {
+ out[i] = redactStringSetting(key, item)
+ }
+ return out
+ case []any:
+ out := make([]any, len(typed))
+ for i, item := range typed {
+ out[i] = redactSettingValue(key, item)
+ }
+ return out
+ default:
+ return value
+ }
+}
+
+func redactStringSetting(key, value string) string {
+ if isProxyKey(key) && proxyValueMayContainUserinfo(value) {
+ return redactedSecret
+ }
+ return redactURLSecretsInText(value)
+}
+
+func normalizeSettingKey(key string) string {
+ k := strings.ToLower(strings.TrimSpace(key))
+ k = strings.ReplaceAll(k, "-", "_")
+ k = strings.ReplaceAll(k, ".", "_")
+ k = strings.ReplaceAll(k, " ", "_")
+ return k
+}
+
+func isFullySensitiveKey(key string) bool {
+ k := normalizeSettingKey(key)
+ if k == "" {
+ return false
+ }
+ if isDatabaseDSNKey(k) {
+ return true
+ }
+ for _, sub := range sensitiveKeySubstrings {
+ if strings.Contains(k, sub) {
+ return true
+ }
+ }
+ return false
+}
+
+// isDatabaseDSNKey matches connection strings whose names do not contain the
+// generic secret substrings. These are the real DSN fields loaded from
+// settings (db_uri, db_keys_uri, chatwoot_import_db_uri) plus the same shape
+// of key nested under another prefix.
+func isDatabaseDSNKey(k string) bool {
+ switch k {
+ case "db_uri", "db_keys_uri", "chatwoot_import_db_uri", "mcp_oauth_db_uri":
+ return true
+ }
+ if strings.HasSuffix(k, "_db_uri") || strings.HasSuffix(k, "db_keys_uri") || strings.HasSuffix(k, "_dsn") {
+ return true
+ }
+ return false
+}
+
+func isProxyKey(key string) bool {
+ return strings.Contains(normalizeSettingKey(key), "proxy")
+}
+
+// proxyValueMayContainUserinfo reports whether a proxy value embeds
+// credentials or is too malformed to prove that it does not.
+func proxyValueMayContainUserinfo(value string) bool {
+ s := strings.TrimSpace(value)
+ if s == "" {
+ return false
+ }
+ // Without a host the parse proves nothing: "user:pass@host:1080" reads as
+ // scheme "user" with the credentials left in Opaque.
+ if u, err := url.Parse(s); err == nil && u.Host != "" {
+ return u.User != nil
+ }
+ return strings.Contains(s, "@")
+}
+
+func redactURLSecretsInText(s string) string {
+ if !strings.Contains(s, "://") {
+ return s
+ }
+ s = maskURLUserinfo(s)
+ return maskSecretQueryValues(s)
+}
+
+// maskSecretQueryValues masks the value of each query parameter whose name
+// looks secret as written or percent-decoded, keeping the rest of the text.
+// The value runs to the next '&', '#' or whitespace because commas are legal
+// in it, so a later URL in the same comma-separated list is masked with it.
+func maskSecretQueryValues(s string) string {
+ var b strings.Builder
+ prev := 0
+ for _, m := range queryParamName.FindAllStringSubmatchIndex(s, -1) {
+ if m[0] < prev {
+ continue // inside a value that is already masked
+ }
+ name := s[m[2]:m[3]]
+ decoded, _ := url.QueryUnescape(name)
+ if !secretQueryName.MatchString(name) && !secretQueryName.MatchString(decoded) {
+ continue
+ }
+ b.WriteString(s[prev:m[1]])
+ b.WriteString(redactedSecret)
+ prev = len(s)
+ if end := strings.IndexAny(s[m[1]:], "&#\t\n\f\r "); end >= 0 {
+ prev = m[1] + end
+ }
+ }
+ b.WriteString(s[prev:])
+ return b.String()
+}
+
+// maskURLUserinfo masks everything between "://" and the last '@' before the
+// next URL or whitespace. Userinfo may hold '/', '?', '#', ',' or quotes, so
+// the authority is not parsed; an '@' later in the path is masked too, which
+// only hides more. A later scheme starts the next URL right after a comma or
+// once whitespace has ended the current one; otherwise, as in a password
+// holding "https://", it stays part of the current URL.
+func maskURLUserinfo(s string) string {
+ var starts [][]int
+ for _, loc := range urlScheme.FindAllStringIndex(s, -1) {
+ if n := len(starts); n > 0 && s[loc[0]-1] != ',' &&
+ strings.IndexFunc(s[starts[n-1][1]:loc[0]], unicode.IsSpace) < 0 {
+ continue
+ }
+ starts = append(starts, loc)
+ }
+ var b strings.Builder
+ prev := 0
+ for i, loc := range starts {
+ end := len(s)
+ if i+1 < len(starts) {
+ end = starts[i+1][0]
+ }
+ segment := s[loc[1]:end]
+ if space := strings.IndexFunc(segment, unicode.IsSpace); space >= 0 {
+ segment = segment[:space]
+ }
+ if at := strings.LastIndexByte(segment, '@'); at >= 0 {
+ b.WriteString(s[prev:loc[1]])
+ b.WriteString(redactedSecret)
+ prev = loc[1] + at
+ }
+ }
+ b.WriteString(s[prev:])
+ return b.String()
+}
+
+// FormatProxyParseFailure describes a proxy URL for logs when url.Parse (or
+// SetProxyAddress) fails. url.Error.Error includes the original URL, so
+// callers must log this string instead of the parser error.
+func FormatProxyParseFailure(raw string) string {
+ scheme, host := safeProxySchemeHost(raw)
+ msg := "parse failure"
+ switch {
+ case scheme != "" && host != "":
+ msg = fmt.Sprintf("scheme=%s host=%s: parse failure", scheme, host)
+ case scheme != "":
+ msg = fmt.Sprintf("scheme=%s: parse failure", scheme)
+ case host != "":
+ msg = fmt.Sprintf("host=%s: parse failure", host)
+ }
+ if info := proxyUserinfo(raw); strings.Contains(info, ":") && strings.Contains(msg, info) {
+ return "parse failure"
+ }
+ return msg
+}
+
+func safeProxySchemeHost(raw string) (scheme, host string) {
+ s := strings.TrimSpace(raw)
+ s = strings.Trim(s, `"'`)
+ if u, err := url.Parse(s); err == nil && validProxyScheme(u.Scheme) && safeProxyHost(u.Host) {
+ return u.Scheme, u.Host
+ }
+ return manualProxySchemeHost(s)
+}
+
+func manualProxySchemeHost(s string) (scheme, host string) {
+ rest := s
+ if i := strings.Index(s, "://"); i >= 0 {
+ candidate := s[:i]
+ if !validProxyScheme(candidate) {
+ return "", ""
+ }
+ scheme = candidate
+ rest = s[i+3:]
+ }
+ if at := strings.LastIndex(rest, "@"); at >= 0 {
+ rest = rest[at+1:]
+ } else if strings.Contains(s, "://") {
+ // No userinfo separator. A failed parse of "scheme://user:pass" would
+ // otherwise treat the credentials as a host:port pair.
+ if !safeProxyHost(cutHostToken(rest)) {
+ return scheme, ""
+ }
+ }
+ host = cutHostToken(rest)
+ if !safeProxyHost(host) {
+ host = ""
+ }
+ return scheme, host
+}
+
+func cutHostToken(rest string) string {
+ if i := strings.IndexAny(rest, "/?# \t\r\n\"'"); i >= 0 {
+ rest = rest[:i]
+ }
+ // Drop a port that is not all digits: it may be a secret. A ':' before the
+ // last ']' belongs to an IPv6 literal.
+ if i := strings.LastIndexByte(rest, ':'); i > strings.LastIndexByte(rest, ']') && !isAllDigits(rest[i+1:]) {
+ rest = rest[:i]
+ }
+ return rest
+}
+
+func proxyUserinfo(raw string) string {
+ s := strings.TrimSpace(raw)
+ s = strings.Trim(s, `"'`)
+ rest := s
+ if i := strings.Index(s, "://"); i >= 0 {
+ rest = s[i+3:]
+ }
+ at := strings.LastIndex(rest, "@")
+ if at <= 0 {
+ return ""
+ }
+ return rest[:at]
+}
+
+func validProxyScheme(scheme string) bool {
+ if scheme == "" || len(scheme) > 32 {
+ return false
+ }
+ for i := 0; i < len(scheme); i++ {
+ c := scheme[i]
+ switch {
+ case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z':
+ case i > 0 && (c >= '0' && c <= '9' || c == '+' || c == '-' || c == '.'):
+ default:
+ return false
+ }
+ }
+ return true
+}
+
+func safeProxyHost(host string) bool {
+ if host == "" || len(host) > 300 || strings.ContainsAny(host, "@/?# \t\r\n\\") {
+ return false
+ }
+ for i := 0; i < len(host); i++ {
+ if host[i] < 0x21 || host[i] > 0x7e {
+ return false
+ }
+ }
+ if strings.HasPrefix(host, "[") {
+ end := strings.Index(host, "]")
+ if end < 2 {
+ return false
+ }
+ if end == len(host)-1 {
+ return true
+ }
+ return host[end+1] == ':' && isAllDigits(host[end+2:])
+ }
+ if strings.Count(host, ":") > 1 {
+ return false
+ }
+ name, port, hasPort := strings.Cut(host, ":")
+ if name == "" || (hasPort && !isAllDigits(port)) {
+ return false
+ }
+ plausibleName := name == "localhost" || strings.Contains(name, ".") || isAllDigits(name)
+ if !plausibleName && !hasPort {
+ return false
+ }
+ return true
+}
+
+func isAllDigits(s string) bool {
+ if s == "" {
+ return false
+ }
+ for i := 0; i < len(s); i++ {
+ if s[i] < '0' || s[i] > '9' {
+ return false
+ }
+ }
+ return true
+}
diff --git a/src/pkg/utils/logredact_test.go b/src/pkg/utils/logredact_test.go
new file mode 100644
index 00000000..ccc67344
--- /dev/null
+++ b/src/pkg/utils/logredact_test.go
@@ -0,0 +1,299 @@
+package utils
+
+import (
+ "fmt"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestRedactSettingsHidesSecretsAndKeepsPortHost(t *testing.T) {
+ in := map[string]any{
+ "app_port": "3000",
+ "app_host": "0.0.0.0",
+ "app_debug": false,
+ "app_basic_auth": "user1:pass1,user2:pass2",
+ "app_ui_github_token": "ghp_supersecret",
+ "app_ui_asset_sha256": "abc123pin",
+ "app_trusted_proxies": "10.0.0.0/8",
+ "db_uri": "postgresql://dbuser:[email protected]:5432/whatsapp",
+ "db_keys_uri": "postgresql://keyuser:[email protected]:5432/keys",
+ "whatsapp_webhook": "https://hooks.example/a,https://user:[email protected]/b",
+ "whatsapp_webhook_secret": "super-secret-key",
+ "whatsapp_webhook_events": "message,message.ack",
+ "whatsapp_account_validation": "true",
+ "whatsapp_proxy": "socks5://user:[email protected]:1080",
+ "chatwoot_url": "https://app.chatwoot.com",
+ "chatwoot_api_token": "cw_token_value",
+ "chatwoot_import_db_uri": "postgresql://cw:[email protected]:5432/chatwoot",
+ "chatwoot_webhook_url": "https://public.example/chatwoot/webhook?secret=cw-wh-secret",
+ "chatwoot_webhook_secret": "cw-wh-secret",
+ "chatwoot_webhook_signature_tolerance": "5m",
+ "API_KEY": "plain-api-key",
+ "service_password": "hunter2",
+ }
+ originalBasic := in["app_basic_auth"]
+ originalDSN := in["db_uri"]
+
+ got := RedactSettings(in)
+ printed := fmt.Sprint(got)
+
+ if in["app_basic_auth"] != originalBasic || in["db_uri"] != originalDSN {
+ t.Fatal("RedactSettings mutated the input map")
+ }
+ if got["app_port"] != "3000" || got["app_host"] != "0.0.0.0" {
+ t.Fatalf("ordinary port/host were hidden: port=%v host=%v", got["app_port"], got["app_host"])
+ }
+ if !strings.Contains(printed, "app_port:3000") || !strings.Contains(printed, "app_host:0.0.0.0") {
+ t.Fatalf("startup print hid port/host: %s", printed)
+ }
+ if got["app_debug"] != false {
+ t.Fatalf("non-secret bool changed: %#v", got["app_debug"])
+ }
+ if got["app_ui_asset_sha256"] != "abc123pin" {
+ t.Fatalf("asset pin should stay visible, got %#v", got["app_ui_asset_sha256"])
+ }
+ if got["app_trusted_proxies"] != "10.0.0.0/8" {
+ t.Fatalf("trusted proxy list should stay visible, got %#v", got["app_trusted_proxies"])
+ }
+ if got["whatsapp_account_validation"] != "true" {
+ t.Fatalf("account validation should stay visible, got %#v", got["whatsapp_account_validation"])
+ }
+ if got["whatsapp_webhook_events"] != "message,message.ack" {
+ t.Fatalf("webhook event list should stay visible, got %#v", got["whatsapp_webhook_events"])
+ }
+ if got["chatwoot_webhook_signature_tolerance"] != "5m" {
+ t.Fatalf("signature tolerance should stay visible, got %#v", got["chatwoot_webhook_signature_tolerance"])
+ }
+ if got["chatwoot_url"] != "https://app.chatwoot.com" {
+ t.Fatalf("chatwoot URL should stay visible, got %#v", got["chatwoot_url"])
+ }
+ if got["chatwoot_webhook_url"] != "https://public.example/chatwoot/webhook?secret=***" {
+ t.Fatalf("chatwoot webhook URL should stay visible with its secret masked, got %#v", got["chatwoot_webhook_url"])
+ }
+
+ for _, key := range []string{
+ "app_basic_auth",
+ "app_ui_github_token",
+ "db_uri",
+ "db_keys_uri",
+ "whatsapp_webhook_secret",
+ "whatsapp_proxy",
+ "chatwoot_api_token",
+ "chatwoot_import_db_uri",
+ "chatwoot_webhook_secret",
+ "API_KEY",
+ "service_password",
+ } {
+ if got[key] != redactedSecret {
+ t.Fatalf("key %s = %#v, want %s", key, got[key], redactedSecret)
+ }
+ }
+
+ webhook, _ := got["whatsapp_webhook"].(string)
+ if webhook == redactedSecret {
+ t.Fatal("non-secret webhook destinations were fully redacted")
+ }
+ if strings.Contains(webhook, "user:pass@") || strings.Contains(webhook, "pass@") {
+ t.Fatalf("webhook userinfo leaked: %s", webhook)
+ }
+ if !strings.Contains(webhook, "https://hooks.example/a") || !strings.Contains(webhook, "https://***@hooks.example/b") {
+ t.Fatalf("webhook URL redaction = %s", webhook)
+ }
+
+ for _, leaked := range []string{
+ "pass1", "pass2", "ghp_supersecret", "dbpass", "keypass", "super-secret-key",
+ "user:pass@", "cw_token_value", "cwpass", "cw-wh-secret", "plain-api-key", "hunter2",
+ } {
+ if strings.Contains(printed, leaked) {
+ t.Fatalf("startup print leaked %q: %s", leaked, printed)
+ }
+ }
+}
+
+func TestRedactSettingsProxyWithoutUserinfoStaysVisible(t *testing.T) {
+ got := RedactSettings(map[string]any{
+ "whatsapp_proxy": "http://127.0.0.1:8080",
+ "app_port": "3000",
+ })
+ if got["whatsapp_proxy"] != "http://127.0.0.1:8080" {
+ t.Fatalf("proxy without userinfo = %#v", got["whatsapp_proxy"])
+ }
+ if got["app_port"] != "3000" {
+ t.Fatalf("port = %#v", got["app_port"])
+ }
+}
+
+func TestRedactSettingsUnparseableProxyWithUserinfo(t *testing.T) {
+ raw := "socks5://user:[email protected]:not-a-port"
+ got := RedactSettings(map[string]any{"whatsapp_proxy": raw})
+ printed := fmt.Sprint(got)
+ if got["whatsapp_proxy"] != redactedSecret {
+ t.Fatalf("malformed proxy = %#v", got["whatsapp_proxy"])
+ }
+ if strings.Contains(printed, "user:pass@") {
+ t.Fatalf("malformed proxy leaked credentials: %s", printed)
+ }
+}
+
+func TestRedactSettingsSchemelessProxyWithUserinfo(t *testing.T) {
+ // url.Parse reads "user" as the scheme and leaves the credentials in Opaque.
+ got := RedactSettings(map[string]any{"whatsapp_proxy": "user:[email protected]:1080"})
+ if got["whatsapp_proxy"] != redactedSecret {
+ t.Fatalf("schemeless proxy = %#v, want %s", got["whatsapp_proxy"], redactedSecret)
+ }
+}
+
+func TestRedactSettingsUserinfoWithQuoteOrComma(t *testing.T) {
+ got := RedactSettings(map[string]any{
+ "whatsapp_webhook": "https://user:p'[email protected]/b",
+ "chatwoot_url": "https://agent:pa,[email protected]",
+ "cache_url": "redis://:p@ss,w0rd@cache:6379",
+ "slash_url": "https://user:pa/[email protected]/b",
+ "query_url": "https://user:[email protected]",
+ "fragment_url": "https://user:pa#[email protected]",
+ "list_url": "https://hooks.example/a,https://u:p/[email protected]/b c",
+ "scheme_url": "https://user:pahttps://[email protected]",
+ "spaced_url": "https://a x=https://u:p@b",
+ "quoted_url": `https://a "https://u:p@b"`,
+ })
+ for key, want := range map[string]string{
+ "whatsapp_webhook": "https://***@hooks.example/b",
+ "chatwoot_url": "https://***@chat.example",
+ "cache_url": "redis://***@cache:6379",
+ "slash_url": "https://***@hooks.example/b",
+ "query_url": "https://***@hooks.example",
+ "fragment_url": "https://***@hooks.example",
+ "list_url": "https://hooks.example/a,https://***@hooks.example/b c",
+ "scheme_url": "https://***@hooks.example",
+ "spaced_url": "https://a x=https://***@b",
+ "quoted_url": `https://a "https://***@b"`,
+ } {
+ if got[key] != want {
+ t.Fatalf("%s = %#v, want %q", key, got[key], want)
+ }
+ }
+}
+
+func TestRedactSettingsMasksSecretQueryValues(t *testing.T) {
+ got := RedactSettings(map[string]any{
+ "whatsapp_webhook": "https://hooks.example/in?source=gowa&token=wh,tok#frag",
+ "chatwoot_url": "https://chat.example/?api_key=k1",
+ })
+ if want := "https://hooks.example/in?source=gowa&token=***#frag"; got["whatsapp_webhook"] != want {
+ t.Fatalf("whatsapp_webhook = %#v, want %q", got["whatsapp_webhook"], want)
+ }
+ if want := "https://chat.example/?api_key=***"; got["chatwoot_url"] != want {
+ t.Fatalf("chatwoot_url = %#v, want %q", got["chatwoot_url"], want)
+ }
+}
+
+func TestRedactSettingsMasksPercentEncodedSecretQueryNames(t *testing.T) {
+ got := RedactSettings(map[string]any{
+ "whatsapp_webhook": "https://hooks.example/?to%6Ben=LIVE_TOKEN",
+ "chatwoot_url": "https://chat.example/?a%20b=1,https://hooks.example/in?p%61ssword=LIVE&x=1",
+ "bad_escape_url": "https://hooks.example/?token%zz=LIVE&ok=%zz",
+ })
+ for key, want := range map[string]string{
+ "whatsapp_webhook": "https://hooks.example/?to%6Ben=***",
+ "chatwoot_url": "https://chat.example/?a%20b=1,https://hooks.example/in?p%61ssword=***&x=1",
+ "bad_escape_url": "https://hooks.example/?token%zz=***&ok=%zz",
+ } {
+ if got[key] != want {
+ t.Fatalf("%s = %#v, want %q", key, got[key], want)
+ }
+ }
+}
+
+func TestRedactSettingsKeepsOAuthSettingsAndEmptySecrets(t *testing.T) {
+ got := RedactSettings(map[string]any{
+ "mcp_oauth_enabled": true,
+ "mcp_oauth_issuer_url": "https://gowa.example",
+ "mcp_oauth_resource_url": "https://gowa.example/mcp",
+ "mcp_oauth_db_uri": "postgres://oauth:[email protected]:5432/oauth",
+ "chatwoot_api_token": "",
+ })
+ if got["mcp_oauth_enabled"] != true {
+ t.Fatalf("mcp_oauth_enabled = %#v, want true", got["mcp_oauth_enabled"])
+ }
+ if got["mcp_oauth_issuer_url"] != "https://gowa.example" || got["mcp_oauth_resource_url"] != "https://gowa.example/mcp" {
+ t.Fatalf("OAuth URLs were hidden: issuer=%#v resource=%#v", got["mcp_oauth_issuer_url"], got["mcp_oauth_resource_url"])
+ }
+ if got["mcp_oauth_db_uri"] != redactedSecret {
+ t.Fatalf("mcp_oauth_db_uri = %#v, want %s", got["mcp_oauth_db_uri"], redactedSecret)
+ }
+ if got["chatwoot_api_token"] != "" {
+ t.Fatalf("empty secret = %#v, want empty", got["chatwoot_api_token"])
+ }
+}
+
+func TestRedactSettingsURLUserinfoOutsideSecretKeys(t *testing.T) {
+ got := RedactSettings(map[string]any{
+ "chatwoot_url": "https://agent:[email protected]",
+ })
+ gotURL, _ := got["chatwoot_url"].(string)
+ if strings.Contains(gotURL, "s3cret") || strings.Contains(gotURL, "agent:s3cret") {
+ t.Fatalf("userinfo leaked: %s", gotURL)
+ }
+ if !strings.Contains(gotURL, "https://***@chat.example") {
+ t.Fatalf("redacted URL = %s", gotURL)
+ }
+}
+
+func TestFormatProxyParseFailureOmitsUserinfo(t *testing.T) {
+ raw := "socks5://user:[email protected]:not-a-port"
+ _, err := url.Parse(raw)
+ if err == nil {
+ t.Fatal("expected url.Parse to fail")
+ }
+ if !strings.Contains(err.Error(), "user:pass@") {
+ t.Fatalf("precondition: parser error should echo the URL, got %q", err.Error())
+ }
+
+ logged := fmt.Sprintf("failed to apply WHATSAPP_PROXY for device %s: %s", "device-1", FormatProxyParseFailure(raw))
+ if strings.Contains(logged, "user:pass@") || strings.Contains(logged, err.Error()) {
+ t.Fatalf("proxy parse log leaked credentials: %q", logged)
+ }
+ if !strings.Contains(logged, "scheme=socks5") || !strings.Contains(logged, "host=proxy.internal") || !strings.Contains(logged, "parse failure") {
+ t.Fatalf("expected scheme, host, and parse failure, got %q", logged)
+ }
+}
+
+func TestFormatProxyParseFailureKeepsHostWithoutEchoingError(t *testing.T) {
+ raw := "ftp://user:[email protected]:21"
+ _, err := url.Parse(raw)
+ if err != nil {
+ t.Fatalf("expected parse to succeed so the failure is the unsupported scheme, got %v", err)
+ }
+ logged := FormatProxyParseFailure(raw)
+ if strings.Contains(logged, "user:pass") {
+ t.Fatalf("logged userinfo: %q", logged)
+ }
+ if !strings.Contains(logged, "scheme=ftp") || !strings.Contains(logged, "host=proxy.internal:21") {
+ t.Fatalf("expected scheme and host, got %q", logged)
+ }
+}
+
+func TestFormatProxyParseFailureCredentialOnlyURL(t *testing.T) {
+ raw := "http://user:pass"
+ logged := FormatProxyParseFailure(raw)
+ if strings.Contains(logged, "user:pass") {
+ t.Fatalf("logged credentials: %q", logged)
+ }
+ if !strings.Contains(logged, "scheme=http") || !strings.Contains(logged, "parse failure") {
+ t.Fatalf("expected scheme and parse failure, got %q", logged)
+ }
+}
+
+func TestFormatProxyParseFailureDropsNonNumericPort(t *testing.T) {
+ for raw, want := range map[string]string{
+ "ftp://example.com:supersecret": "scheme=ftp host=example.com: parse failure",
+ "socks5://user:pass@[::1]:supersecret": "scheme=socks5 host=[::1]: parse failure",
+ "socks5://user:pass@[::1]:supersecret]:x": "scheme=socks5: parse failure",
+ "socks5://user:[email protected]:supersecret]:x": "scheme=socks5: parse failure",
+ } {
+ if got := FormatProxyParseFailure(raw); got != want {
+ t.Fatalf("FormatProxyParseFailure(%q) = %q, want %q", raw, got, want)
+ }
+ }
+}