Fix HTTP proxy authentication to support both preemptive and challenge-response auth (#134)

This commit is contained in:
Luiz Henrique Gomes Palácio 2024-09-03 17:21:40 -03:00 committed by GitHub
parent 5b7f822f17
commit 4a564b5ea2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

36
http.go
View file

@ -31,23 +31,23 @@ func (s *HTTPServer) authenticate(req *http.Request) (int, error) {
}
auth := req.Header.Get(proxyAuthHeaderKey)
if auth != "" {
enc := strings.TrimPrefix(auth, "Basic ")
str, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
return http.StatusNotAcceptable, fmt.Errorf("decode username and password failed: %w", err)
}
pairs := bytes.SplitN(str, []byte(":"), 2)
if len(pairs) != 2 {
return http.StatusLengthRequired, fmt.Errorf("username and password format invalid")
}
if s.auth.Valid(string(pairs[0]), string(pairs[1])) {
return 0, nil
}
return http.StatusUnauthorized, fmt.Errorf("username and password not matching")
if auth == "" {
return http.StatusProxyAuthRequired, fmt.Errorf(http.StatusText(http.StatusProxyAuthRequired))
}
return http.StatusProxyAuthRequired, fmt.Errorf(http.StatusText(http.StatusProxyAuthRequired))
enc := strings.TrimPrefix(auth, "Basic ")
str, err := base64.StdEncoding.DecodeString(enc)
if err != nil {
return http.StatusNotAcceptable, fmt.Errorf("decode username and password failed: %w", err)
}
pairs := bytes.SplitN(str, []byte(":"), 2)
if len(pairs) != 2 {
return http.StatusLengthRequired, fmt.Errorf("username and password format invalid")
}
if s.auth.Valid(string(pairs[0]), string(pairs[1])) {
return 0, nil
}
return http.StatusUnauthorized, fmt.Errorf("username and password not matching")
}
func (s *HTTPServer) handleConn(req *http.Request, conn net.Conn) (peer net.Conn, err error) {
@ -103,7 +103,11 @@ func (s *HTTPServer) serve(conn net.Conn) {
code, err := s.authenticate(req)
if err != nil {
_ = responseWith(req, code).Write(conn)
resp := responseWith(req, code)
if code == http.StatusProxyAuthRequired {
resp.Header.Set("Proxy-Authenticate", "Basic realm=\"Proxy\"")
}
_ = resp.Write(conn)
log.Println(err)
return
}