From f2b11cd50deb1ee88468f76677ea85345150fcd9 Mon Sep 17 00:00:00 2001 From: Kaan <73611128+KaanSimsek@users.noreply.github.com> Date: Mon, 18 May 2026 17:02:06 +0300 Subject: [PATCH] fix(accesslog): escape double quotes in quoted log fields --- .../accesslog/logger_formatters.go | 3 +- .../accesslog/logger_formatters_test.go | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/pkg/middlewares/accesslog/logger_formatters.go b/pkg/middlewares/accesslog/logger_formatters.go index ec1c04f05..c001ea904 100644 --- a/pkg/middlewares/accesslog/logger_formatters.go +++ b/pkg/middlewares/accesslog/logger_formatters.go @@ -3,6 +3,7 @@ package accesslog import ( "bytes" "fmt" + "strings" "time" "github.com/sirupsen/logrus" @@ -108,7 +109,7 @@ func toLogEntry(s, defaultValue string, quote bool) string { } if quote { - return `"` + s + `"` + return `"` + strings.ReplaceAll(s, `"`, `\"`) + `"` } return s } diff --git a/pkg/middlewares/accesslog/logger_formatters_test.go b/pkg/middlewares/accesslog/logger_formatters_test.go index c1647a2a9..345c4d0fc 100644 --- a/pkg/middlewares/accesslog/logger_formatters_test.go +++ b/pkg/middlewares/accesslog/logger_formatters_test.go @@ -79,6 +79,27 @@ func TestCommonLogFormatter_Format(t *testing.T) { ServiceURL: "http://10.0.0.2/toto", }, expectedLog: `10.0.0.1 - Client [10/Nov/2009:14:00:00 -0900] "GET /foo http" 123 132 "referer" "agent" - "foo" "http://10.0.0.2/toto" 123000ms +`, + }, + { + name: "user-agent with double quote is escaped", + data: map[string]any{ + StartUTC: time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), + Duration: 1 * time.Millisecond, + ClientHost: "10.0.0.1", + ClientUsername: "-", + RequestMethod: http.MethodGet, + RequestPath: "/", + RequestProtocol: "HTTP/1.1", + DownstreamStatus: 200, + DownstreamContentSize: 0, + RequestRefererHeader: "-", + RequestUserAgentHeader: `foo " bar`, + RequestCount: 1, + RouterName: "test@file", + ServiceURL: "http://127.0.0.1:8080", + }, + expectedLog: `10.0.0.1 - - [10/Nov/2009:23:00:00 +0000] "GET / HTTP/1.1" 200 0 "-" "foo \" bar" 1 "test@file" "http://127.0.0.1:8080" 1ms `, }, } @@ -221,6 +242,16 @@ func Test_toLog(t *testing.T) { quoted: true, expectedLog: `"foo"`, }, + { + desc: "Should escape double quotes in quoted string", + fields: logrus.Fields{ + "Powpow": `foo " bar`, + }, + fieldName: "Powpow", + defaultValue: defaultValue, + quoted: true, + expectedLog: `"foo \" bar"`, + }, { desc: "Should return defaultValue if fieldName does not exist", fields: logrus.Fields{