request_metadata.go 776 B

123456789101112131415161718192021222324252627282930
  1. package middleware
  2. import (
  3. "strings"
  4. "unicode/utf8"
  5. )
  6. const (
  7. maxPersistentRequestIDBytes = 64
  8. maxPersistentUserAgentBytes = 512
  9. )
  10. // normalizePersistentText bounds attacker-controlled metadata before it reaches
  11. // logs or database columns while preserving valid UTF-8 content.
  12. func normalizePersistentText(value string, maxBytes int) string {
  13. value = strings.TrimSpace(strings.ToValidUTF8(value, ""))
  14. if maxBytes <= 0 || len(value) <= maxBytes {
  15. return value
  16. }
  17. value = value[:maxBytes]
  18. for !utf8.ValidString(value) {
  19. value = value[:len(value)-1]
  20. }
  21. return value
  22. }
  23. func normalizeCorrelationID(value string) (string, bool) {
  24. value = strings.TrimSpace(strings.ToValidUTF8(value, ""))
  25. return value, value != "" && len(value) <= maxPersistentRequestIDBytes
  26. }