Skip to content

Commit 0732180

Browse files
committed
test: add basic auth test
1 parent f0219f9 commit 0732180

File tree

1 file changed

+38
-3
lines changed

1 file changed

+38
-3
lines changed

proxy_test.go

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package antch
22

33
import (
4+
"encoding/base64"
45
"fmt"
56
"io"
67
"io/ioutil"
@@ -9,6 +10,7 @@ import (
910
"net/http/httptest"
1011
"net/http/httputil"
1112
"net/url"
13+
"strings"
1214
"sync"
1315
"testing"
1416
)
@@ -25,22 +27,55 @@ func testProxyHandler(t *testing.T, proxyURL *url.URL) {
2527
},
2628
}
2729

28-
handler := proxyHandler(http.ProxyURL(proxyURL), backMessageHandler(client))
30+
handler := ProxyMiddleware(http.ProxyURL(proxyURL))(backMessageHandler(client))
2931
req, _ := http.NewRequest("GET", ts.URL, nil)
3032
resp, err := handler.Send(req)
3133
if err != nil {
3234
t.Fatal(err)
3335
}
3436
defer resp.Body.Close()
35-
3637
b, err := ioutil.ReadAll(resp.Body)
3738
if err != nil {
3839
t.Fatalf("ReadAll: %v", err)
3940
}
4041
if g, e := string(b), "hello world"; g != e {
41-
t.Error("expected %s; got %s", e, g)
42+
t.Errorf("expected %s; got %s", e, g)
4243
}
4344
}
45+
46+
func TestHTTPAuthProxyHandler(t *testing.T) {
47+
// HTTP proxy server with authentication.
48+
var (
49+
username = "test"
50+
password = "test"
51+
)
52+
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
53+
if r.Method == "CONNECT" {
54+
auth := strings.SplitN(r.Header.Get("Proxy-Authorization"), " ", 2)
55+
if len(auth) != 2 && auth[0] != "Basic" {
56+
w.WriteHeader(401)
57+
return
58+
}
59+
payload, _ := base64.StdEncoding.DecodeString(auth[1])
60+
if pair := strings.Split(string(payload), ":"); len(pair) != 2 || !(pair[0] == username && pair[1] == password) {
61+
w.WriteHeader(401)
62+
return
63+
}
64+
}
65+
director := func(req *http.Request) {
66+
req.URL.Host = r.Host
67+
req.URL.Scheme = "http"
68+
}
69+
proxy := &httputil.ReverseProxy{Director: director}
70+
proxy.ServeHTTP(w, r)
71+
}))
72+
defer proxyServer.Close()
73+
74+
proxyURL, _ := url.Parse(proxyServer.URL)
75+
proxyURL.User = url.UserPassword(username, password)
76+
testProxyHandler(t, proxyURL)
77+
}
78+
4479
func TestHTTPProxyHandler(t *testing.T) {
4580
// HTTP proxy server.
4681
proxyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

0 commit comments

Comments
 (0)