Files
chorus/internal/core/queue/sanitize.go
T

55 lines
1.4 KiB
Go

package queue
import (
"regexp"
"strings"
"unicode"
"unicode/utf8"
)
var (
credentialPattern = regexp.MustCompile(`(?i)\b(api[_-]?key|authorization|password|token)\s*[:=]\s*[^\s,;]+`)
bearerPattern = regexp.MustCompile(`(?i)\bbearer\s+[^\s,;]+`)
urlPattern = regexp.MustCompile(`(?i)https?://[^\s]+`)
codePattern = regexp.MustCompile(`^[a-z0-9_]+$`)
)
func SanitizeErrorMessage(message string, maxBytes int) string {
message = urlPattern.ReplaceAllString(message, "[REDACTED-URL]")
message = bearerPattern.ReplaceAllString(message, "Bearer [REDACTED]")
message = credentialPattern.ReplaceAllString(message, "$1=[REDACTED]")
message = strings.Map(func(value rune) rune {
if unicode.IsControl(value) {
return ' '
}
return value
}, message)
message = strings.Join(strings.Fields(message), " ")
if message == "" {
message = "upstream request failed"
}
return truncateUTF8(message, maxBytes)
}
func sanitizeCode(code string) string {
code = strings.ToLower(strings.TrimSpace(code))
if len(code) == 0 || len(code) > 64 || !codePattern.MatchString(code) {
return "upstream_error"
}
return code
}
func truncateUTF8(value string, maxBytes int) string {
if maxBytes <= 0 {
return ""
}
if len(value) <= maxBytes {
return value
}
value = value[:maxBytes]
for !utf8.ValidString(value) {
value = value[:len(value)-1]
}
return value
}