url_test.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. package policy
  2. import (
  3. "context"
  4. "errors"
  5. "net"
  6. "testing"
  7. )
  8. type resolver struct {
  9. ips []net.IPAddr
  10. err error
  11. }
  12. func (r resolver) LookupIPAddr(context.Context, string) ([]net.IPAddr, error) { return r.ips, r.err }
  13. func TestNavigationPolicy(t *testing.T) {
  14. ctx := context.Background()
  15. p := URLPolicy{Resolver: resolver{ips: []net.IPAddr{{IP: net.ParseIP("8.8.8.8")}}}, AllowOrigins: []string{"http://127.0.0.1:8000", "https://private.example"}}
  16. for _, raw := range []string{"https://example.org/path?q=test#section", "http://8.8.8.8/", "https://[2606:4700:4700::1111]/", "http://127.0.0.1:8000/path", "https://private.example:443/a"} {
  17. if _, e := p.Validate(ctx, raw); e != nil {
  18. t.Errorf("%s: %v", raw, e)
  19. }
  20. }
  21. for _, raw := range []string{"file:///etc/passwd", "javascript:alert(1)", "https://user:pass@example.org", "http://localhost/", "http://x.localhost/", "http://127.0.0.1:8001/", "http://10.0.0.1/", "http://169.254.169.254/", "http://100.64.1.1/", "http://192.0.2.1/", "http://[::1]/", "https://", "://bad"} {
  22. if _, e := p.Validate(ctx, raw); e == nil {
  23. t.Errorf("blocked URL accepted: %s", raw)
  24. }
  25. }
  26. }
  27. func TestDNSMustOnlyResolvePublicAddresses(t *testing.T) {
  28. for _, r := range []resolver{{err: errors.New("dns")}, {}, {ips: []net.IPAddr{{IP: net.ParseIP("8.8.8.8")}, {IP: net.ParseIP("10.0.0.1")}}}} {
  29. p := URLPolicy{Resolver: r}
  30. if _, e := p.Validate(context.Background(), "https://example.org"); e == nil {
  31. t.Fatal("unsafe DNS result accepted")
  32. }
  33. }
  34. if public(nil) || public(net.IPv4zero) || public(net.ParseIP("2001:db8::1")) {
  35. t.Fatal("non-public IP accepted")
  36. }
  37. }