Skip to content

Commit 3983b96

Browse files
committed
Added function and tests to redact password from URL
1 parent cd74be0 commit 3983b96

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

internal/connectionmanager/connection_manager.go

+9-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package connectionmanager
33
import (
44
"errors"
55
"fmt"
6+
"net/url"
67
"sync"
78
"time"
89

@@ -42,12 +43,19 @@ func dial(log logger.Logger, resolver Resolver, conf amqp.Config) (*amqp.Connect
4243
if err == nil {
4344
return conn, err
4445
}
45-
log.Warnf("failed to connect to amqp server %s: %v", url, err)
46+
47+
// Log masked url
48+
log.Warnf("failed to connect to amqp server %s: %v", maskPassword(url), err)
4649
errs = append(errs, err)
4750
}
4851
return nil, errors.Join(errs...)
4952
}
5053

54+
func maskPassword(urlToMask string) string {
55+
parsedUrl, _ := url.Parse(urlToMask)
56+
return parsedUrl.Redacted()
57+
}
58+
5159
// NewConnectionManager creates a new connection manager
5260
func NewConnectionManager(resolver Resolver, conf amqp.Config, log logger.Logger, reconnectInterval time.Duration) (*ConnectionManager, error) {
5361
conn, err := dial(log, resolver, amqp.Config(conf))
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package connectionmanager
2+
3+
import "testing"
4+
5+
func Test_maskUrl(t *testing.T) {
6+
tests := []struct {
7+
name string
8+
url string
9+
expected string
10+
}{
11+
{
12+
name: "No username or password",
13+
url: "amqp://localhost",
14+
expected: "amqp://localhost",
15+
},
16+
{
17+
name: "With username and password",
18+
url: "amqp://user:password@localhost",
19+
expected: "amqp://user:xxxxx@localhost",
20+
},
21+
{
22+
name: "With username and password and query params",
23+
url: "amqp://user:password@localhost?heartbeat=60",
24+
expected: "amqp://user:xxxxx@localhost?heartbeat=60",
25+
},
26+
{
27+
name: "Invalid URL",
28+
url: "invalidUrl",
29+
expected: "invalidUrl",
30+
},
31+
}
32+
33+
for _, tt := range tests {
34+
t.Run(tt.name, func(t *testing.T) {
35+
if maskPassword(tt.url) != tt.expected {
36+
t.Errorf("masked password = %v, but wanted %v", maskPassword(tt.url), tt.expected)
37+
}
38+
})
39+
}
40+
}

0 commit comments

Comments
 (0)