Skip to content

Commit

Permalink
Merge pull request #37 from fabriziosalmi/alert-autofix-42
Browse files Browse the repository at this point in the history
Potential fix for code scanning alert no. 42: Clear-text logging of sensitive information
  • Loading branch information
fabriziosalmi authored Jan 22, 2025
2 parents f4aef01 + 2f169d0 commit b503785
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,25 @@ func (m *Middleware) logRequest(level zapcore.Level, msg string, r *http.Request
}
}

// redactSensitiveFields redacts sensitive information in the log fields.
func (m *Middleware) redactSensitiveFields(fields []zap.Field) []zap.Field {
redactedFields := make([]zap.Field, len(fields))
for i, field := range fields {
redacted := false
for _, key := range sensitiveKeys {
if strings.Contains(strings.ToLower(field.Key), key) {
redactedFields[i] = zap.String(field.Key, "[REDACTED]")
redacted = true
break
}
}
if !redacted {
redactedFields[i] = field
}
}
return redactedFields
}

// prepareLogFields consolidates the logic for preparing log fields, including common fields and log_id.
func (m *Middleware) prepareLogFields(r *http.Request, fields []zap.Field) []zap.Field { // Corrected signature: Removed 'level zapcore.Level'
var logID string
Expand All @@ -50,6 +69,9 @@ func (m *Middleware) prepareLogFields(r *http.Request, fields []zap.Field) []zap
commonFields := m.getCommonLogFields(r)
allFields := m.mergeFields(customFields, commonFields, zap.String("log_id", logID)) // Ensure log_id is always present

// Redact sensitive information in the log fields
allFields = m.redactSensitiveFields(allFields)

return allFields
}

Expand Down

0 comments on commit b503785

Please sign in to comment.