TUN-1550: Add validation timeout for non-responsive origins

This commit is contained in:
Nick Vollmar 2019-02-27 16:47:00 -06:00
parent 073c5bfdaa
commit 6ca642e572
2 changed files with 37 additions and 1 deletions

View File

@ -5,6 +5,7 @@ import (
"net" "net"
"net/url" "net/url"
"strings" "strings"
"time"
"net/http" "net/http"
@ -14,7 +15,10 @@ import (
const defaultScheme = "http" const defaultScheme = "http"
var supportedProtocol = [2]string{"http", "https"} var (
supportedProtocol = [2]string{"http", "https"}
validationTimeout = time.Duration(30 * time.Second)
)
func ValidateHostname(hostname string) (string, error) { func ValidateHostname(hostname string) (string, error) {
if hostname == "" { if hostname == "" {
@ -149,6 +153,7 @@ func ValidateHTTPService(originURL string, hostname string, transport http.Round
CheckRedirect: func(req *http.Request, via []*http.Request) error { CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse return http.ErrUseLastResponse
}, },
Timeout: validationTimeout,
} }
initialRequest, err := http.NewRequest("GET", parsedURL.String(), nil) initialRequest, err := http.NewRequest("GET", parsedURL.String(), nil)

View File

@ -5,6 +5,7 @@ import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
"time"
"context" "context"
"crypto/tls" "crypto/tls"
@ -383,6 +384,36 @@ func TestValidateHTTPService_HTTP2HTTPS(t *testing.T) {
assert.Error(t, ValidateHTTPService(originURL, hostname, redirectClient.Transport)) assert.Error(t, ValidateHTTPService(originURL, hostname, redirectClient.Transport))
} }
// error path 3: origin URL is nonresponsive
func TestValidateHTTPService_NonResponsiveOrigin(t *testing.T) {
originURL := "https://127.0.0.1/"
hostname := "example.com"
oldValidationTimeout := validationTimeout
defer func() {
validationTimeout = oldValidationTimeout
}()
validationTimeout = 500 * time.Millisecond
server, client, err := createSecureMockServerAndClient(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "CONNECT" {
assert.Equal(t, "127.0.0.1:443", r.Host)
} else {
assert.Equal(t, hostname, r.Host)
}
time.Sleep(1 * time.Second)
w.WriteHeader(200)
}))
if !assert.NoError(t, err) {
t.FailNow()
}
defer server.Close()
err = ValidateHTTPService(originURL, hostname, client.Transport)
if err, ok := err.(net.Error); assert.True(t, ok) {
assert.True(t, err.Timeout())
}
}
type testRoundTripper func(req *http.Request) (*http.Response, error) type testRoundTripper func(req *http.Request) (*http.Response, error)
func (f testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { func (f testRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {