-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogger_test.go
More file actions
647 lines (568 loc) · 18.7 KB
/
Copy pathlogger_test.go
File metadata and controls
647 lines (568 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2025 Daniel Schmidt
package netconf
import (
"bytes"
"context"
"log"
"os"
"regexp"
"strings"
"testing"
)
func TestLogLevel_String(t *testing.T) {
tests := []struct {
name string
level LogLevel
expected string
}{
{"Debug", LogLevelDebug, "DEBUG"},
{"Info", LogLevelInfo, "INFO"},
{"Warn", LogLevelWarn, "WARN"},
{"Error", LogLevelError, "ERROR"},
{"None", LogLevelNone, "NONE"},
{"Unknown", LogLevel(999), "UNKNOWN(999)"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.level.String(); got != tt.expected {
t.Errorf("LogLevel.String() = %v, want %v", got, tt.expected)
}
})
}
}
func TestDefaultLogger(t *testing.T) {
// Capture log output
var buf bytes.Buffer
log.SetOutput(&buf)
defer log.SetOutput(os.Stderr)
logger := NewDefaultLogger(LogLevelDebug)
t.Run("Debug", func(t *testing.T) {
buf.Reset()
logger.Debug(context.Background(), "test message", "key1", "value1", "key2", "value2")
output := buf.String()
if !strings.Contains(output, "[DEBUG]") {
t.Errorf("Expected [DEBUG] in output, got: %s", output)
}
if !strings.Contains(output, "test message") {
t.Errorf("Expected 'test message' in output, got: %s", output)
}
if !strings.Contains(output, "key1=value1") {
t.Errorf("Expected 'key1=value1' in output, got: %s", output)
}
if !strings.Contains(output, "key2=value2") {
t.Errorf("Expected 'key2=value2' in output, got: %s", output)
}
})
t.Run("Info", func(t *testing.T) {
buf.Reset()
logger.Info(context.Background(), "info message", "host", "192.168.1.1", "port", 830)
output := buf.String()
if !strings.Contains(output, "[INFO]") {
t.Errorf("Expected [INFO] in output, got: %s", output)
}
if !strings.Contains(output, "info message") {
t.Errorf("Expected 'info message' in output, got: %s", output)
}
if !strings.Contains(output, "host=192.168.1.1") {
t.Errorf("Expected 'host=192.168.1.1' in output, got: %s", output)
}
if !strings.Contains(output, "port=830") {
t.Errorf("Expected 'port=830' in output, got: %s", output)
}
})
t.Run("Warn", func(t *testing.T) {
buf.Reset()
logger.Warn(context.Background(), "warning message")
output := buf.String()
if !strings.Contains(output, "[WARN]") {
t.Errorf("Expected [WARN] in output, got: %s", output)
}
if !strings.Contains(output, "warning message") {
t.Errorf("Expected 'warning message' in output, got: %s", output)
}
})
t.Run("Error", func(t *testing.T) {
buf.Reset()
logger.Error(context.Background(), "error message", "error", "something went wrong")
output := buf.String()
if !strings.Contains(output, "[ERROR]") {
t.Errorf("Expected [ERROR] in output, got: %s", output)
}
if !strings.Contains(output, "error message") {
t.Errorf("Expected 'error message' in output, got: %s", output)
}
if !strings.Contains(output, "error=something went wrong") {
t.Errorf("Expected 'error=something went wrong' in output, got: %s", output)
}
})
}
func TestDefaultLogger_LogLevels(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
defer log.SetOutput(os.Stderr)
tests := []struct {
name string
level LogLevel
logFunc func(Logger)
shouldLog bool
}{
{"Debug at Debug", LogLevelDebug, func(l Logger) { l.Debug(context.Background(), "test") }, true},
{"Info at Debug", LogLevelDebug, func(l Logger) { l.Info(context.Background(), "test") }, true},
{"Warn at Debug", LogLevelDebug, func(l Logger) { l.Warn(context.Background(), "test") }, true},
{"Error at Debug", LogLevelDebug, func(l Logger) { l.Error(context.Background(), "test") }, true},
{"Debug at Info", LogLevelInfo, func(l Logger) { l.Debug(context.Background(), "test") }, false},
{"Info at Info", LogLevelInfo, func(l Logger) { l.Info(context.Background(), "test") }, true},
{"Warn at Info", LogLevelInfo, func(l Logger) { l.Warn(context.Background(), "test") }, true},
{"Error at Info", LogLevelInfo, func(l Logger) { l.Error(context.Background(), "test") }, true},
{"Debug at Warn", LogLevelWarn, func(l Logger) { l.Debug(context.Background(), "test") }, false},
{"Info at Warn", LogLevelWarn, func(l Logger) { l.Info(context.Background(), "test") }, false},
{"Warn at Warn", LogLevelWarn, func(l Logger) { l.Warn(context.Background(), "test") }, true},
{"Error at Warn", LogLevelWarn, func(l Logger) { l.Error(context.Background(), "test") }, true},
{"Debug at Error", LogLevelError, func(l Logger) { l.Debug(context.Background(), "test") }, false},
{"Info at Error", LogLevelError, func(l Logger) { l.Info(context.Background(), "test") }, false},
{"Warn at Error", LogLevelError, func(l Logger) { l.Warn(context.Background(), "test") }, false},
{"Error at Error", LogLevelError, func(l Logger) { l.Error(context.Background(), "test") }, true},
{"Debug at None", LogLevelNone, func(l Logger) { l.Debug(context.Background(), "test") }, false},
{"Info at None", LogLevelNone, func(l Logger) { l.Info(context.Background(), "test") }, false},
{"Warn at None", LogLevelNone, func(l Logger) { l.Warn(context.Background(), "test") }, false},
{"Error at None", LogLevelNone, func(l Logger) { l.Error(context.Background(), "test") }, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
buf.Reset()
logger := NewDefaultLogger(tt.level)
tt.logFunc(logger)
output := buf.String()
if tt.shouldLog && output == "" {
t.Errorf("Expected log output, got empty string")
}
if !tt.shouldLog && output != "" {
t.Errorf("Expected no log output, got: %s", output)
}
})
}
}
func TestNoOpLogger(_ *testing.T) {
// NoOpLogger should not panic and should do nothing
logger := &NoOpLogger{}
// These should all be no-ops
logger.Debug(context.Background(), "test", "key", "value")
logger.Info(context.Background(), "test", "key", "value")
logger.Warn(context.Background(), "test", "key", "value")
logger.Error(context.Background(), "test", "key", "value")
// If we got here without panic, test passes
}
func TestClient_redactSensitiveData(t *testing.T) {
client := &Client{
redactionPatterns: []*regexp.Regexp{
regexp.MustCompile(`<password>.*?</password>`),
regexp.MustCompile(`<secret>.*?</secret>`),
regexp.MustCompile(`<key>.*?</key>`),
regexp.MustCompile(`<community>.*?</community>`),
},
}
tests := []struct {
name string
input string
expected string
}{
{
name: "Redact password",
input: "<config><password>secret123</password></config>",
expected: "<config><password>[REDACTED]</password></config>",
},
{
name: "Redact secret",
input: "<config><secret>topsecret</secret></config>",
expected: "<config><secret>[REDACTED]</secret></config>",
},
{
name: "Redact key",
input: "<config><key>abc123</key></config>",
expected: "<config><key>[REDACTED]</key></config>",
},
{
name: "Redact community",
input: "<config><community>public</community></config>",
expected: "<config><community>[REDACTED]</community></config>",
},
{
name: "Redact multiple",
input: `<config>
<password>secret123</password>
<key>abc123</key>
<community>private</community>
</config>`,
expected: `<config>
<password>[REDACTED]</password>
<key>[REDACTED]</key>
<community>[REDACTED]</community>
</config>`,
},
{
name: "No sensitive data",
input: "<config><hostname>router1</hostname></config>",
expected: "<config><hostname>router1</hostname></config>",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := client.redactSensitiveData(tt.input)
if result != tt.expected {
t.Errorf("redactSensitiveData() = %v, want %v", result, tt.expected)
}
})
}
}
func TestClient_redactSensitiveData_NestedStructures(t *testing.T) {
client := &Client{
redactionPatterns: defaultRedactionPatterns,
}
tests := []struct {
name string
input string
expected string
}{
{
name: "Nested password (Cisco YANG style)",
input: "<username><name>admin</name><password><password>secret123</password></password></username>",
expected: "<username><name>admin</name><password>[REDACTED]</password></username>",
},
{
name: "Deeply nested password",
input: "<config><password><password><password>secret</password></password></password></config>",
expected: "<config><password>[REDACTED]</password></config>",
},
{
name: "Multiple nested passwords",
input: "<users><user1><password><password>pass1</password></password></user1><user2><password><password>pass2</password></password></user2></users>",
expected: "<users><user1><password>[REDACTED]</password></user1><user2><password>[REDACTED]</password></user2></users>",
},
{
name: "Mixed simple and nested passwords",
input: "<config><simple><password>secret1</password></simple><nested><password><password>secret2</password></password></nested></config>",
expected: "<config><simple><password>[REDACTED]</password></simple><nested><password>[REDACTED]</password></nested></config>",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := client.redactSensitiveData(tt.input)
if result != tt.expected {
t.Errorf("Expected:\n%s\nGot:\n%s", tt.expected, result)
}
})
}
}
func TestClient_prepareXMLForLogging(t *testing.T) {
client := &Client{
prettyPrintLogs: true,
redactionPatterns: []*regexp.Regexp{
regexp.MustCompile(`<password>.*?</password>`),
regexp.MustCompile(`<secret>.*?</secret>`),
regexp.MustCompile(`<key>.*?</key>`),
regexp.MustCompile(`<community>.*?</community>`),
},
}
t.Run("Redaction and pretty print", func(t *testing.T) {
input := "<config><password>secret</password><hostname>router1</hostname></config>"
result := client.prepareXMLForLogging(input)
// Should be redacted (password should not appear in plain text)
if strings.Contains(result, "secret") {
t.Errorf("Expected password to be redacted, got: %s", result)
}
// The result should contain either the redacted XML or be empty (if @pretty doesn't work)
// In either case, the secret should be gone
if result != "" {
// If we got output, it should contain [REDACTED]
if !strings.Contains(result, "[REDACTED]") {
t.Errorf("Expected [REDACTED] in non-empty output, got: %s", result)
}
// Should contain hostname (not redacted)
if !strings.Contains(result, "router1") {
t.Errorf("Expected 'router1' in output, got: %s", result)
}
}
})
t.Run("Pretty print disabled", func(t *testing.T) {
client.prettyPrintLogs = false
input := "<config><password>secret</password><hostname>router1</hostname></config>"
result := client.prepareXMLForLogging(input)
// Should be redacted
if strings.Contains(result, "secret") {
t.Errorf("Expected password to be redacted, got: %s", result)
}
if !strings.Contains(result, "[REDACTED]") {
t.Errorf("Expected [REDACTED] in output, got: %s", result)
}
// Should start with newline for formatting
if !strings.HasPrefix(result, "\n") {
t.Errorf("Expected leading newline for formatting, got: %s", result)
}
// Should not have additional newlines (not pretty printed - single line XML)
if strings.Count(result, "\n") > 1 {
t.Errorf("Expected only leading newline (not pretty printed), got: %s", result)
}
})
}
func TestWithLogger(t *testing.T) {
logger := NewDefaultLogger(LogLevelInfo)
client := &Client{
logger: &NoOpLogger{},
}
// Apply option
opt := WithLogger(logger)
opt(client)
// Verify logger was set
if client.logger != logger {
t.Errorf("Expected custom logger to be set")
}
}
func TestWithLogger_Nil(t *testing.T) {
client := &Client{
logger: &NoOpLogger{},
}
// Apply option with nil logger (should not change)
opt := WithLogger(nil)
opt(client)
// Verify logger was not changed
if _, ok := client.logger.(*NoOpLogger); !ok {
t.Errorf("Expected NoOpLogger to remain when nil logger provided")
}
}
func TestWithPrettyPrintLogs(t *testing.T) {
tests := []struct {
name string
enabled bool
expected bool
}{
{"Enable", true, true},
{"Disable", false, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
client := &Client{}
opt := WithPrettyPrintLogs(tt.enabled)
opt(client)
if client.prettyPrintLogs != tt.expected {
t.Errorf("Expected prettyPrintLogs = %v, got %v", tt.expected, client.prettyPrintLogs)
}
})
}
}
// TestDefaultLogger_LogInjectionPrevention tests log injection attack prevention
func TestDefaultLogger_LogInjectionPrevention(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
defer func() {
log.SetOutput(os.Stderr)
}()
logger := NewDefaultLogger(LogLevelInfo)
t.Run("Newline injection", func(t *testing.T) {
buf.Reset()
// Newlines are now preserved for multi-line XML logging
logger.Info(context.Background(), "Test", "xml", "value\nFAKE ERROR")
output := buf.String()
// Newlines are preserved for multi-line logging
if !strings.Contains(output, "\nFAKE ERROR") {
t.Error("Newline should be preserved for multi-line XML logging")
}
// Should contain the full content
if !strings.Contains(output, "FAKE ERROR") {
t.Errorf("Expected content in output, got: %s", output)
}
})
t.Run("Carriage return injection", func(t *testing.T) {
buf.Reset()
logger.Info(context.Background(), "Test", "key", "value\r[ERROR] Injected")
output := buf.String()
// Carriage return should be replaced
if strings.Contains(output, "\r") {
t.Error("Carriage return was not sanitized")
}
})
t.Run("Tab injection", func(t *testing.T) {
buf.Reset()
logger.Info(context.Background(), "Test", "key", "value\ttab")
output := buf.String()
// Tab should be replaced with space
if strings.Contains(output, "\t") {
t.Error("Tab was not sanitized")
}
// Should contain sanitized version (space)
if !strings.Contains(output, "value tab") {
t.Errorf("Expected sanitized tab in output, got: %s", output)
}
})
t.Run("Control characters", func(t *testing.T) {
buf.Reset()
// Control character (ASCII 0x01)
logger.Info(context.Background(), "Test", "key", "value\x01control")
output := buf.String()
// Control character should be replaced with dot
if strings.Contains(output, "\x01") {
t.Error("Control character was not sanitized")
}
// Should contain sanitized version (dot)
if !strings.Contains(output, "value.control") {
t.Errorf("Expected sanitized control character in output, got: %s", output)
}
})
}
// TestDefaultLogger_LongValueTruncation tests truncation of long log values
func TestDefaultLogger_LongValueTruncation(t *testing.T) {
var buf bytes.Buffer
log.SetOutput(&buf)
defer func() {
log.SetOutput(os.Stderr)
}()
logger := NewDefaultLogger(LogLevelInfo)
t.Run("Long value truncation", func(t *testing.T) {
buf.Reset()
// Create a very long value (> MaxLogValueLength)
// MaxLogValueLength is 100000, so use 150000 to trigger truncation
longValue := strings.Repeat("A", 150000)
logger.Info(context.Background(), "Test", "key", longValue)
output := buf.String()
// Should be truncated
if strings.Contains(output, strings.Repeat("A", 150000)) {
t.Error("Long value was not truncated")
}
// Should contain truncation marker
if !strings.Contains(output, "[TRUNCATED]") {
t.Error("Truncation marker not found")
}
// Should contain first part of the value (first 100 chars)
if !strings.Contains(output, strings.Repeat("A", 100)) {
t.Error("Expected truncated value to contain first part")
}
// Should NOT contain the end of the long value
if strings.Contains(output, strings.Repeat("A", 140000)) {
t.Error("Expected long tail to be truncated")
}
})
t.Run("Exact limit value", func(t *testing.T) {
buf.Reset()
// Create a value exactly at the limit
exactValue := strings.Repeat("B", MaxLogValueLength)
logger.Info(context.Background(), "Test", "key", exactValue)
output := buf.String()
// Should NOT be truncated (equal to limit)
if strings.Contains(output, "[TRUNCATED]") {
t.Error("Value at exact limit should not be truncated")
}
// Should contain full value
if !strings.Contains(output, exactValue) {
t.Error("Expected full value at exact limit")
}
})
}
// TestSanitizeLogValue tests the sanitizeLogValue function directly
func TestSanitizeLogValue(t *testing.T) {
tests := []struct {
name string
input any
expected string
}{
{
name: "Normal string",
input: "normal value",
expected: "normal value",
},
{
name: "String with newline",
input: "line1\nline2",
expected: "line1\nline2", // Newlines preserved for multi-line XML logging
},
{
name: "String with carriage return",
input: "line1\rline2",
expected: "line1line2", // Carriage returns removed (security risk)
},
{
name: "String with tab",
input: "col1\tcol2",
expected: "col1 col2",
},
{
name: "String with control character",
input: "value\x00null",
expected: "value.null",
},
{
name: "Integer value",
input: 12345,
expected: "12345",
},
{
name: "Boolean value",
input: true,
expected: "true",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := sanitizeLogValue(tt.input)
if result != tt.expected {
t.Errorf("sanitizeLogValue(%v) = %q, want %q", tt.input, result, tt.expected)
}
})
}
}
func TestSanitizeLogValue_ANSIEscapeSequences(t *testing.T) {
tests := []struct {
name string
input string
notContains string // What should NOT be in output
}{
{
name: "ANSI red color code",
input: "\x1b[31mRED TEXT\x1b[0m",
notContains: "\x1b",
},
{
name: "ANSI cursor movement",
input: "\x1b[2J\x1b[H",
notContains: "\x1b",
},
{
name: "Terminal bell",
input: "alert\x07",
notContains: "\x07",
},
{
name: "Backspace attack",
input: "admin\x08\x08\x08\x08\x08hacker",
notContains: "\x08",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := sanitizeLogValue(tt.input)
if tt.notContains != "" && strings.Contains(result, tt.notContains) {
t.Errorf("Result still contains dangerous character: %q", tt.notContains)
}
})
}
}
func TestSanitizeLogValue_UnicodeAttacks(t *testing.T) {
tests := []struct {
name string
input string
}{
{"Zero-width space", "admin\u200Bhacker"},
{"Zero-width joiner", "admin\u200Dhacker"},
{"RTL override", "admin\u202Ehacker"},
{"BOM", "admin\uFEFFhacker"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := sanitizeLogValue(tt.input)
// Result should either remove or replace dangerous Unicode
// Length should be different from input (unless replaced with same-width)
if result == tt.input {
t.Errorf("Dangerous Unicode was not sanitized")
}
})
}
}