Skip to content

Commit e30123a

Browse files
authored
refactor(recovery): extract Authorization header masking into maskAuthorization func (#4143)
* refactor(recovery): extract Authorization header masking into maskAuthorization func * test(recovery): Add a test for maskAuthorization
1 parent 3c12d2a commit e30123a

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

recovery.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,12 +70,7 @@ func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc {
7070
stack := stack(3)
7171
httpRequest, _ := httputil.DumpRequest(c.Request, false)
7272
headers := strings.Split(string(httpRequest), "\r\n")
73-
for idx, header := range headers {
74-
key, _, _ := strings.Cut(header, ":")
75-
if key == "Authorization" {
76-
headers[idx] = key + ": *"
77-
}
78-
}
73+
maskAuthorization(headers)
7974
headersToStr := strings.Join(headers, "\r\n")
8075
if brokenPipe {
8176
logger.Printf("%s\n%s%s", err, headersToStr, reset)
@@ -131,6 +126,16 @@ func stack(skip int) []byte {
131126
return buf.Bytes()
132127
}
133128

129+
// maskAuthorization replaces any "Authorization: <token>" header with "Authorization: *", hiding sensitive credentials.
130+
func maskAuthorization(headers []string) {
131+
for idx, header := range headers {
132+
key, _, _ := strings.Cut(header, ":")
133+
if strings.EqualFold(key, "Authorization") {
134+
headers[idx] = key + ": *"
135+
}
136+
}
137+
}
138+
134139
// source returns a space-trimmed slice of the n'th line.
135140
func source(lines [][]byte, n int) []byte {
136141
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed

recovery_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,24 @@ func TestPanicWithAbort(t *testing.T) {
8888
assert.Equal(t, http.StatusBadRequest, w.Code)
8989
}
9090

91+
func TestMaskAuthorization(t *testing.T) {
92+
secret := "Bearer aaaabbbbccccddddeeeeffff"
93+
headers := []string{
94+
"Host: www.example.com",
95+
"Authorization: " + secret,
96+
"User-Agent: curl/7.51.0",
97+
"Accept: */*",
98+
"Content-Type: application/json",
99+
"Content-Length: 1",
100+
}
101+
maskAuthorization(headers)
102+
103+
for _, h := range headers {
104+
assert.NotContains(t, h, secret)
105+
}
106+
assert.Contains(t, headers, "Authorization: *")
107+
}
108+
91109
func TestSource(t *testing.T) {
92110
bs := source(nil, 0)
93111
assert.Equal(t, dunnoBytes, bs)

0 commit comments

Comments
 (0)