MCPcopy
hub / github.com/grafana/dskit / TestEndToEnd_logfmt

Function TestEndToEnd_logfmt

log/sanitize_test.go:289–357  ·  view source on GitHub ↗

TestEndToEnd_logfmt verifies that values wrapped with DropUnsafeChars or EscapeUnsafeChars are encoded as expected by go-kit's logfmt logger.

(t *testing.T)

Source from the content-addressed store, hash-verified

287// DropUnsafeChars or EscapeUnsafeChars are encoded as expected by
288// go-kit's logfmt logger.
289func TestEndToEnd_logfmt(t *testing.T) {
290 testCases := map[string]struct {
291 value any
292 wantOnWire map[string]string // logger name -> expected bytes
293 }{
294 "clean string passes through both wrappers unchanged": {
295 value: "Mozilla/5.0",
296 wantOnWire: map[string]string{
297 "drop": "user_agent=Mozilla/5.0\n",
298 "escape": "user_agent=Mozilla/5.0\n",
299 },
300 },
301 "embedded newline is sanitized before reaching the encoder": {
302 value: "Mozilla\nFAKE",
303 wantOnWire: map[string]string{
304 // Drop yields "MozillaFAKE". Because the result contains no whitespace,
305 // logfmt emits it without quotes.
306 "drop": "user_agent=MozillaFAKE\n",
307 // Escape yields "Mozilla\x0aFAKE" (with a literal backslash). Because
308 // the result contains no whitespace, logfmt does not quote it and it
309 // reaches the output unchanged.
310 "escape": "user_agent=Mozilla\\x0aFAKE\n",
311 },
312 },
313 "custom Stringer rendering user-controlled text is sanitized": {
314 value: testUnsafeUserInputStringer{"path=/foo\nFAKE"},
315 wantOnWire: map[string]string{
316 // Drop yields "path=/fooFAKE". Because the value contains '=',
317 // logfmt quotes it in the output.
318 "drop": "user_agent=\"path=/fooFAKE\"\n",
319 // Escape yields "path=/foo\x0aFAKE". The embedded '=' causes logfmt to
320 // quote the value, and the backslash in `\x0a` is escaped within the
321 // quoted string.
322 "escape": "user_agent=\"path=/foo\\\\x0aFAKE\"\n",
323 },
324 },
325 "typed-nil error renders as null, matching go-kit raw output": {
326 value: (*testNilSafeError)(nil),
327 wantOnWire: map[string]string{
328 "drop": "user_agent=null\n",
329 "escape": "user_agent=null\n",
330 },
331 },
332 "nil any renders as null, matching go-kit raw output": {
333 value: nil,
334 wantOnWire: map[string]string{
335 "drop": "user_agent=null\n",
336 "escape": "user_agent=null\n",
337 },
338 },
339 }
340
341 for name, tc := range testCases {
342 t.Run(name, func(t *testing.T) {
343 t.Run("drop", func(t *testing.T) {
344 buf := &bytes.Buffer{}
345 logger := log.NewLogfmtLogger(buf)
346 require.NoError(t, logger.Log("user_agent", DropUnsafeChars(tc.value)))

Callers

nothing calls this directly

Calls 6

DropUnsafeCharsFunction · 0.85
EscapeUnsafeCharsFunction · 0.85
RunMethod · 0.80
StringMethod · 0.65
LogMethod · 0.45
EqualMethod · 0.45

Tested by

no test coverage detected