Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

sanitize.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2021 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package util
  5. import (
  6. "net/url"
  7. "strings"
  8. )
  9. const userPlaceholder = "sanitized-credential"
  10. const unparsableURL = "(unparsable url)"
  11. type sanitizedError struct {
  12. err error
  13. replacer *strings.Replacer
  14. }
  15. func (err sanitizedError) Error() string {
  16. return err.replacer.Replace(err.err.Error())
  17. }
  18. // NewSanitizedError wraps an error and replaces all old, new string pairs in the message text.
  19. func NewSanitizedError(err error, oldnew ...string) error {
  20. return sanitizedError{err: err, replacer: strings.NewReplacer(oldnew...)}
  21. }
  22. // NewURLSanitizedError wraps an error and replaces the url credential or removes them.
  23. func NewURLSanitizedError(err error, u *url.URL, usePlaceholder bool) error {
  24. return sanitizedError{err: err, replacer: NewURLSanitizer(u, usePlaceholder)}
  25. }
  26. // NewStringURLSanitizedError wraps an error and replaces the url credential or removes them.
  27. // If the url can't get parsed it gets replaced with a placeholder string.
  28. func NewStringURLSanitizedError(err error, unsanitizedURL string, usePlaceholder bool) error {
  29. return sanitizedError{err: err, replacer: NewStringURLSanitizer(unsanitizedURL, usePlaceholder)}
  30. }
  31. // NewURLSanitizer creates a replacer for the url with the credential sanitized or removed.
  32. func NewURLSanitizer(u *url.URL, usePlaceholder bool) *strings.Replacer {
  33. old := u.String()
  34. if u.User != nil && usePlaceholder {
  35. u.User = url.User(userPlaceholder)
  36. } else {
  37. u.User = nil
  38. }
  39. return strings.NewReplacer(old, u.String())
  40. }
  41. // NewStringURLSanitizer creates a replacer for the url with the credential sanitized or removed.
  42. // If the url can't get parsed it gets replaced with a placeholder string
  43. func NewStringURLSanitizer(unsanitizedURL string, usePlaceholder bool) *strings.Replacer {
  44. u, err := url.Parse(unsanitizedURL)
  45. if err != nil {
  46. // don't log the error, since it might contain unsanitized URL.
  47. return strings.NewReplacer(unsanitizedURL, unparsableURL)
  48. }
  49. return NewURLSanitizer(u, usePlaceholder)
  50. }