url_validator.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. package common
  2. import (
  3. "fmt"
  4. "net/url"
  5. "strings"
  6. "github.com/QuantumNous/new-api/constant"
  7. )
  8. // ValidateRedirectURL validates that a redirect URL is safe to use.
  9. // It checks that:
  10. // - The URL is properly formatted
  11. // - The scheme is either http or https
  12. // - The domain is in the trusted domains list (exact match or subdomain)
  13. //
  14. // Returns nil if the URL is valid and trusted, otherwise returns an error
  15. // describing why the validation failed.
  16. func ValidateRedirectURL(rawURL string) error {
  17. // Parse the URL
  18. parsedURL, err := url.Parse(rawURL)
  19. if err != nil {
  20. return fmt.Errorf("invalid URL format: %s", err.Error())
  21. }
  22. if parsedURL.Scheme != "http" && parsedURL.Scheme != "https" {
  23. return fmt.Errorf("invalid URL scheme: only http and https are allowed")
  24. }
  25. domain := strings.ToLower(parsedURL.Hostname())
  26. for _, trustedDomain := range constant.TrustedRedirectDomains {
  27. if domain == trustedDomain || strings.HasSuffix(domain, "."+trustedDomain) {
  28. return nil
  29. }
  30. }
  31. return fmt.Errorf("domain %s is not in the trusted domains list", domain)
  32. }