Skip to content

Commit

Permalink
core/logger: sanitize escape chars in console logs (#11402)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmank88 authored Nov 28, 2023
1 parent 7280c40 commit 41ab6be
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
6 changes: 6 additions & 0 deletions core/logger/internal/colortest/prettyconsole_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,12 @@ func TestPrettyConsole_Write(t *testing.T) {
"2018-04-12T12:55:28Z \x1b[91m[FATAL] \x1b[0mtop level \x1b[34m\x1b[0m \n",
false,
},
{
"control",
`{"ts":1523537728, "level":"fatal", "msg":"\u0008\t\n\r\u000b\u000c\ufffd\ufffd", "hash":"nuances"}`,
"2018-04-12T12:55:28Z \x1b[91m[FATAL] \x1b[0m\\b\t\n\r\\v\\f�� \x1b[34m\x1b[0m \n",
false,
},
{"broken", `{"broken":}`, `{}`, true},
}

Expand Down
29 changes: 27 additions & 2 deletions core/logger/prettyconsole.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ import (
"net/url"
"os"
"sort"
"strconv"
"strings"
"time"
"unicode"

"github.com/fatih/color"
"github.com/tidwall/gjson"
Expand Down Expand Up @@ -72,7 +74,7 @@ func generateHeadline(js gjson.Result) string {
tsStr,
" ",
coloredLevel(js.Get("level")),
fmt.Sprintf("%-50s", js.Get("msg")),
fmt.Sprintf("%-50s", sanitized(js.Get("msg").String())),
" ",
fmt.Sprintf("%-32s", blue(js.Get("caller"))),
}
Expand Down Expand Up @@ -105,7 +107,7 @@ func generateDetails(js gjson.Result) string {
var details strings.Builder

for _, v := range keys {
details.WriteString(fmt.Sprintf("%s=%v ", green(v), data[v]))
details.WriteString(fmt.Sprintf("%s=%v ", green(sanitized(v)), sanitized(data[v].String())))
}

return details.String()
Expand All @@ -129,3 +131,26 @@ func prettyConsoleSink(s zap.Sink) func(*url.URL) (zap.Sink, error) {
return PrettyConsole{s}, nil
}
}

type sanitized string

// String replaces control characters with Go escape sequences, except for newlines and tabs.
// See strconv.QuoteRune.
func (s sanitized) String() string {
var out string
for _, r := range s {
switch r {
case '\n', '\r', '\t':
// allowed
default:
// escape others
if unicode.IsControl(r) {
q := strconv.QuoteRune(r)
out += q[1 : len(q)-1] // trim quotes
continue
}
}
out += string(r)
}
return out
}
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ LatestReportDeadline = "5s" # Default
### Changed

- `L2Suggested` mode is now called `SuggestedPrice`
- Console logs will now escape (non-whitespace) control characters

### Removed

Expand Down

0 comments on commit 41ab6be

Please sign in to comment.