http/httpproxy: match http scheme when selecting http_proxy

Protocol specific proxies must match based on scheme.

If the https proxy is no configured, and the proxy for a https URL is
requested, no proxy should be returned.

Updates golang/go#40909

Change-Id: I62dfcf95d819c634e8f2862e891877a4eb55fca7
Reviewed-on: https://go-review.googlesource.com/c/net/+/249440
Trust: Brad Fitzpatrick <bradfitz@golang.org>
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/http/httpproxy/proxy.go b/http/httpproxy/proxy.go
index 163645b..1415b07 100644
--- a/http/httpproxy/proxy.go
+++ b/http/httpproxy/proxy.go
@@ -27,8 +27,7 @@
 type Config struct {
 	// HTTPProxy represents the value of the HTTP_PROXY or
 	// http_proxy environment variable. It will be used as the proxy
-	// URL for HTTP requests and HTTPS requests unless overridden by
-	// HTTPSProxy or NoProxy.
+	// URL for HTTP requests unless overridden by NoProxy.
 	HTTPProxy string
 
 	// HTTPSProxy represents the HTTPS_PROXY or https_proxy
@@ -129,8 +128,7 @@
 	var proxy *url.URL
 	if reqURL.Scheme == "https" {
 		proxy = cfg.httpsProxy
-	}
-	if proxy == nil {
+	} else if reqURL.Scheme == "http" {
 		proxy = cfg.httpProxy
 		if proxy != nil && cfg.CGI {
 			return nil, errors.New("refusing to use HTTP_PROXY value in CGI environment; see golang.org/s/cgihttpproxy")
diff --git a/http/httpproxy/proxy_test.go b/http/httpproxy/proxy_test.go
index 9951246..2a12dad 100644
--- a/http/httpproxy/proxy_test.go
+++ b/http/httpproxy/proxy_test.go
@@ -112,6 +112,18 @@
 	req:  "https://secure.tld/",
 	want: "https://secure.proxy.tld",
 }, {
+	cfg: httpproxy.Config{
+		HTTPProxy: "http.proxy.tld",
+	},
+	req:  "https://secure.tld/",
+	want: "<nil>",
+}, {
+	cfg: httpproxy.Config{
+		HTTPProxy: "http.proxy.tld",
+	},
+	req:  "ftp://insecure.tld/",
+	want: "<nil>",
+}, {
 	// Issue 16405: don't use HTTP_PROXY in a CGI environment,
 	// where HTTP_PROXY can be attacker-controlled.
 	cfg: httpproxy.Config{