-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlogger.go
More file actions
348 lines (310 loc) · 10.3 KB
/
Copy pathlogger.go
File metadata and controls
348 lines (310 loc) · 10.3 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
// SPDX-License-Identifier: MPL-2.0
// Copyright (c) 2025 Daniel Schmidt
package netconf
import (
"context"
"fmt"
"log"
"strings"
"unicode/utf8"
)
// MaxLogValueLength limits the length of log values to prevent log injection
// and excessive log file growth. Values longer than this are truncated.
const MaxLogValueLength = 100000
// Logger interface for pluggable logging support
//
// All methods receive a context.Context as the first parameter, enabling
// integration with context-based logging frameworks and distributed tracing.
//
// Implementations should use structured logging with key-value pairs.
// The go-netconf library provides two implementations:
// - DefaultLogger: Wraps Go's standard log package with configurable log level
// - NoOpLogger: Zero-overhead logging when disabled (default)
//
// Context Usage Guidelines:
//
// The context parameter enables trace correlation and debugging:
// - Use context.Background() for utility methods and internal operations
// - Propagate the user's context from API calls (Get, Set, EditConfig, etc.)
// - Extract trace IDs, request IDs, or tenant IDs for correlation
// - Check context deadline to log timeout information
//
// When to use context.Background():
// - Internal utility methods (validation, formatting, sanitization)
// - Constructor methods (NewClient)
// - Configuration processing
// - Static operations that don't involve user requests
//
// When to propagate user context:
// - NETCONF operations (Get, EditConfig, Lock, Unlock, etc.)
// - Network operations (Connect, Close)
// - Request/response processing
// - Any operation initiated by a user API call
//
// Example custom logger integration:
//
// type SlogAdapter struct {
// logger *slog.Logger
// }
//
// func (s *SlogAdapter) Debug(ctx context.Context, msg string, keysAndValues ...any) {
// s.logger.DebugContext(ctx, msg, keysAndValues...)
// }
// // ... implement other methods
//
// client, _ := netconf.NewClient("192.168.1.1",
// netconf.Username("admin"),
// netconf.Password("secret"),
// netconf.WithLogger(&SlogAdapter{logger: slog.Default()}))
type Logger interface {
Debug(ctx context.Context, msg string, keysAndValues ...any)
Info(ctx context.Context, msg string, keysAndValues ...any)
Warn(ctx context.Context, msg string, keysAndValues ...any)
Error(ctx context.Context, msg string, keysAndValues ...any)
}
// LogLevel represents the severity threshold for logging
type LogLevel int
const (
// LogLevelDebug enables all log levels (most verbose)
LogLevelDebug LogLevel = iota
// LogLevelInfo enables Info, Warn, and Error logs
LogLevelInfo
// LogLevelWarn enables Warn and Error logs
LogLevelWarn
// LogLevelError enables only Error logs
LogLevelError
// LogLevelNone disables all logging
LogLevelNone
)
// String returns the string representation of a LogLevel
func (l LogLevel) String() string {
switch l {
case LogLevelDebug:
return "DEBUG"
case LogLevelInfo:
return "INFO"
case LogLevelWarn:
return "WARN"
case LogLevelError:
return "ERROR"
case LogLevelNone:
return "NONE"
default:
return fmt.Sprintf("UNKNOWN(%d)", l)
}
}
// DefaultLogger wraps Go's standard log package with configurable log level
//
// Log output format: [LEVEL] message key1=value1 key2=value2
//
// Context Parameter Usage:
//
// DefaultLogger does NOT use the context parameter. It is provided to satisfy
// the Logger interface and enable integration with context-aware logging frameworks.
//
// Custom logger implementations SHOULD use the context to extract trace correlation
// data such as:
// - Request ID / Trace ID for distributed tracing
// - User ID or tenant ID for multi-tenant applications
// - Deadline information for timeout debugging
//
// Example of context-aware logging in a custom logger:
//
// func (s *SlogAdapter) Debug(ctx context.Context, msg string, keysAndValues ...any) {
// // Extract trace ID from context
// if traceID := ctx.Value("trace_id"); traceID != nil {
// keysAndValues = append(keysAndValues, "trace_id", traceID)
// }
// s.logger.DebugContext(ctx, msg, keysAndValues...)
// }
//
// Example:
//
// logger := netconf.NewDefaultLogger(netconf.LogLevelDebug)
// client, _ := netconf.NewClient("192.168.1.1",
// netconf.Username("admin"),
// netconf.Password("secret"),
// netconf.WithLogger(logger))
type DefaultLogger struct {
level LogLevel
}
// NewDefaultLogger creates a DefaultLogger with the specified log level
func NewDefaultLogger(level LogLevel) *DefaultLogger {
return &DefaultLogger{level: level}
}
// Debug logs a debug message with structured key-value pairs
func (l *DefaultLogger) Debug(ctx context.Context, msg string, keysAndValues ...any) {
if l.level <= LogLevelDebug {
l.log("DEBUG", msg, keysAndValues...)
}
}
// Info logs an informational message with structured key-value pairs
func (l *DefaultLogger) Info(ctx context.Context, msg string, keysAndValues ...any) {
if l.level <= LogLevelInfo {
l.log("INFO", msg, keysAndValues...)
}
}
// Warn logs a warning message with structured key-value pairs
func (l *DefaultLogger) Warn(ctx context.Context, msg string, keysAndValues ...any) {
if l.level <= LogLevelWarn {
l.log("WARN", msg, keysAndValues...)
}
}
// Error logs an error message with structured key-value pairs
func (l *DefaultLogger) Error(ctx context.Context, msg string, keysAndValues ...any) {
if l.level <= LogLevelError {
l.log("ERROR", msg, keysAndValues...)
}
}
// sanitizeLogValue sanitizes a log value to prevent log injection attacks
// and limit log size. Handles control characters, ANSI escape sequences,
// Unicode attacks (RTL override, zero-width), and excessive length.
//
// Security Note: Newlines (\n) are preserved to support multi-line XML logging
// with pretty printing. Other control characters that could enable log injection
// attacks (carriage return, ANSI escape sequences, etc.) are still sanitized.
//
// Example sanitization:
//
// Input: "user\r\n\x1b[31mFake\x1b[0m"
// Output: "user\n.31mFake.0m" (newlines preserved, ANSI codes neutralized)
//
// Returns the sanitized string value.
func sanitizeLogValue(val any) string {
str := fmt.Sprintf("%v", val)
// Truncate long values to prevent log file DoS
if len(str) > MaxLogValueLength {
str = str[:MaxLogValueLength] + "...[TRUNCATED]"
}
// Sanitize potentially malicious characters
var builder strings.Builder
builder.Grow(len(str))
for i := 0; i < len(str); i++ {
r := rune(str[i])
// Handle multi-byte UTF-8 sequences
if r >= 0x80 {
// Decode full rune
decoded, size := utf8.DecodeRuneInString(str[i:])
if decoded == utf8.RuneError {
builder.WriteRune('.')
// CRITICAL: Must advance index even on error to prevent infinite loop
if size == 0 {
size = 1 // Ensure forward progress on malformed UTF-8
}
i += size - 1
continue
}
// Block dangerous Unicode characters
switch decoded {
case 0x200B, 0x200C, 0x200D, 0xFEFF: // Zero-width characters
// Skip entirely (don't even write space)
case 0x202E: // Right-to-left override
builder.WriteRune(' ')
default:
// Allow normal Unicode
builder.WriteString(str[i : i+size])
i += size - 1 // Advance past multi-byte sequence
}
continue
}
// ASCII control characters and ANSI escape sequences
switch r {
case '\n': // Preserve newlines for multi-line XML logging
builder.WriteRune('\n')
case '\r': // Carriage return can enable log injection, remove it
// Skip entirely (don't write anything)
case '\t': // Tab injection
builder.WriteRune(' ')
case 0x1B: // ESC - start of ANSI sequence
builder.WriteRune('.') // Visible indicator
case 0x07: // Bell
builder.WriteRune('.')
case 0x08: // Backspace (log manipulation)
builder.WriteRune('.')
case 0x0C: // Form feed
builder.WriteRune(' ')
default:
if r < 32 || r == 127 {
// Other control characters
builder.WriteRune('.')
} else {
// Normal printable ASCII
builder.WriteRune(r)
}
}
}
return builder.String()
}
// log formats and outputs a log message with structured key-value pairs
//
// All key-value pairs are sanitized to prevent log injection attacks and
// enforce size limits. The message string is NOT sanitized as it comes from
// trusted sources (the library code itself).
func (l *DefaultLogger) log(level, msg string, keysAndValues ...any) {
if l.level > logLevelFromString(level) {
return
}
// Pre-allocate builder capacity to reduce allocations
estimatedSize := len(level) + len(msg) + 10 + (len(keysAndValues) * 25)
var builder strings.Builder
builder.Grow(estimatedSize)
builder.WriteString("[")
builder.WriteString(level)
builder.WriteString("] ")
builder.WriteString(msg)
// Format key-value pairs
for i := 0; i < len(keysAndValues); i += 2 {
builder.WriteString(" ")
// Write key (sanitized)
if i < len(keysAndValues) {
builder.WriteString(sanitizeLogValue(keysAndValues[i]))
}
// Write value (sanitized)
if i+1 < len(keysAndValues) {
builder.WriteString("=")
builder.WriteString(sanitizeLogValue(keysAndValues[i+1]))
} else {
// Odd-length array - mark missing value explicitly
builder.WriteString("=<MISSING>")
}
}
log.Println(builder.String())
}
// logLevelFromString converts a level string to LogLevel for comparison
func logLevelFromString(level string) LogLevel {
switch level {
case "DEBUG":
return LogLevelDebug
case "INFO":
return LogLevelInfo
case "WARN":
return LogLevelWarn
case "ERROR":
return LogLevelError
default:
return LogLevelNone
}
}
// NoOpLogger is a no-operation logger that discards all log messages
//
// This logger provides zero overhead when logging is disabled. All methods
// are no-ops and will be optimized away by the compiler.
//
// This is the default logger used by go-netconf when no custom logger
// is configured.
//
// Example:
//
// // Logging is disabled by default (uses NoOpLogger)
// client, _ := netconf.NewClient("192.168.1.1",
// netconf.Username("admin"),
// netconf.Password("secret"))
type NoOpLogger struct{}
// Debug discards the log message
func (n *NoOpLogger) Debug(_ context.Context, _ string, _ ...any) {}
// Info discards the log message
func (n *NoOpLogger) Info(_ context.Context, _ string, _ ...any) {}
// Warn discards the log message
func (n *NoOpLogger) Warn(_ context.Context, _ string, _ ...any) {}
// Error discards the log message
func (n *NoOpLogger) Error(_ context.Context, _ string, _ ...any) {}