本站源代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.4KB

  1. // Copyright 2017 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. // urlSafeError wraps an error whose message may contain a sensitive URL
  10. type urlSafeError struct {
  11. err error
  12. unsanitizedURL string
  13. }
  14. func (err urlSafeError) Error() string {
  15. return SanitizeMessage(err.err.Error(), err.unsanitizedURL)
  16. }
  17. // URLSanitizedError returns the sanitized version an error whose message may
  18. // contain a sensitive URL
  19. func URLSanitizedError(err error, unsanitizedURL string) error {
  20. return urlSafeError{err: err, unsanitizedURL: unsanitizedURL}
  21. }
  22. // SanitizeMessage sanitizes a message which may contains a sensitive URL
  23. func SanitizeMessage(message, unsanitizedURL string) string {
  24. sanitizedURL := SanitizeURLCredentials(unsanitizedURL, true)
  25. return strings.Replace(message, unsanitizedURL, sanitizedURL, -1)
  26. }
  27. // SanitizeURLCredentials sanitizes a url, either removing user credentials
  28. // or replacing them with a placeholder.
  29. func SanitizeURLCredentials(unsanitizedURL string, usePlaceholder bool) string {
  30. u, err := url.Parse(unsanitizedURL)
  31. if err != nil {
  32. // don't log the error, since it might contain unsanitized URL.
  33. return "(unparsable url)"
  34. }
  35. if u.User != nil && usePlaceholder {
  36. u.User = url.User("<credentials>")
  37. } else {
  38. u.User = nil
  39. }
  40. return u.String()
  41. }
上海开阖软件有限公司 沪ICP备12045867号-1